diff --git a/app/Config/Constants.php b/app/Config/Constants.php index d601d75..8f22519 100644 --- a/app/Config/Constants.php +++ b/app/Config/Constants.php @@ -101,6 +101,29 @@ define('DEFAULTS', [ 'DELIMITER_FILE' => "||", 'DELIMITER_ROLE' => ",", ]); +define('MESSAGES', [ + 'CREATED' => '생성되었습니다.', + 'UPDATED' => '수정되였습니다.', + 'DELETED' => '삭제되였습니다.', + 'SUCCESS' => '작업이 성공적으로 완료되었습니다.', + 'FAILED' => '작업이 실패하였습니다.', + 'NOT_FOUND' => '데이터가 존재하지 않습니다.', + 'NOT_AUTH' => '권한이 없습니다.', + 'NOT_LOGIN' => '로그인이 필요합니다.', + 'NOT_MATCH' => '데이터가 일치하지 않습니다.', + 'NOT_EMPTY' => '데이터가 비어있습니다.', + 'NOT_UNIQUE' => '중복된 데이터가 존재합니다.', + 'NOT_DELETE' => '삭제할 수 없는 데이터가 존재합니다.', + 'NOT_UPDATE' => '수정할 수 없는 데이터가 존재합니다.', + 'NOT_CREATE' => '생성할 수 없는 데이터가 존재합니다.', + 'NOT_SYNC' => '동기화할 수 없는 데이터가 존재합니다.', + 'NOT_SYNC_RESULT' => '동기화 결과가 실패하였습니다.', + 'NOT_SYNC_SUCCESS' => '동기화 결과가 성공하였습니다.', + 'NOT_SYNC_ERROR' => '동기화 결과가 실패하였습니다.', + 'NOT_SYNC_NOTHING' => '동기화할 데이터가 없습니다.', + 'NOT_SYNC_NOTHING_RESULT' => '동기화 결과가 없습니다.', + 'NOT_SYNC_NOTHING_ERROR' => '동기화 결과가 없습니다.', +]); //URL define('URLS', [ 'LOGIN' => '/user/login', diff --git a/app/Config/Routes.php b/app/Config/Routes.php index c085c4e..dfc7233 100644 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -74,6 +74,10 @@ $routes->group('admin', ['namespace' => 'App\Controllers\Admin', 'filter' => 'au $routes->post('batchjob_delete', 'MapurlController::batchjob_delete'); $routes->get('download/(:alpha)', 'MapurlController::download/$1'); }); + $routes->group('mylog', ['namespace' => 'App\Controllers\Admin'], function ($routes) { + $routes->get('/', 'MyLogController::index'); + $routes->get('view/(:num)', 'MyLogController::view/$1'); + }); $routes->group('cloudflare', ['namespace' => 'App\Controllers\Admin\Cloudflare', 'filter' => 'authFilter:cloudflare'], function ($routes) { $routes->group('auth', ['namespace' => 'App\Controllers\Admin\Cloudflare'], function ($routes) { $routes->get('/', 'AuthController::index'); diff --git a/app/Controllers/Admin/AdminController.php b/app/Controllers/Admin/AdminController.php index 2cae6ec..f44d3a7 100644 --- a/app/Controllers/Admin/AdminController.php +++ b/app/Controllers/Admin/AdminController.php @@ -2,12 +2,12 @@ namespace App\Controllers\Admin; -use App\Controllers\MVController; +use App\Controllers\CommonController; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; use Psr\Log\LoggerInterface; -abstract class AdminController extends MVController +abstract class AdminController extends CommonController { public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) { diff --git a/app/Controllers/Admin/Cloudflare/AccountController.php b/app/Controllers/Admin/Cloudflare/AccountController.php index 8cdac95..f2c0d54 100644 --- a/app/Controllers/Admin/Cloudflare/AccountController.php +++ b/app/Controllers/Admin/Cloudflare/AccountController.php @@ -3,7 +3,6 @@ namespace App\Controllers\Admin\Cloudflare; use App\Helpers\Cloudflare\AccountHelper; -use App\Models\Cloudflare\AccountModel; use App\Services\Cloudflare\AccountService; use CodeIgniter\HTTP\DownloadResponse; use CodeIgniter\HTTP\RedirectResponse; @@ -13,20 +12,12 @@ use Psr\Log\LoggerInterface; class AccountController extends CloudflareController { - private $_auth_entity = null; public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) { parent::initController($request, $response, $logger); - $this->title = lang("{$this->getService()->class_path}.title"); + $this->title = lang("{$this->getService()->getClassPath()}.title"); $this->helper = new AccountHelper(); } - protected function getModel(): AccountModel - { - if ($this->_model === null) { - $this->_model = new AccountModel(); - } - return $this->_model; - } protected function getService(): AccountService { if ($this->service === null) { @@ -37,7 +28,7 @@ class AccountController extends CloudflareController protected function getFormFieldOption(string $field, array $options = []): array { switch ($field) { - case $this->getModel()::PARENT: + case $this->getService()->getModel()::PARENT: // $this->getAuthModel()->where('status', DEFAULTS['STATUS']); $options[$field] = $this->getAuthModel()->getFormFieldOption($field); // echo $this->getAuthModel()->getLastQuery(); @@ -49,15 +40,6 @@ class AccountController extends CloudflareController } return $options; } - private function init(string $action, array $fields = []): void - { - $this->action = $action; - $this->fields = count($fields) ? $fields : [$this->getModel()::PARENT, $this->getModel()::TITLE, 'type', 'status', 'updated_at', 'created_at']; - $this->field_rules = $this->getModel()->getFieldRules($this->action, $this->fields); - $this->filter_fields = [$this->getModel()::PARENT, 'type', 'status']; - $this->field_options = $this->getFormFieldOptions($this->filter_fields); - $this->batchjob_fields = []; - } //View public function view(string $uid): RedirectResponse|string { diff --git a/app/Controllers/Admin/Cloudflare/AuditLogController.php b/app/Controllers/Admin/Cloudflare/AuditLogController.php index d6c5b88..fb16e48 100644 --- a/app/Controllers/Admin/Cloudflare/AuditLogController.php +++ b/app/Controllers/Admin/Cloudflare/AuditLogController.php @@ -17,16 +17,9 @@ class AuditLogController extends CloudflareController public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) { parent::initController($request, $response, $logger); - $this->title = lang("{$this->getService()->class_path}.title"); + $this->title = lang("{$this->getService()->getClassPath()}.title"); $this->helper = new AuditLogHelper(); } - protected function getModel(): AuditLogModel - { - if ($this->_model === null) { - $this->_model = new AuditLogModel(); - } - return $this->_model; - } protected function getService(): AuditLogService { if ($this->service === null) { @@ -34,26 +27,17 @@ class AuditLogController extends CloudflareController } return $this->service; } - private function init(string $action, array $fields = []): void - { - $this->action = $action; - $this->fields = count($fields) ? $fields : ['zone_name', $this->getModel()::TITLE, 'action_info', 'actor', 'interface', 'status', 'updated_at', 'created_at']; - $this->field_rules = $this->getModel()->getFieldRules($this->action, $this->fields); - $this->filter_fields = []; - $this->field_options = $this->getFormFieldOptions($this->filter_fields); - $this->batchjob_fields = []; - } //View public function view(string $uid): RedirectResponse|string { - $this->init(__FUNCTION__, ['zone_name', $this->getModel()::TITLE, 'actor', 'action_info', 'interface', 'meta', 'resource', 'status', 'updated_at', 'created_at']); + $this->init(__FUNCTION__, ['zone_name', $this->getService()->getModel()::TITLE, 'actor', 'action_info', 'interface', 'meta', 'resource', 'status', 'updated_at', 'created_at']); return $this->view_procedure($uid); } // 리스트 protected function list_entitys_process(): array { //기본Soring처리 - $this->getModel()->orderBy("created_at DESC,zone_name ASC"); + $this->getService()->getModel()->orderBy("created_at DESC,zone_name ASC"); return parent::list_entitys_process(); } public function index(): string diff --git a/app/Controllers/Admin/Cloudflare/AuthController.php b/app/Controllers/Admin/Cloudflare/AuthController.php index e430495..cd1ff28 100644 --- a/app/Controllers/Admin/Cloudflare/AuthController.php +++ b/app/Controllers/Admin/Cloudflare/AuthController.php @@ -3,7 +3,6 @@ namespace App\Controllers\Admin\Cloudflare; use App\Helpers\Cloudflare\AuthHelper; -use App\Models\Cloudflare\AuthModel; use App\Services\Cloudflare\AuthService; use CodeIgniter\HTTP\DownloadResponse; use CodeIgniter\HTTP\RedirectResponse; @@ -16,16 +15,9 @@ class AuthController extends CloudflareController public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) { parent::initController($request, $response, $logger); - $this->title = lang("{$this->getService()->class_path}.title"); + $this->title = lang("{$this->getService()->getClassPath()}.title"); $this->helper = new AuthHelper(); } - protected function getModel(): AuthModel - { - if ($this->_model === null) { - $this->_model = new AuthModel(); - } - return $this->_model; - } protected function getService(): AuthService { if ($this->service === null) { @@ -33,35 +25,26 @@ class AuthController extends CloudflareController } return $this->service; } - private function init(string $action, array $fields = []): void - { - $this->action = $action; - $this->fields = count($fields) ? $fields : [$this->getModel()::TITLE, 'authkey', 'status', 'updated_at', 'created_at']; - $this->field_rules = $this->getModel()->getFieldRules($this->action, $this->fields); - $this->filter_fields = ['status']; - $this->field_options = $this->getFormFieldOptions($this->filter_fields); - $this->batchjob_fields = ['status']; - } //생성 public function create_form(): RedirectResponse|string { - $this->init('create', [$this->getModel()::TITLE, 'authkey', 'status']); + $this->init('create', [$this->getService()->getModel()::TITLE, 'authkey', 'status']); return $this->create_form_procedure(); } public function create(): RedirectResponse|string { - $this->init(__FUNCTION__, [$this->getModel()::TITLE, 'authkey', 'status']); + $this->init(__FUNCTION__, [$this->getService()->getModel()::TITLE, 'authkey', 'status']); return $this->create_procedure(); } //수정 public function modify_form(int $uid): RedirectResponse|string { - $this->init('modify', [$this->getModel()::TITLE, 'authkey', 'status']); + $this->init('modify', [$this->getService()->getModel()::TITLE, 'authkey', 'status']); return $this->modify_form_procedure($uid); } public function modify(int $uid): RedirectResponse|string { - $this->init(__FUNCTION__, [$this->getModel()::TITLE, 'authkey', 'status']); + $this->init(__FUNCTION__, [$this->getService()->getModel()::TITLE, 'authkey', 'status']); return $this->modify_procedure($uid); } //단일필드작업 diff --git a/app/Controllers/Admin/Cloudflare/CloudflareController.php b/app/Controllers/Admin/Cloudflare/CloudflareController.php index 3076946..e6f41a7 100644 --- a/app/Controllers/Admin/Cloudflare/CloudflareController.php +++ b/app/Controllers/Admin/Cloudflare/CloudflareController.php @@ -11,6 +11,7 @@ use CodeIgniter\HTTP\RedirectResponse; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; use Psr\Log\LoggerInterface; +use App\Services\MyLogService; abstract class CloudflareController extends AdminController { @@ -18,6 +19,7 @@ abstract class CloudflareController extends AdminController private $_accountModel = null; private $_zoneModel = null; private $_recordModel = null; + public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) { parent::initController($request, $response, $logger); @@ -53,42 +55,56 @@ abstract class CloudflareController extends AdminController return $this->_recordModel; } protected function sync_process(string $uid): void {} + protected function sync_process_result($message): RedirectResponse|string + { + return redirect()->to($this->myauth->popPreviousUrl())->with('error', $message); + } final protected function sync_procedure(string $uid): RedirectResponse { //Transaction Start - $this->getModel()->transStart(); + $this->getService()->getModel()->transStart(); try { $this->sync_process($uid); - $this->message = "{$this->getService()->class_name}: 동기화작업을 완료하였습니다."; - $this->getModel()->transCommit(); - log_message("notice", __FUNCTION__ . $this->message); - // 이전 URL로 리다이렉트 - return redirect()->to($this->myauth->popPreviousUrl())->with('error', $this->message); + if ($this->isMyLog) { + MyLogService::save($this->getService()->getClassName(), __FUNCTION__, MESSAGES["SUCCESS"], $this->myauth->getUIDByAuthInfo()); + } + $this->getService()->getModel()->transCommit(); + return $this->sync_process_result(MESSAGES["SUCCESS"]); } catch (\Exception $e) { //Transaction Rollback - $this->getModel()->transRollback(); - log_message("error", $e->getMessage()); - return redirect()->back()->with('error', __FUNCTION__ . " 실패하였습니다.\n" . $e->getMessage()); + $this->getService()->getModel()->transRollback(); + if ($this->isMyLog) { + MyLogService::add("error", $e->getMessage()); + MyLogService::save($this->getService()->getClassName(), __FUNCTION__, MESSAGES["FAILED"], $this->myauth->getUIDByAuthInfo()); + } + return redirect()->back()->with('error', $e->getMessage()); } } protected function reload_process(mixed $uid): void {} + protected function reload_process_result($message): RedirectResponse|string + { + return redirect()->to($this->myauth->popPreviousUrl())->with('error', $message); + } final protected function reload_procedure(mixed $uid): RedirectResponse { //Transaction Start - $this->getModel()->transStart(); + $this->getService()->getModel()->transStart(); try { $this->reload_process($uid); - $this->message = "{$this->getService()->class_name}: Reload 작업이 완료되었습니다."; - $this->getModel()->transCommit(); - log_message("notice", __FUNCTION__ . $this->message); - // 이전 URL로 리다이렉트 - return redirect()->to($this->myauth->popPreviousUrl())->with('error', $this->message); + if ($this->isMyLog) { + MyLogService::save($this->getService()->getClassName(), __FUNCTION__, MESSAGES["SUCCESS"], $this->myauth->getUIDByAuthInfo()); + } + $this->getService()->getModel()->transCommit(); + return $this->reload_process_result(MESSAGES["SUCCESS"]); } catch (\Exception $e) { //Transaction Rollback - $this->getModel()->transRollback(); - log_message("error", $e->getMessage()); - return redirect()->back()->with('error', __FUNCTION__ . " 실패하였습니다.\n" . $e->getMessage()); + $this->getService()->getModel()->transRollback(); + if ($this->isMyLog) { + MyLogService::add("error", $e->getMessage()); + MyLogService::save($this->getService()->getClassName(), __FUNCTION__, MESSAGES["FAILED"], $this->myauth->getUIDByAuthInfo()); + } + return redirect()->back()->with('error', $e->getMessage()); } } } diff --git a/app/Controllers/Admin/Cloudflare/FirewallController.php b/app/Controllers/Admin/Cloudflare/FirewallController.php index 1ff9ea2..ff68622 100644 --- a/app/Controllers/Admin/Cloudflare/FirewallController.php +++ b/app/Controllers/Admin/Cloudflare/FirewallController.php @@ -7,7 +7,6 @@ use CodeIgniter\HTTP\RedirectResponse; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; use Psr\Log\LoggerInterface; -use App\Models\Cloudflare\FirewallModel; use App\Services\Cloudflare\FirewallService; use App\Helpers\Cloudflare\FirewallHelper; use App\Models\Cloudflare\ZoneModel; @@ -18,15 +17,9 @@ class FirewallController extends CloudflareController public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) { parent::initController($request, $response, $logger); - $this->title = lang("{$this->getService()->class_path}.title"); + $this->title = lang("{$this->getService()->getClassPath()}.title"); $this->helper = new FirewallHelper(); - } - final protected function getModel(): FirewallModel - { - if ($this->model === null) { - $this->model = new FirewallModel(); - } - return $this->model; + $this->isMyLog = env("mylog.cloudflare.firewall.use") == "true"; //MyLogService 사용여부 } protected function getService(): FirewallService { @@ -38,7 +31,7 @@ class FirewallController extends CloudflareController protected function getFormFieldOption(string $field, array $options = []): array { switch ($field) { - case $this->getModel()::PARENT: + case $this->getService()->getModel()::PARENT: // $this->getZoneModel()->where('status', 'active'); $options[$field] = $this->getZoneModel()->getFormFieldOption($field); // echo $this->getAccountModel()->getLastQuery(); @@ -50,23 +43,13 @@ class FirewallController extends CloudflareController } return $options; } - //전송된 데이터 - private function init(string $action, array $fields = []): void - { - $this->action = $action; - $this->fields = count($fields) ? $fields : [$this->getModel()::PARENT, 'mode', 'description', 'expression', 'enabled', 'updated_at', 'created_at']; - $this->field_rules = $this->getModel()->getFieldRules($this->action, $this->fields); - $this->filter_fields = [$this->getModel()::PARENT, 'mode', 'enabled']; - $this->field_options = $this->getFormFieldOptions($this->filter_fields); - $this->batchjob_fields = []; - } //수정 (modify,toggle,batchjob사용) protected function modify_process(mixed $uid): void { //DB작업도 Socket에서 다 처리하므로 parent::modify_process($uid)하면 않됨 $this->formDatas = $this->modify_validate($this->action, $this->fields); //자신정보정의 - $this->entity = $this->getModel()->getEntityByPK($uid); + $this->entity = $this->getService()->getModel()->getEntityByPK($uid); if ($this->entity === null) { throw new \Exception("{$uid} 정보를 찾을수 없습니다."); } @@ -91,29 +74,29 @@ class FirewallController extends CloudflareController { $this->list_condition_process(); //기본Soring처리 - $this->getModel()->orderBy(ZoneModel::TABLE . "." . ZoneModel::TITLE . " ASC ," . $this->getModel()::TITLE . " ASC"); + $this->getService()->getModel()->orderBy(ZoneModel::TABLE . "." . ZoneModel::TITLE . " ASC ," . $this->getService()->getModel()::TITLE . " ASC"); //Sorting 처리 $this->order_field = $this->request->getVar('order_field') ?: DEFAULTS['EMPTY']; $this->order_value = $this->request->getVar('order_value') ?: DEFAULTS['EMPTY']; if ($this->order_field !== DEFAULTS['EMPTY'] && $this->order_value !== DEFAULTS['EMPTY']) { - $this->getModel()->orderBy(sprintf( + $this->getService()->getModel()->orderBy(sprintf( "%s.%s %s", - $this->getModel()::TABLE, + $this->getService()->getModel()::TABLE, $this->order_field, $this->order_value )); } - $this->getModel()->limit($this->per_page, $this->page * $this->per_page - $this->per_page); + $this->getService()->getModel()->limit($this->per_page, $this->page * $this->per_page - $this->per_page); //Join을 해서 도메인부터 Sorting하기위함 - $this->getModel()->join(ZoneModel::TABLE, sprintf( + $this->getService()->getModel()->join(ZoneModel::TABLE, sprintf( "%s.%s=%s.%s", - $this->getModel()::TABLE, - $this->getModel()::PARENT, + $this->getService()->getModel()::TABLE, + $this->getService()->getModel()::PARENT, ZoneModel::TABLE, ZoneModel::PK )); - $entitys = $this->getModel()->select($this->getModel()::TABLE . '.*')->findAll(); - log_message("debug", $this->getModel()->getLastQuery()); + $entitys = $this->getService()->getModel()->select($this->getService()->getModel()::TABLE . '.*')->findAll(); + log_message("debug", $this->getService()->getModel()->getLastQuery()); return $entitys; } public function index(): string diff --git a/app/Controllers/Admin/Cloudflare/RecordController.php b/app/Controllers/Admin/Cloudflare/RecordController.php index 5dddea0..223b6be 100644 --- a/app/Controllers/Admin/Cloudflare/RecordController.php +++ b/app/Controllers/Admin/Cloudflare/RecordController.php @@ -8,7 +8,6 @@ use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; use Psr\Log\LoggerInterface; use App\Helpers\Cloudflare\RecordHelper; -use App\Models\Cloudflare\RecordModel; use App\Services\Cloudflare\RecordService; use App\Models\Cloudflare\ZoneModel; @@ -18,15 +17,9 @@ class RecordController extends CloudflareController public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) { parent::initController($request, $response, $logger); - $this->title = lang("{$this->getService()->class_path}.title"); + $this->title = lang("{$this->getService()->getClassPath()}.title"); $this->helper = new RecordHelper(); - } - final protected function getModel(): RecordModel - { - if ($this->model === null) { - $this->model = new RecordModel(); - } - return $this->model; + $this->isMyLog = env("mylog.cloudflare.record.use") == "true"; //MyLogService 사용여부 } protected function getService(): RecordService { @@ -38,7 +31,7 @@ class RecordController extends CloudflareController protected function getFormFieldOption(string $field, array $options = []): array { switch ($field) { - case $this->getModel()::PARENT: + case $this->getService()->getModel()::PARENT: // $this->getZoneModel()->where('status', 'active'); $options[$field] = $this->getZoneModel()->getFormFieldOption($field); // echo $this->getAccountModel()->getLastQuery(); @@ -50,22 +43,13 @@ class RecordController extends CloudflareController } return $options; } - private function init(string $action, array $fields = []): void - { - $this->action = $action; - $this->fields = count($fields) ? $fields : [$this->getModel()::PARENT, 'host', 'type', 'content', 'proxied', 'updated_at', 'created_at']; - $this->field_rules = $this->getModel()->getFieldRules($this->action, $this->fields); - $this->filter_fields = [$this->getModel()::PARENT, 'type', 'proxied', 'fixed']; - $this->field_options = $this->getFormFieldOptions($this->filter_fields); - $this->batchjob_fields = ['type', 'content', 'proxied']; - } //생성 public function create_form(): RedirectResponse|string { - $this->init('create', [$this->getModel()::PARENT, 'hosts', 'type', 'content', 'proxied']); - $this->field_rules = $this->getModel()->getFieldRules($this->action, $this->fields); + $this->init('create', [$this->getService()->getModel()::PARENT, 'hosts', 'type', 'content', 'proxied']); + $this->field_rules = $this->getService()->getModel()->getFieldRules($this->action, $this->fields); //부모데이터 정의 - $parent_field = $this->getModel()::PARENT; + $parent_field = $this->getService()->getModel()::PARENT; $this->$parent_field = $this->request->getVar($parent_field) ?: DEFAULTS["EMPTY"]; return $this->create_form_procedure(); } @@ -93,9 +77,9 @@ class RecordController extends CloudflareController } //Socket처리 //부모데이터정의 - $this->_zone_entity = $this->getZoneModel()->getEntityByPK($this->formDatas[$this->getModel()::PARENT]); + $this->_zone_entity = $this->getZoneModel()->getEntityByPK($this->formDatas[$this->getService()->getModel()::PARENT]); if ($this->_zone_entity === null) { - throw new \Exception("Zone: [{$this->formDatas[$this->getModel()::PARENT]}] 정보를 찾을수 없습니다."); + throw new \Exception("Zone: [{$this->formDatas[$this->getService()->getModel()::PARENT]}] 정보를 찾을수 없습니다."); } $entitys = []; foreach ($hosts as $host) { @@ -110,20 +94,20 @@ class RecordController extends CloudflareController } $this->entitys = $entitys; } - protected function create_process_result(): RedirectResponse|string + protected function create_process_result($message): RedirectResponse|string { $this->init(__FUNCTION__); helper(['form']); $this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []]; return view( - strtolower($this->view_path . $this->class_path . "/create_result"), + strtolower($this->view_path . $this->getService()->getClassPath() . "/create_result"), data: ['viewDatas' => $this->getViewDatas()] ); } public function create(): RedirectResponse|string { - $this->init(__FUNCTION__, [$this->getModel()::PARENT, 'hosts', 'type', 'content', 'proxied']); - $this->field_rules = $this->getModel()->getFieldRules($this->action, $this->fields); + $this->init(__FUNCTION__, [$this->getService()->getModel()::PARENT, 'hosts', 'type', 'content', 'proxied']); + $this->field_rules = $this->getService()->getModel()->getFieldRules($this->action, $this->fields); return $this->create_procedure(); } //수정 (modify,toggle,batchjob사용) @@ -132,7 +116,7 @@ class RecordController extends CloudflareController //DB작업도 Socket에서 다 처리하므로 parent::modify_process($uid)하면 않됨 $this->formDatas = $this->modify_validate($this->action, $this->fields); //자신정보정의 - $this->entity = $this->getModel()->getEntityByPK($uid); + $this->entity = $this->getService()->getModel()->getEntityByPK($uid); if ($this->entity === null) { throw new \Exception("{$uid} 정보를 찾을수 없습니다."); } @@ -167,7 +151,7 @@ class RecordController extends CloudflareController { //DB작업도 Socket에서 다 처리하므로 parent::delete_process($uid)하면 않됨 //자신정보정의 - $this->entity = $this->getModel()->getEntityByPK($uid); + $this->entity = $this->getService()->getModel()->getEntityByPK($uid); if ($this->entity === null) { throw new \Exception("{$uid} 정보를 찾을수 없습니다."); } @@ -183,12 +167,12 @@ class RecordController extends CloudflareController protected function list_entitys_process(): array { //기본Soring처리 - $this->getModel()->orderBy(ZoneModel::TABLE . "." . ZoneModel::TITLE . " ASC ," . $this->getModel()::TITLE . " ASC"); + $this->getService()->getModel()->orderBy(ZoneModel::TABLE . "." . ZoneModel::TITLE . " ASC ," . $this->getService()->getModel()::TITLE . " ASC"); //Join을 해서 도메인부터 Sorting하기위함 - $this->getModel()->join(ZoneModel::TABLE, sprintf( + $this->getService()->getModel()->join(ZoneModel::TABLE, sprintf( "%s.%s=%s.%s", - $this->getModel()::TABLE, - $this->getModel()::PARENT, + $this->getService()->getModel()::TABLE, + $this->getService()->getModel()::PARENT, ZoneModel::TABLE, ZoneModel::PK )); @@ -209,7 +193,7 @@ class RecordController extends CloudflareController protected function sync_process(string $uid): void { //자신정보정의 - $this->entity = $this->getModel()->getEntityByPK($uid); + $this->entity = $this->getService()->getModel()->getEntityByPK($uid); if ($this->entity === null) { throw new \Exception("{$uid} 정보를 찾을수 없습니다."); } diff --git a/app/Controllers/Admin/Cloudflare/ZoneController.php b/app/Controllers/Admin/Cloudflare/ZoneController.php index d6e04d3..87c9b12 100644 --- a/app/Controllers/Admin/Cloudflare/ZoneController.php +++ b/app/Controllers/Admin/Cloudflare/ZoneController.php @@ -4,7 +4,6 @@ namespace App\Controllers\Admin\Cloudflare; use App\Helpers\Cloudflare\ZoneHelper; use App\Models\Cloudflare\AccountModel; -use App\Models\Cloudflare\ZoneModel; use App\Services\Cloudflare\RecordService; use App\Services\Cloudflare\ZoneService; use CodeIgniter\HTTP\DownloadResponse; @@ -19,15 +18,9 @@ class ZoneController extends CloudflareController public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) { parent::initController($request, $response, $logger); - $this->title = lang("{$this->getService()->class_path}.title");; + $this->title = lang("{$this->getService()->getClassPath()}.title");; $this->helper = new ZoneHelper(); - } - protected function getModel(): ZoneModel - { - if ($this->_model === null) { - $this->_model = new ZoneModel(); - } - return $this->_model; + $this->isMyLog = env("mylog.cloudflare.zone.use") == "true"; //MyLogService 사용여부 } protected function getService(): ZoneService { @@ -39,7 +32,7 @@ class ZoneController extends CloudflareController protected function getFormFieldOption(string $field, array $options = []): array { switch ($field) { - case $this->getModel()::PARENT: + case $this->getService()->getModel()::PARENT: // $this->getAccountModel()->where('status', DEFAULTS['STATUS']); $options[$field] = $this->getAccountModel()->getFormFieldOption($field); // echo $this->getAccountModel()->getLastQuery(); @@ -55,24 +48,15 @@ class ZoneController extends CloudflareController } return $options; } - private function init(string $action, array $fields = []): void - { - $this->action = $action; - $this->fields = count($fields) ? $fields : [$this->getModel()::PARENT, $this->getModel()::TITLE, 'name_servers', 'original_name_servers', 'plan', 'development_mode', 'ipv6', 'security_level', 'ssl_mode', 'always_use_https', 'status', 'updated_at', 'created_at']; - $this->field_rules = $this->getModel()->getFieldRules($this->action, $this->fields); - $this->filter_fields = [$this->getModel()::PARENT, 'plan', 'development_mode', 'ipv6', 'security_level', 'ssl_mode', 'always_use_https']; - $this->field_options = $this->getFormFieldOptions($this->filter_fields); - $this->batchjob_fields = ['development_mode', 'ipv6', 'security_level', 'ssl_mode', 'always_use_https']; - } //생성 public function create_form(): RedirectResponse|string { - $this->init('create', [$this->getModel()::PARENT, 'domains', 'hosts', 'type', 'content', 'proxied']); - $this->field_rules = $this->getModel()->getFieldRules($this->action, $this->fields); - $this->filter_fields = [$this->getModel()::PARENT, 'type', 'proxied']; + $this->init('create', [$this->getService()->getModel()::PARENT, 'domains', 'hosts', 'type', 'content', 'proxied']); + $this->field_rules = $this->getService()->getModel()->getFieldRules($this->action, $this->fields); + $this->filter_fields = [$this->getService()->getModel()::PARENT, 'type', 'proxied']; $this->field_options = $this->getFormFieldOptions($this->filter_fields); //부모데이터 정의 - $parent_field = $this->getModel()::PARENT; + $parent_field = $this->getService()->getModel()::PARENT; $this->$parent_field = $this->request->getVar($parent_field) ?: DEFAULTS["EMPTY"]; return $this->create_form_procedure(); } @@ -81,9 +65,9 @@ class ZoneController extends CloudflareController //DB작업도 Socket에서 다 처리하므로 parent::create_process()하면 않됨 $this->formDatas = $this->create_validate($this->action, $this->fields); //부모데이터 정의 - $this->_account_entity = $this->getAccountModel()->getEntityByPK($this->formDatas[$this->getModel()::PARENT]); + $this->_account_entity = $this->getAccountModel()->getEntityByPK($this->formDatas[$this->getService()->getModel()::PARENT]); if ($this->_account_entity === null) { - throw new \Exception("Account: [{$this->formDatas[$this->getModel()::PARENT]}] 정보를 찾을수 없습니다."); + throw new \Exception("Account: [{$this->formDatas[$this->getService()->getModel()::PARENT]}] 정보를 찾을수 없습니다."); } //데이터검증 @@ -105,7 +89,7 @@ class ZoneController extends CloudflareController throw new \Exception("{$cnt}번째 : [{$domain}]는 도메인명 형식에 맞지 않습니다."); } //도메인명이 해당계정의 유일한 도메인인지 확인 - if (!$this->getModel()->isUniqueDomain($this->_account_entity, $domain)) { + if (!$this->getService()->getModel()->isUniqueDomain($this->_account_entity, $domain)) { throw new \Exception("{$cnt}번째 : [{$domain}]는 이미 등록된 도메인입니다."); } $cnt++; @@ -146,21 +130,21 @@ class ZoneController extends CloudflareController } $this->entitys = $entitys; } - protected function create_process_result(): RedirectResponse|string + protected function create_process_result($message): RedirectResponse|string { $this->init(__FUNCTION__); helper(['form']); $this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []]; return view( - strtolower($this->view_path . $this->class_path . "/create_result"), + strtolower($this->view_path . $this->getService()->getClassPath() . "/create_result"), data: ['viewDatas' => $this->getViewDatas()] ); } public function create(): RedirectResponse|string { - $this->init(__FUNCTION__, [$this->getModel()::PARENT, 'domains', 'hosts', 'type', 'content', 'proxied']); - $this->field_rules = $this->getModel()->getFieldRules($this->action, $this->fields); - $this->filter_fields = [$this->getModel()::PARENT, 'type', 'proxied']; + $this->init(__FUNCTION__, [$this->getService()->getModel()::PARENT, 'domains', 'hosts', 'type', 'content', 'proxied']); + $this->field_rules = $this->getService()->getModel()->getFieldRules($this->action, $this->fields); + $this->filter_fields = [$this->getService()->getModel()::PARENT, 'type', 'proxied']; $this->field_options = $this->getFormFieldOptions($this->filter_fields); return $this->create_procedure(); } @@ -170,7 +154,7 @@ class ZoneController extends CloudflareController //DB작업도 Socket에서 다 처리하므로 parent::modify_process($uid)하면 않됨 $this->formDatas = $this->modify_validate($this->action, $this->fields); //자신정보정의 - $this->entity = $this->getModel()->getEntityByPK($uid); + $this->entity = $this->getService()->getModel()->getEntityByPK($uid); if ($this->entity === null) { throw new \Exception("{$uid} 정보를 찾을수 없습니다."); } @@ -205,7 +189,7 @@ class ZoneController extends CloudflareController { //DB작업도 Socket에서 다 처리하므로 parent::delete_process($uid)하면 않됨 //자신정보정의 - $this->entity = $this->getModel()->getEntityByPK($uid); + $this->entity = $this->getService()->getModel()->getEntityByPK($uid); if ($this->entity === null) { throw new \Exception("{$uid} 정보를 찾을수 없습니다."); } @@ -227,12 +211,12 @@ class ZoneController extends CloudflareController protected function list_entitys_process(): array { //기본Soring처리 - $this->getModel()->orderBy(orderBy: AccountModel::TABLE . "." . AccountModel::TITLE . " ASC ," . $this->getModel()::TITLE . " ASC"); + $this->getService()->getModel()->orderBy(orderBy: AccountModel::TABLE . "." . AccountModel::TITLE . " ASC ," . $this->getService()->getModel()::TITLE . " ASC"); //Join을 해서 Account부터 Sorting하기위함 - $this->getModel()->join(AccountModel::TABLE, sprintf( + $this->getService()->getModel()->join(AccountModel::TABLE, sprintf( "%s.%s=%s.%s", - $this->getModel()::TABLE, - $this->getModel()::PARENT, + $this->getService()->getModel()::TABLE, + $this->getService()->getModel()::PARENT, AccountModel::TABLE, AccountModel::PK )); @@ -253,7 +237,7 @@ class ZoneController extends CloudflareController protected function sync_process(mixed $uid): void { //자신정보정의 - $this->entity = $this->getModel()->getEntityByPK($uid); + $this->entity = $this->getService()->getModel()->getEntityByPK($uid); if ($this->entity === null) { throw new \Exception("{$uid} 정보를 찾을수 없습니다."); } diff --git a/app/Controllers/Admin/Home.php b/app/Controllers/Admin/Home.php index eca7fea..781cc4c 100644 --- a/app/Controllers/Admin/Home.php +++ b/app/Controllers/Admin/Home.php @@ -2,13 +2,14 @@ namespace App\Controllers\Admin; -use App\Controllers\CommonController; -use Psr\Log\LoggerInterface; -use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\HTTP\RequestInterface; -use App\Helpers\CommonHelper; +use CodeIgniter\HTTP\ResponseInterface; +use Psr\Log\LoggerInterface; -class Home extends CommonController +use App\Helpers\CommonHelper; +use App\Services\UserService; + +class Home extends AdminController { public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) { @@ -19,6 +20,13 @@ class Home extends CommonController $this->title = "관리자페이지 메인"; $this->helper = new CommonHelper(); } + protected function getService(): UserService + { + if ($this->service === null) { + $this->service = new UserService(); + } + return $this->service; + } public function index(): string { helper(['form']); diff --git a/app/Controllers/Admin/MapurlController.php b/app/Controllers/Admin/MapurlController.php index ad443aa..2b51572 100644 --- a/app/Controllers/Admin/MapurlController.php +++ b/app/Controllers/Admin/MapurlController.php @@ -3,7 +3,6 @@ namespace App\Controllers\Admin; use App\Helpers\MapurlHelper; -use App\Models\MapurlModel; use App\Services\MapurlService; use CodeIgniter\HTTP\DownloadResponse; use CodeIgniter\HTTP\RedirectResponse; @@ -16,17 +15,10 @@ class MapurlController extends AdminController public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) { parent::initController($request, $response, $logger); - $this->title = lang("{$this->getService()->class_path}.title"); + $this->title = lang("{$this->getService()->getClassPath()}.title"); $this->helper = new MapurlHelper(); + $this->isMyLog = env("mylog.mapurl.use") == "true"; //MyLogService 사용여부 } - protected function getModel(): MapurlModel - { - if ($this->_model === null) { - $this->_model = new MapurlModel(); - } - return $this->_model; - } - protected function getService(): MapurlService { if ($this->service === null) { @@ -34,22 +26,13 @@ class MapurlController extends AdminController } return $this->service; } - private function init(string $action, array $fields = []): void - { - $this->action = $action; - $this->fields = count($fields) ? $fields : [$this->getModel()::TITLE, 'newurl', 'status', 'updated_at', 'created_at']; - $this->field_rules = $this->getModel()->getFieldRules($this->action, $this->fields); - $this->filter_fields = ['status']; - $this->field_options = $this->getFormFieldOptions($this->filter_fields); - $this->batchjob_fields = ['status']; - } private function remaping_process(): void { //모든 필요한 FormOption등 조기화작업 필요 - $this->getModel()->where('status', DEFAULTS['STATUS']); - $this->getModel()->orderBy('oldurl', 'ASC'); - $this->entitys = $this->getModel()->getEntitys(); - $remap_page = view($this->view_path . DIRECTORY_SEPARATOR . strtolower($this->class_path) . DIRECTORY_SEPARATOR . 'remap_template', ["viewDatas" => $this->getViewDatas()]); + $this->getService()->getModel()->where('status', DEFAULTS['STATUS']); + $this->getService()->getModel()->orderBy('oldurl', 'ASC'); + $this->entitys = $this->getService()->getModel()->getEntitys(); + $remap_page = view($this->view_path . DIRECTORY_SEPARATOR . strtolower($this->getService()->getClassPath()) . DIRECTORY_SEPARATOR . 'remap_template', ["viewDatas" => $this->getViewDatas()]); $remap_path = FCPATH . DIRECTORY_SEPARATOR . "mapurl"; //디렉토리 생성 여부 확인 if (!is_dir($remap_path)) { @@ -63,7 +46,7 @@ class MapurlController extends AdminController //생성 public function create_form(): RedirectResponse|string { - $this->init('create', [$this->getModel()::TITLE, 'newurl', 'status']); + $this->init('create', [$this->getService()->getModel()::TITLE, 'newurl', 'status']); return $this->create_form_procedure(); } protected function create_process(): void @@ -73,13 +56,13 @@ class MapurlController extends AdminController } public function create(): RedirectResponse|string { - $this->init(__FUNCTION__, [$this->getModel()::TITLE, 'newurl', 'status']); + $this->init(__FUNCTION__, [$this->getService()->getModel()::TITLE, 'newurl', 'status']); return $this->create_procedure(); } //수정 public function modify_form(int $uid): RedirectResponse|string { - $this->init('modify', [$this->getModel()::TITLE, 'newurl', 'status']); + $this->init('modify', [$this->getService()->getModel()::TITLE, 'newurl', 'status']); return $this->modify_form_procedure($uid); } //(modify,toggle,batchjob사용) @@ -90,7 +73,7 @@ class MapurlController extends AdminController } public function modify(int $uid): RedirectResponse|string { - $this->init(__FUNCTION__, [$this->getModel()::TITLE, 'newurl', 'status']); + $this->init(__FUNCTION__, [$this->getService()->getModel()::TITLE, 'newurl', 'status']); return $this->modify_procedure($uid); } public function toggle(mixed $uid, string $field): RedirectResponse diff --git a/app/Controllers/Admin/MyLogController.php b/app/Controllers/Admin/MyLogController.php new file mode 100644 index 0000000..f423326 --- /dev/null +++ b/app/Controllers/Admin/MyLogController.php @@ -0,0 +1,63 @@ +title = lang("Mylog.title"); + $this->helper = new MyLogHelper(); + } + protected function getService(): MyLogService + { + if ($this->service === null) { + $this->service = new MyLogService(); + } + return $this->service; + } + public function getUserModel(): UserModel + { + if ($this->_userModel === null) { + $this->_userModel = new UserModel(); + } + return $this->_userModel; + } + protected function getFormFieldOption(string $field, array $options = []): array + { + switch ($field) { + case 'user_uid': + // $this->getUserModel()->where('status', DEFAULTS['STATUS']); + $options[$field] = $this->getUserModel()->getFormFieldOption($field); + // echo $this->getUserModel()->getLastQuery(); + // dd($options); + break; + default: + $options = parent::getFormFieldOption($field, $options); + break; + } + return $options; + } + //View + public function view(int $uid): RedirectResponse|string + { + $this->init(__FUNCTION__, ['user_uid', 'class_name', 'method_name', $this->getService()->getModel()::TITLE, 'created_at', 'content']); + return $this->view_procedure($uid); + } + // 리스트 + public function index(): string + { + $this->init(__FUNCTION__); + return $this->list_procedure(); + } +} diff --git a/app/Controllers/Admin/UserController.php b/app/Controllers/Admin/UserController.php index 16554db..88561d1 100644 --- a/app/Controllers/Admin/UserController.php +++ b/app/Controllers/Admin/UserController.php @@ -3,7 +3,6 @@ namespace App\Controllers\Admin; use App\Helpers\UserHelper; -use App\Models\UserModel; use App\Services\UserService; use CodeIgniter\HTTP\DownloadResponse; use CodeIgniter\HTTP\RedirectResponse; @@ -18,16 +17,9 @@ class UserController extends AdminController public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) { parent::initController($request, $response, $logger); - $this->title = lang("{$this->getService()->class_path}.title"); + $this->title = lang("{$this->getService()->getClassPath()}.title"); $this->helper = new UserHelper(); } - protected function getModel(): UserModel - { - if ($this->_model === null) { - $this->_model = new UserModel(); - } - return $this->_model; - } protected function getService(): UserService { if ($this->service === null) { @@ -40,7 +32,7 @@ class UserController extends AdminController switch ($field) { case 'role': //아래 Rule Array는 필드명.* checkbox를 사용 - $validation->setRule("{$field}.*", $field, $this->getModel()->getFieldRule($action, $field)); + $validation->setRule("{$field}.*", $field, $this->getService()->getModel()->getFieldRule($action, $field)); break; default: $validation = parent::setValidation($action, $field, $validation); @@ -48,35 +40,26 @@ class UserController extends AdminController } return $validation; } - private function init(string $action, array $fields = []): void - { - $this->action = $action; - $this->fields = count($fields) ? $fields : ['id', $this->getModel()::TITLE, 'email', 'mobile', 'role', 'status', 'updated_at', 'created_at']; - $this->field_rules = $this->getModel()->getFieldRules($action, $this->fields); - $this->filter_fields = ['role', 'status']; - $this->field_options = $this->getFormFieldOptions($this->filter_fields); - $this->batchjob_fields = ['status']; - } //생성 public function create_form(): RedirectResponse|string { - $this->init('create', ['id', 'passwd', 'confirmpassword', $this->getModel()::TITLE, 'email', 'mobile', 'role']); + $this->init('create', ['id', 'passwd', 'confirmpassword', $this->getService()->getModel()::TITLE, 'email', 'mobile', 'role']); return $this->create_form_procedure(); } public function create(): RedirectResponse|string { - $this->init(__FUNCTION__, ['id', 'passwd', 'confirmpassword', $this->getModel()::TITLE, 'email', 'mobile', 'role']); + $this->init(__FUNCTION__, ['id', 'passwd', 'confirmpassword', $this->getService()->getModel()::TITLE, 'email', 'mobile', 'role']); return $this->create_procedure(); } //수정 public function modify_form(int $uid): RedirectResponse|string { - $this->init('modify', ['passwd', 'confirmpassword', $this->getModel()::TITLE, 'email', 'mobile', 'role', 'status']); + $this->init('modify', ['passwd', 'confirmpassword', $this->getService()->getModel()::TITLE, 'email', 'mobile', 'role', 'status']); return $this->modify_form_procedure($uid); } public function modify(int $uid): RedirectResponse|string { - $this->init(__FUNCTION__, ['passwd', 'confirmpassword', $this->getModel()::TITLE, 'email', 'mobile', 'role', 'status']); + $this->init(__FUNCTION__, ['passwd', 'confirmpassword', $this->getService()->getModel()::TITLE, 'email', 'mobile', 'role', 'status']); return $this->modify_procedure($uid); } public function toggle(mixed $uid, string $field): RedirectResponse diff --git a/app/Controllers/Admin/UserSNSController.php b/app/Controllers/Admin/UserSNSController.php index eb99a45..e55c79e 100644 --- a/app/Controllers/Admin/UserSNSController.php +++ b/app/Controllers/Admin/UserSNSController.php @@ -9,7 +9,6 @@ use CodeIgniter\HTTP\ResponseInterface; use Psr\Log\LoggerInterface; use App\Helpers\UserSNSHelper; use App\Models\UserModel; -use App\Models\UserSNSModel; use App\Services\UserSNSService; class UserSNSController extends AdminController @@ -17,16 +16,9 @@ class UserSNSController extends AdminController public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) { parent::initController($request, $response, $logger); - $this->title = lang("{$this->getService()->class_path}.title"); + $this->title = lang("{$this->getService()->getClassPath()}.title"); $this->helper = new UserSNSHelper(); } - protected function getModel(): UserSNSModel - { - if ($this->_model === null) { - $this->_model = new UserSNSModel(); - } - return $this->_model; - } protected function getService(): UserSNSService { if ($this->service === null) { @@ -37,7 +29,7 @@ class UserSNSController extends AdminController protected function getFormFieldOption(string $field, array $options = []): array { switch ($field) { - case $this->getModel()::PARENT: + case $this->getService()->getModel()::PARENT: $userModel = model(UserModel::class); // $this->getUserModel()->where('status', DEFAULTS['STATUS']); $options[$field] = $userModel->getFormFieldOption($field); @@ -50,24 +42,15 @@ class UserSNSController extends AdminController } return $options; } - private function init(string $action, array $fields = []): void - { - $this->action = $action; - $this->fields = count($fields) ? $fields : [$this->getModel()::PARENT, 'site', 'id', $this->getModel()::TITLE, 'email', 'updated_at', 'created_at']; - $this->field_rules = $this->getModel()->getFieldRules($this->action, $this->fields); - $this->filter_fields = [$this->getModel()::PARENT, 'status']; - $this->field_options = $this->getFormFieldOptions($this->filter_fields); - $this->batchjob_fields = []; - } //수정 public function modify_form(int $uid): RedirectResponse|string { - $this->init('modify', [$this->getModel()::PARENT, 'site', 'id', $this->getModel()::TITLE, 'email']); + $this->init('modify', [$this->getService()->getModel()::PARENT, 'site', 'id', $this->getService()->getModel()::TITLE, 'email']); return $this->modify_form_procedure($uid); } public function modify(int $uid): RedirectResponse|string { - $this->init(__FUNCTION__, [$this->getModel()::PARENT, 'site', 'id', $this->getModel()::TITLE, 'email']); + $this->init(__FUNCTION__, [$this->getService()->getModel()::PARENT, 'site', 'id', $this->getService()->getModel()::TITLE, 'email']); return $this->modify_procedure($uid); } public function toggle(mixed $uid, string $field): RedirectResponse diff --git a/app/Controllers/CLI/Cloudflare.php b/app/Controllers/CLI/Cloudflare.php index b19fe24..1628e63 100644 --- a/app/Controllers/CLI/Cloudflare.php +++ b/app/Controllers/CLI/Cloudflare.php @@ -116,9 +116,9 @@ class Cloudflare extends BaseController $zone = new ZoneService(); foreach ($zone_model->getEntitys() as $entity) { if (!array_key_exists($entity->getParent(), $account_entitys)) { - $account_entitys[$entity->getParent()] = $account_model->getEntity($entity->getParent()); + $account_entitys[$entity->getParent()] = $account_model->getEntityByID($entity->getParent()); } - $zone->expire($account_entitys[$entity->getParent()], $entity); + $zone->expired($account_entitys[$entity->getParent()], $entity); } log_message("notice", "Expire 작업을 완료하였습니다."); // $this->_db->transCommit(); diff --git a/app/Controllers/CommonController.php b/app/Controllers/CommonController.php index 12b8d1d..8120e28 100644 --- a/app/Controllers/CommonController.php +++ b/app/Controllers/CommonController.php @@ -7,9 +7,21 @@ use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; use Psr\Log\LoggerInterface; +use CodeIgniter\HTTP\RedirectResponse; +use CodeIgniter\HTTP\DownloadResponse; +use CodeIgniter\Validation\Validation; +use PhpOffice\PhpSpreadsheet\IOFactory; +use PhpOffice\PhpSpreadsheet\Reader\Html; +use PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf; +use App\Services\MyLogService; + abstract class CommonController extends BaseController { - private $_controlDatas = []; + private $_viewDatas = []; + + abstract protected function getService(): mixed; + //Field별 Form Rule용 + public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) { parent::initController($request, $response, $logger); @@ -17,17 +29,542 @@ abstract class CommonController extends BaseController } final public function __get($name) { - if (!array_key_exists($name, $this->_controlDatas)) { + if (!array_key_exists($name, $this->_viewDatas)) { return null; } - return $this->_controlDatas[$name]; + return $this->_viewDatas[$name]; } final public function __set($name, $value): void { - $this->_controlDatas[$name] = $value; + $this->_viewDatas[$name] = $value; } final public function getViewDatas(): array { - return $this->_controlDatas; + return $this->_viewDatas; + } + + protected function init(string $action, array $fields = []): void + { + $this->action = $action; + $this->fields = count($fields) ? $fields : $this->getService()->getModel()->getFields(); + $this->field_rules = $this->getService()->getModel()->getFieldRules($this->action, $this->fields); + $this->filter_fields = $this->getService()->getModel()->getFilterFields(); + $this->field_options = $this->getFormFieldOptions($this->filter_fields); + $this->batchjob_fields = $this->getService()->getModel()->getBatchJobFields(); + } + + protected function setValidation(string $action, string $field, Validation $validation): Validation + { + switch ($field) { + default: + $validation->setRule($field, $field, $this->getService()->getModel()->getFieldRule($action, $field)); + break; + } + return $validation; + } + final protected function getValidation(string $action, array $fields): Validation + { + $validation = service('validation'); + foreach ($fields as $field) { + $validation = $this->setValidation($action, $field, $validation); + } + return $validation; + } + //Field별 Form Option용 + protected function getFormFieldOption(string $field, array $options): array + { + switch ($field) { + default: + $options[$field] = lang($this->getService()->getClassPath() . '.' . strtoupper($field)); + break; + } + return $options; + } + final protected function getFormFieldOptions(array $fields, array $options = []): array + { + foreach ($fields as $field) { + if (is_array($field)) { + throw new \Exception(__FUNCTION__ . "에서 field array 입니다.\n" . var_export($field, true)); + } + $options = $this->getFormFieldOption($field, $options); + } + return $options; + } + // 생성 + protected function create_form_process(): void {} + final protected function create_form_procedure(): RedirectResponse|string + { + try { + helper(['form']); + $this->create_form_process(); + $this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []]; + return view( + $this->view_path . "create", + data: ['viewDatas' => $this->getViewDatas()] + ); + } catch (\Exception $e) { + return redirect()->back()->with('error', $e->getMessage()); + } + } + protected function create_validate(string $action, array $fields): array + { + //변경할 값 확인 : Upload된 파일 검증시 $this->request->getPOST()보다 먼처 체크필요 + $validation = $this->getValidation($action, $fields); + if (!$validation->withRequest($this->request)->run()) { + throw new \Exception("{$this->getService()->getClassName()} 작업 데이터 검증 오류발생\n" . implode( + "\n", + $validation->getErrors() + )); + } + return $validation->getValidated(); + } + protected function create_process(): void + { + $this->formDatas = $this->create_validate($this->action, $this->fields); + $this->entity = $this->getService()->create($this->formDatas); + } + protected function create_process_result($message): RedirectResponse|string + { + $url = strtolower(base_url() . $this->uri_path . $this->getService()->getClassName()) . "/view/" . $this->entity->getPK(); + return redirect()->to($url)->with('error', $message); + } + final protected function create_procedure(): RedirectResponse|string + { + //Transaction Start + $this->getService()->getModel()->transStart(); + try { + helper(['form']); + $this->create_process(); + $this->getService()->getModel()->transCommit(); + if ($this->isMyLog) { + MyLogService::save($this->getService()->getClassName(), __FUNCTION__, MESSAGES["SUCCESS"], $this->myauth->getUIDByAuthInfo()); + } + return $this->create_process_result(MESSAGES["SUCCESS"]); + } catch (\Exception $e) { + //Transaction Rollback + $this->getService()->getModel()->transRollback(); + if ($this->isMyLog) { + MyLogService::add("error", $e->getMessage()); + MyLogService::save($this->getService()->getClassName(), __FUNCTION__, MESSAGES["FAILED"], $this->myauth->getUIDByAuthInfo()); + } + return redirect()->back()->withInput()->with('error', $e->getMessage()); + } + } + // 수정 + protected function modify_form_process(mixed $uid): void + { + $this->entity = $this->getService()->getModel()->getEntityByPK($uid); + if ($this->entity === null) { + throw new \Exception("해당 정보를 찾을수 없습니다."); + } + } + final protected function modify_form_procedure(mixed $uid): RedirectResponse|string + { + try { + helper(['form']); + $this->modify_form_process($uid); + $this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []]; + return view( + $this->view_path . "modify", + data: ['viewDatas' => $this->getViewDatas()] + ); + } catch (\Exception $e) { + return redirect()->back()->with('error', $e->getMessage()); + } + } + final protected function modify_validate(string $action, array $fields): array + { + //변경할 값 확인 : Upload된 파일 검증시 $this->request->getVar()보다 먼처 체크필요 + $validation = $this->getValidation($action, $fields); + if (!$validation->withRequest($this->request)->run()) { + throw new \Exception("{$this->getService()->getClassName()} 작업 데이터 검증 오류발생\n" . implode( + "\n", + $validation->getErrors() + )); + } + return $validation->getValidated(); + } + //modify,toggle,batchjob 공통사용 + protected function modify_process(mixed $uid): void + { + $this->formDatas = $this->modify_validate($this->action, $this->fields); + //자신정보정의 + $this->entity = $this->getService()->getModel()->getEntityByPK($uid); + if ($this->entity === null) { + throw new \Exception(__FUNCTION__ . " => {$uid} 정보를 찾을수 없습니다."); + } + //수정된값 Log남기기 + foreach ($this->fields as $field) { + MyLogService::add("info", "{$field}: {$this->formDatas[$field]}=>{$this->entity->$field}"); + } + $this->entity = $this->getService()->modify($this->entity, $this->formDatas); + } + protected function modify_process_result($message): RedirectResponse|string + { + $url = strtolower(base_url() . $this->uri_path . $this->getService()->getClassName()) . "/view/" . $this->entity->getPK(); + return redirect()->to($url)->with('error', $message); + } + final protected function modify_procedure(mixed $uid): RedirectResponse|string + { + //Transaction Start + $this->getService()->getModel()->transStart(); + try { + helper(['form']); + $this->modify_process($uid); + $this->getService()->getModel()->transCommit(); + if ($this->isMyLog) { + MyLogService::save($this->getService()->getClassName(), __FUNCTION__, MESSAGES["SUCCESS"], $this->myauth->getUIDByAuthInfo()); + } + return $this->modify_process_result(MESSAGES["SUCCESS"]); + } catch (\Exception $e) { + //Transaction Rollback + $this->getService()->getModel()->transRollback(); + if ($this->isMyLog) { + MyLogService::add("error", $e->getMessage()); + MyLogService::save($this->getService()->getClassName(), __FUNCTION__, MESSAGES["FAILED"], $this->myauth->getUIDByAuthInfo()); + } + return redirect()->back()->withInput()->with('error', $e->getMessage()); + } + } + //단일필드작업 + protected function toggle_process_result($message): RedirectResponse|string + { + return redirect()->to($this->myauth->popPreviousUrl())->with('error', $message); + } + final protected function toggle_procedure(mixed $uid, string $field): RedirectResponse + { + //Transaction Start + $this->getService()->getModel()->transStart(); + try { + $this->action = __FUNCTION__; + $this->fields = [$field]; + $this->modify_process($uid); + $this->getService()->getModel()->transCommit(); + + if ($this->isMyLog) { + MyLogService::save($this->getService()->getClassName(), __FUNCTION__, MESSAGES["SUCCESS"], $this->myauth->getUIDByAuthInfo()); + } + return $this->toggle_process_result(MESSAGES["SUCCESS"]); + } catch (\Exception $e) { + //Transaction Rollback + $this->getService()->getModel()->transRollback(); + if ($this->isMyLog) { + MyLogService::add("error", $e->getMessage()); + MyLogService::save($this->getService()->getClassName(), __FUNCTION__, MESSAGES["FAILED"], $this->myauth->getUIDByAuthInfo()); + } + return redirect()->back()->with('error', $e->getMessage()); + } + } + //일괄처리작업 + protected function batchjob_process_result($message): RedirectResponse|string + { + return redirect()->to($this->myauth->popPreviousUrl())->with('error', $message); + } + final protected function batchjob_procedure(): RedirectResponse + { + //Transaction Start + $this->getService()->getModel()->transStart(); + try { + //데이터가 있는경우 Field만 처리하기위해 + $fields = []; + foreach ($this->batchjob_fields as $field) { + if ($this->request->getVar($field)) { + $fields[$field] = $field; + } + } + $this->fields = $fields; + //변경할 UIDS + $uids = $this->request->getVar('batchjob_uids'); + if (!$uids) { + throw new \Exception("적용할 리스트를 선택하셔야합니다."); + } + foreach (explode(",", $uids) as $uid) { + $this->modify_process($uid); + } + $this->getService()->getModel()->transCommit(); + + if ($this->isMyLog) { + MyLogService::save($this->getService()->getClassName(), __FUNCTION__, MESSAGES["SUCCESS"], $this->myauth->getUIDByAuthInfo()); + } + return $this->batchjob_process_result(MESSAGES["SUCCESS"]); + } catch (\Exception $e) { + //Transaction Rollback + $this->getService()->getModel()->transRollback(); + if ($this->isMyLog) { + MyLogService::add("error", $e->getMessage()); + MyLogService::save($this->getService()->getClassName(), __FUNCTION__, MESSAGES["FAILED"], $this->myauth->getUIDByAuthInfo()); + } + return redirect()->back()->with('error', $e->getMessage()); + } + } + //View + protected function view_process(mixed $uid): void + { + //자신정보정의 + $this->entity = $this->getService()->getModel()->getEntityByPK($uid); + if ($this->entity === null) { + throw new \Exception("해당 정보를 찾을수 없습니다."); + } + } + protected function view_process_result(): string + { + helper(['form']); + $this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []]; + return view( + $this->view_path . "view", + data: ['viewDatas' => $this->getViewDatas()] + ); + } + final protected function view_procedure(mixed $uid): RedirectResponse|string + { + try { + $this->view_process($uid); + return $this->view_process_result(); + } catch (\Exception $e) { + return redirect()->back()->with('error', $e->getMessage()); + } + } + //삭제 delete,batchjob_delete 공통사용 + protected function delete_process(mixed $uid): void + { + //자신정보정의 + $this->entity = $this->getService()->getModel()->getEntityByPK($uid); + if ($this->entity === null) { + throw new \Exception("{$uid} 정보를 찾을수 없습니다."); + } + //삭제된값 Log남기기 + foreach ($this->fields as $field) { + MyLogService::add("info", "{$field}: {$this->entity->$field}"); + } + $this->entity = $this->getService()->delete($this->entity->getPK()); + } + protected function delete_process_result($message): RedirectResponse|string + { + return redirect()->to($this->myauth->popPreviousUrl())->with('error', $message); + } + final public function delete(mixed $uid): RedirectResponse + { + //Transaction Start + $this->getService()->getModel()->transStart(); + try { + $this->delete_process($uid); + $this->getService()->getModel()->transCommit(); + + if ($this->isMyLog) { + MyLogService::save($this->getService()->getClassName(), __FUNCTION__, MESSAGES["SUCCESS"], $this->myauth->getUIDByAuthInfo()); + } + return $this->delete_process_result(MESSAGES["SUCCESS"]); + } catch (\Exception $e) { + //Transaction Rollback + $this->getService()->getModel()->transRollback(); + if ($this->isMyLog) { + MyLogService::add("error", $e->getMessage()); + MyLogService::save($this->getService()->getClassName(), __FUNCTION__, MESSAGES["FAILED"], $this->myauth->getUIDByAuthInfo()); + } + return redirect()->back()->with('error', $e->getMessage()); + } + } + //일괄삭제 + final public function batchjob_delete(): RedirectResponse|string + { + //Transaction Start + $this->getService()->getModel()->transStart(); + try { + //변경할 UIDS + $uids = $this->request->getVar('batchjob_uids'); + if (!$uids) { + throw new \Exception("적용할 리스트를 선택하셔야합니다."); + } + foreach (explode(",", $uids) as $uid) { + $this->delete_process($uid); + } + $this->getService()->getModel()->transCommit(); + + if ($this->isMyLog) { + MyLogService::save($this->getService()->getClassName(), __FUNCTION__, MESSAGES["SUCCESS"], $this->myauth->getUIDByAuthInfo()); + } + return $this->delete_process_result(MESSAGES["SUCCESS"]); + } catch (\Exception $e) { + //Transaction Rollback + $this->getService()->getModel()->transRollback(); + if ($this->isMyLog) { + MyLogService::add("error", $e->getMessage()); + MyLogService::save($this->getService()->getClassName(), __FUNCTION__, MESSAGES["FAILED"], $this->myauth->getUIDByAuthInfo()); + } + return redirect()->back()->with('error', $e->getMessage()); + } + } + // 리스트 + protected function list_condition_process(): void + { + //조건절 처리 + foreach ($this->filter_fields as $field) { + $this->$field = $this->request->getVar($field) ?: DEFAULTS['EMPTY']; + if ($this->$field !== DEFAULTS['EMPTY']) { + $this->getService()->getModel()->setList_FieldFilter($field, $this->$field); + } + } + //검색어 처리 + $this->word = $this->request->getVar('word') ?: DEFAULTS['EMPTY']; + if ($this->word !== DEFAULTS['EMPTY']) { + $this->getService()->getModel()->setList_WordFilter($this->word); + } + //검색일 처리 + $this->start = $this->request->getVar('start') ?: DEFAULTS['EMPTY']; + $this->end = $this->request->getVar('end') ?: DEFAULTS['EMPTY']; + $this->getService()->getModel()->setList_DateFilter($this->start, $this->end); + } + //Totalcount 처리 + private function list_total_process(): int + { + $this->list_condition_process(); + $total_count = $this->getService()->getModel()->countAllResults(); + // MyLogService::add("debug", $this->getService()->getModel()->getLastQuery()); + return $total_count; + } + //PageNation 처리 + private function list_pagination_process($pager_group = 'default', int $segment = 0, $template = 'bootstrap_full'): string + { + //Page, Per_page필요부분 + $this->page = (int) $this->request->getVar('page') ?: 1; + $this->per_page = (int) $this->request->getVar('per_page') ?: intval(env("mvc.default.list.per_page") ?? 10); + //줄수 처리용 + $page_options = array("" => "줄수선택"); + for ($i = $this->per_page; $i <= $this->total_count; $i += $this->per_page) { + $page_options[$i] = $i; + } + $this->page_options = $page_options; + // 1.Views/Pagers/에 bootstrap_full.php,bootstrap_simple.php 생성 + // 2.app/Config/Pager.php/$templates에 'bootstrap_full => 'Pagers\bootstrap_full', + // 'bootstrap_simple' => 'Pagers\bootstrap_simple', 추가 + $pager = service("pager"); + // $this->getService()->getModel()->paginate($this->per_page, $pager_group, $this->page, $segment); + $pager->makeLinks( + $this->page, + $this->per_page, + $this->total_count, + $template, + $segment, + $pager_group + ); + $this->page = $pager->getCurrentPage($pager_group); + $this->total_page = $pager->getPageCount($pager_group); + return $pager->links($pager_group, $template); + } + protected function list_entitys_process(): array + { + $this->list_condition_process(); + //Sorting 처리 + $this->order_field = $this->request->getVar('order_field') ?: DEFAULTS['EMPTY']; + $this->order_value = $this->request->getVar('order_value') ?: DEFAULTS['EMPTY']; + if ($this->order_field !== DEFAULTS['EMPTY'] && $this->order_value !== DEFAULTS['EMPTY']) { + $this->getService()->getModel()->orderBy(sprintf( + "%s.%s %s", + $this->getService()->getModel()::TABLE, + $this->order_field, + $this->order_value + )); + } + $this->getService()->getModel()->limit($this->per_page, $this->page * $this->per_page - $this->per_page); + $entitys = $this->getService()->getModel()->select($this->getService()->getModel()::TABLE . '.*')->findAll(); + MyLogService::add("debug", $this->getService()->getModel()->getLastQuery()); + return $entitys; + } + protected function list_process_result(): string + { + return view( + $this->view_path . "index", + ['viewDatas' => $this->getViewDatas()] + ); + } + final protected function list_procedure(): string + { + try { + helper(['form']); + //URL처리 + $this->uri = $this->request->getUri(); + //total 처리 + $this->total_count = $this->list_total_process(); + //pagenation 처리 + $this->pagination = $this->list_pagination_process(); + //모델 처리 + $this->entitys = $this->list_entitys_process(); + // 현재 URL을 스택에 저장 + $this->myauth->pushCurrentUrl($this->request->getUri()->getPath() . ($this->request->getUri()->getQuery() ? "?" . $this->request->getUri()->getQuery() : "")); + return $this->list_process_result(); + } catch (\Exception $e) { + return $this->helper->alert($e->getMessage()); + } + } + + //OUPUT Document 관련 + private function output_save_process(string $document_type, mixed $loaded_data): array + { + $full_path = WRITEPATH . DIRECTORY_SEPARATOR . "excel"; + switch ($document_type) { + case 'excel': + $file_name = sprintf("%s_%s.xlsx", $this->getService()->getClassName(), date('Y-m-d_Hm')); + $writer = IOFactory::createWriter($loaded_data, 'Xlsx'); + $writer->save($full_path . DIRECTORY_SEPARATOR . $file_name); + break; + case 'pdf': + $file_name = sprintf("%s_%s.pdf", $this->getService()->getClassName(), date('Y-m-d_Hm')); + $writer = new Mpdf($loaded_data); + $writer->save($full_path . DIRECTORY_SEPARATOR . $file_name); + break; + default: + if (!is_file($full_path)) { + throw new \Exception("첨부파일이 확인되지 않습니다.\n"); + } + // //oupuput directly + // header("Content-Type: application/vnd.ms-excel"); + // header(sprintf("Content-Disposition: attachment; filename=%s", urlencode($output_name))); + // header("Expires: 0"); + // header("Cache-Control: must-revalidate"); + // header("Pragma: public"); + // header("Content-Length:" . filesize($full_path)); + // return $writer->save('php://output'); + break; + } + return array($full_path, $file_name); + } + //File Download관련 + final protected function download_procedure(string $output_type, mixed $uid = false): DownloadResponse|RedirectResponse + { + try { + helper(['form']); + //URL처리 + $this->uri = $this->request->getUri(); + switch ($output_type) { + case 'excel': + case 'pdf': + // string buffer에서 읽어오는 경우 + $this->entitys = $this->list_entitys_process(); + $html = view( + 'templates' . DIRECTORY_SEPARATOR . $this->action, + ['viewDatas' => $this->getViewDatas()] + ); + //data loading + $reader = new Html(); + $loaded_data = $reader->loadFromString($html); + list($full_path, $file_name) = $this->output_save_process($output_type, $loaded_data); + $full_path .= DIRECTORY_SEPARATOR . $file_name; + break; + default: + if (!$uid) { + throw new \Exception("{$output_type}은 반드시 uid의 값이 필요합니다."); + } + $this->entity = $this->getService()->getModel()->getEntityByPK($uid); + if ($this->entity === null) { + throw new \Exception("{$uid} 정보를 찾을수 없습니다."); + } + list($file_name, $uploaded_filename) = $this->entity->getDownlaodFile(); + $full_path = WRITEPATH . DIRECTORY_SEPARATOR . "uploads" . DIRECTORY_SEPARATOR . $uploaded_filename; + break; + } + return $this->response->download($full_path, null)->setFileName($file_name); + } catch (\Exception $e) { + return $this->helper->alert($e->getMessage()); + } } } diff --git a/app/Controllers/Home.php b/app/Controllers/Home.php index 1f9787f..5934333 100644 --- a/app/Controllers/Home.php +++ b/app/Controllers/Home.php @@ -2,7 +2,7 @@ namespace App\Controllers; -class Home extends CommonController +class Home extends BaseController { public function index(): string { diff --git a/app/Controllers/MVController.php b/app/Controllers/MVController.php deleted file mode 100644 index 85b05ec..0000000 --- a/app/Controllers/MVController.php +++ /dev/null @@ -1,502 +0,0 @@ -class_path = $this->getService()->class_path; - } - abstract protected function getModel(): mixed; - abstract protected function getService(): mixed; - //Field별 Form Rule용 - protected function setValidation(string $action, string $field, Validation $validation): Validation - { - switch ($field) { - default: - $validation->setRule($field, $field, $this->getModel()->getFieldRule($action, $field)); - break; - } - return $validation; - } - final protected function getValidation(string $action, array $fields): Validation - { - $validation = service('validation'); - foreach ($fields as $field) { - $validation = $this->setValidation($action, $field, $validation); - } - return $validation; - } - //Field별 Form Option용 - protected function getFormFieldOption(string $field, array $options): array - { - switch ($field) { - default: - // echo "TEST:" . $this->getService()->class_path . "," . $this->getService()->class_name; - // dd(lang($this->getService()->class_path . '.' . strtoupper($field))); - $options[$field] = lang($this->getService()->class_path . '.' . strtoupper($field)); - break; - } - return $options; - } - final protected function getFormFieldOptions(array $fields, array $options = []): array - { - foreach ($fields as $field) { - if (is_array($field)) { - throw new \Exception(__FUNCTION__ . "에서 field array 입니다.\n" . var_export($field, true)); - } - $options = $this->getFormFieldOption($field, $options); - } - return $options; - } - // 생성 - protected function create_form_process(): void {} - final protected function create_form_procedure(): RedirectResponse|string - { - try { - helper(['form']); - $this->create_form_process(); - $this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []]; - return view( - $this->view_path . "create", - data: ['viewDatas' => $this->getViewDatas()] - ); - } catch (\Exception $e) { - log_message("error", $e->getMessage()); - return redirect()->back()->with('error', $e->getMessage()); - } - } - protected function create_validate(string $action, array $fields): array - { - //변경할 값 확인 : Upload된 파일 검증시 $this->request->getPOST()보다 먼처 체크필요 - $validation = $this->getValidation($action, $fields); - if (!$validation->withRequest($this->request)->run()) { - throw new \Exception("{$this->getService()->class_name} 작업 데이터 검증 오류발생\n" . implode( - "\n", - $validation->getErrors() - )); - } - return $validation->getValidated(); - } - protected function create_process(): void - { - $this->formDatas = $this->create_validate($this->action, $this->fields); - $this->entity = $this->getService()->create($this->formDatas); - } - protected function create_process_result(): RedirectResponse|string - { - $url = strtolower(base_url() . $this->uri_path . $this->getService()->class_name) . "/view/" . $this->entity->getPK(); - return redirect()->to($url)->with('error', $this->message); - } - final protected function create_procedure(): RedirectResponse|string - { - //Transaction Start - $this->getModel()->transStart(); - try { - helper(['form']); - $this->create_process(); - $this->getModel()->transCommit(); - $this->message = "{$this->getService()->class_name} : 생성작업이 완료되었습니다."; - log_message("notice", $this->message); - return $this->create_process_result(); - } catch (\Exception $e) { - //Transaction Rollback - $this->getModel()->transRollback(); - log_message("error", $e->getMessage()); - return redirect()->back()->withInput()->with('error', __FUNCTION__ . " 실패하였습니다.\n" . $e->getMessage()); - } - } - // 수정 - protected function modify_form_process(mixed $uid): void - { - $this->entity = $this->getModel()->getEntityByPK($uid); - if ($this->entity === null) { - throw new \Exception("해당 정보를 찾을수 없습니다."); - } - } - final protected function modify_form_procedure(mixed $uid): RedirectResponse|string - { - try { - helper(['form']); - $this->modify_form_process($uid); - $this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []]; - return view( - $this->view_path . "modify", - data: ['viewDatas' => $this->getViewDatas()] - ); - } catch (\Exception $e) { - log_message("error", $e->getMessage()); - return redirect()->back()->with('error', $e->getMessage()); - } - } - final protected function modify_validate(string $action, array $fields): array - { - //변경할 값 확인 : Upload된 파일 검증시 $this->request->getVar()보다 먼처 체크필요 - $validation = $this->getValidation($action, $fields); - if (!$validation->withRequest($this->request)->run()) { - throw new \Exception("{$this->getService()->class_name} 작업 데이터 검증 오류발생\n" . implode( - "\n", - $validation->getErrors() - )); - } - return $validation->getValidated(); - } - //modify,toggle,batchjob 공통사용 - protected function modify_process(mixed $uid): void - { - $this->formDatas = $this->modify_validate($this->action, $this->fields); - //자신정보정의 - $this->entity = $this->getModel()->getEntityByPK($uid); - if ($this->entity === null) { - throw new \Exception(__FUNCTION__ . " => {$uid} 정보를 찾을수 없습니다."); - } - $this->entity = $this->getService()->modify($this->entity, $this->formDatas); - } - protected function modify_process_result(): RedirectResponse|string - { - $url = strtolower(base_url() . $this->uri_path . $this->getService()->class_name) . "/view/" . $this->entity->getPK(); - return redirect()->to($url)->with('error', $this->message); - } - final protected function modify_procedure(mixed $uid): RedirectResponse|string - { - //Transaction Start - $this->getModel()->transStart(); - try { - helper(['form']); - $this->modify_process($uid); - $this->getModel()->transCommit(); - $this->message = "{$this->getService()->class_name} : 수정작업이 완료되었습니다."; - log_message("notice", $this->message); - return $this->modify_process_result(); - } catch (\Exception $e) { - //Transaction Rollback - $this->getModel()->transRollback(); - log_message("error", $e->getMessage()); - return redirect()->back()->withInput()->with('error', __FUNCTION__ . " 실패하였습니다.\n" . $e->getMessage()); - } - } - //단일필드작업 - final protected function toggle_procedure(mixed $uid, string $field): RedirectResponse - { - //Transaction Start - $this->getModel()->transStart(); - try { - $this->action = __FUNCTION__; - $this->fields = [$field]; - $this->modify_process($uid); - $this->getModel()->transCommit(); - $this->message = "{$this->getService()->class_name} : 단일필드작업이 완료되었습니다."; - log_message("notice", $this->message); - // 이전 URL로 리다이렉트 - return redirect()->to($this->myauth->popPreviousUrl())->with('error', $this->message); - } catch (\Exception $e) { - //Transaction Rollback - $this->getModel()->transRollback(); - log_message("error", $e->getMessage()); - return redirect()->back()->with('error', __FUNCTION__ . " 실패하였습니다.\n" . $e->getMessage()); - } - } - //일괄처리작업 - final protected function batchjob_procedure(): RedirectResponse - { - //Transaction Start - $this->getModel()->transStart(); - try { - //데이터가 있는경우 Field만 처리하기위해 - $fields = []; - foreach ($this->batchjob_fields as $field) { - if ($this->request->getVar($field)) { - $fields[$field] = $field; - } - } - $this->fields = $fields; - //변경할 UIDS - $uids = $this->request->getVar('batchjob_uids'); - if (!$uids) { - throw new \Exception("적용할 리스트를 선택하셔야합니다."); - } - foreach (explode(",", $uids) as $uid) { - $this->modify_process($uid); - } - $this->getModel()->transCommit(); - $this->message = "{$this->getService()->class_name} : 일괄처리작업이 완료되었습니다."; - log_message("notice", $this->message); - // 이전 URL로 리다이렉트 - return redirect()->to($this->myauth->popPreviousUrl())->with('error', $this->message); - } catch (\Exception $e) { - //Transaction Rollback - $this->getModel()->transRollback(); - log_message("error", $e->getMessage()); - return redirect()->back()->with('error', __FUNCTION__ . " 실패하였습니다.\n" . $e->getMessage()); - } - } - //View - protected function view_process(mixed $uid): void - { - //자신정보정의 - $this->entity = $this->getModel()->getEntityByPK($uid); - if ($this->entity === null) { - throw new \Exception("해당 정보를 찾을수 없습니다."); - } - } - protected function view_process_result(): string - { - helper(['form']); - $this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []]; - return view( - $this->view_path . "view", - data: ['viewDatas' => $this->getViewDatas()] - ); - } - final protected function view_procedure(mixed $uid): RedirectResponse|string - { - try { - $this->view_process($uid); - return $this->view_process_result(); - } catch (\Exception $e) { - log_message("error", $e->getMessage()); - return redirect()->back()->with('error', $e->getMessage()); - } - } - //삭제 delete,batchjob_delete 공통사용 - protected function delete_process(mixed $uid): void - { - //자신정보정의 - $this->entity = $this->getModel()->getEntityByPK($uid); - if ($this->entity === null) { - throw new \Exception("{$uid} 정보를 찾을수 없습니다."); - } - $this->entity = $this->getService()->delete($this->entity->getPK()); - } - final public function delete(mixed $uid): RedirectResponse - { - //Transaction Start - $this->getModel()->transStart(); - try { - $this->delete_process($uid); - $this->getModel()->transCommit(); - $this->message = "{$this->getService()->class_name} : 삭제작업이 완료되었습니다."; - log_message("notice", $this->message); - // 이전 URL로 리다이렉트 - return redirect()->to($this->myauth->popPreviousUrl())->with('error', $this->message); - } catch (\Exception $e) { - //Transaction Rollback - $this->getModel()->transRollback(); - log_message("error", $e->getMessage()); - return redirect()->back()->with('error', __FUNCTION__ . " 실패하였습니다.\n" . $e->getMessage()); - } - } - //일괄삭제 - final public function batchjob_delete(): RedirectResponse|string - { - //Transaction Start - $this->getModel()->transStart(); - try { - //변경할 UIDS - $uids = $this->request->getVar('batchjob_uids'); - if (!$uids) { - throw new \Exception("적용할 리스트를 선택하셔야합니다."); - } - foreach (explode(",", $uids) as $uid) { - $this->delete_process($uid); - } - $this->getModel()->transCommit(); - $this->message = "{$this->getService()->class_name} : 일괄삭제처리작업이 완료되었습니다."; - log_message("notice", $this->message); - // 이전 URL로 리다이렉트 - return redirect()->to($this->myauth->popPreviousUrl())->with('error', $this->message); - } catch (\Exception $e) { - //Transaction Rollback - $this->getModel()->transRollback(); - log_message("error", $e->getMessage()); - return redirect()->back()->with('error', __FUNCTION__ . " 실패하였습니다.\n" . $e->getMessage()); - } - } - // 리스트 - protected function list_condition_process(): void - { - //조건절 처리 - foreach ($this->filter_fields as $field) { - $this->$field = $this->request->getVar($field) ?: DEFAULTS['EMPTY']; - if ($this->$field !== DEFAULTS['EMPTY']) { - $this->getModel()->setList_FieldFilter($field, $this->$field); - } - } - //검색어 처리 - $this->word = $this->request->getVar('word') ?: DEFAULTS['EMPTY']; - if ($this->word !== DEFAULTS['EMPTY']) { - $this->getModel()->setList_WordFilter($this->word); - } - //검색일 처리 - $this->start = $this->request->getVar('start') ?: DEFAULTS['EMPTY']; - $this->end = $this->request->getVar('end') ?: DEFAULTS['EMPTY']; - $this->getModel()->setList_DateFilter($this->start, $this->end); - } - //Totalcount 처리 - private function list_total_process(): int - { - $this->list_condition_process(); - $total_count = $this->getModel()->countAllResults(); - // log_message("debug", $this->getModel()->getLastQuery()); - return $total_count; - } - //PageNation 처리 - private function list_pagination_process($pager_group = 'default', int $segment = 0, $template = 'bootstrap_full'): string - { - //Page, Per_page필요부분 - $this->page = (int) $this->request->getVar('page') ?: 1; - $this->per_page = (int) $this->request->getVar('per_page') ?: intval(env("mvc.default.list.per_page") ?? 10); - //줄수 처리용 - $page_options = array("" => "줄수선택"); - for ($i = $this->per_page; $i <= $this->total_count; $i += $this->per_page) { - $page_options[$i] = $i; - } - $this->page_options = $page_options; - // 1.Views/Pagers/에 bootstrap_full.php,bootstrap_simple.php 생성 - // 2.app/Config/Pager.php/$templates에 'bootstrap_full => 'Pagers\bootstrap_full', - // 'bootstrap_simple' => 'Pagers\bootstrap_simple', 추가 - $pager = service("pager"); - // $this->getModel()->paginate($this->per_page, $pager_group, $this->page, $segment); - $pager->makeLinks( - $this->page, - $this->per_page, - $this->total_count, - $template, - $segment, - $pager_group - ); - $this->page = $pager->getCurrentPage($pager_group); - $this->total_page = $pager->getPageCount($pager_group); - return $pager->links($pager_group, $template); - } - protected function list_entitys_process(): array - { - $this->list_condition_process(); - //Sorting 처리 - $this->order_field = $this->request->getVar('order_field') ?: DEFAULTS['EMPTY']; - $this->order_value = $this->request->getVar('order_value') ?: DEFAULTS['EMPTY']; - if ($this->order_field !== DEFAULTS['EMPTY'] && $this->order_value !== DEFAULTS['EMPTY']) { - $this->getModel()->orderBy(sprintf( - "%s.%s %s", - $this->getModel()::TABLE, - $this->order_field, - $this->order_value - )); - } - $this->getModel()->limit($this->per_page, $this->page * $this->per_page - $this->per_page); - $entitys = $this->getModel()->select($this->getModel()::TABLE . '.*')->findAll(); - log_message("debug", $this->getModel()->getLastQuery()); - return $entitys; - } - protected function list_process_result(): string - { - return view( - $this->view_path . "index", - ['viewDatas' => $this->getViewDatas()] - ); - } - final protected function list_procedure(): string - { - try { - helper(['form']); - //URL처리 - $this->uri = $this->request->getUri(); - //total 처리 - $this->total_count = $this->list_total_process(); - //pagenation 처리 - $this->pagination = $this->list_pagination_process(); - //모델 처리 - $this->entitys = $this->list_entitys_process(); - // 현재 URL을 스택에 저장 - $this->myauth->pushCurrentUrl($this->request->getUri()->getPath() . ($this->request->getUri()->getQuery() ? "?" . $this->request->getUri()->getQuery() : "")); - return $this->list_process_result(); - } catch (\Exception $e) { - log_message("error", $e->getMessage()); - return $this->helper->alert($e->getMessage()); - } - } - - //OUPUT Document 관련 - private function output_save_process(string $document_type, mixed $loaded_data): array - { - $full_path = WRITEPATH . DIRECTORY_SEPARATOR . "excel"; - switch ($document_type) { - case 'excel': - $file_name = sprintf("%s_%s.xlsx", $this->getService()->class_name, date('Y-m-d_Hm')); - $writer = IOFactory::createWriter($loaded_data, 'Xlsx'); - $writer->save($full_path . DIRECTORY_SEPARATOR . $file_name); - break; - case 'pdf': - $file_name = sprintf("%s_%s.pdf", $this->getService()->class_name, date('Y-m-d_Hm')); - $writer = new Mpdf($loaded_data); - $writer->save($full_path . DIRECTORY_SEPARATOR . $file_name); - break; - default: - if (!is_file($full_path)) { - throw new \Exception("첨부파일이 확인되지 않습니다.\n"); - } - // //oupuput directly - // header("Content-Type: application/vnd.ms-excel"); - // header(sprintf("Content-Disposition: attachment; filename=%s", urlencode($output_name))); - // header("Expires: 0"); - // header("Cache-Control: must-revalidate"); - // header("Pragma: public"); - // header("Content-Length:" . filesize($full_path)); - // return $writer->save('php://output'); - break; - } - return array($full_path, $file_name); - } - //File Download관련 - final protected function download_procedure(string $output_type, mixed $uid = false): DownloadResponse|RedirectResponse - { - try { - helper(['form']); - //URL처리 - $this->uri = $this->request->getUri(); - switch ($output_type) { - case 'excel': - case 'pdf': - // string buffer에서 읽어오는 경우 - $this->entitys = $this->list_entitys_process(); - $html = view( - 'templates' . DIRECTORY_SEPARATOR . $this->action, - ['viewDatas' => $this->getViewDatas()] - ); - //data loading - $reader = new Html(); - $loaded_data = $reader->loadFromString($html); - list($full_path, $file_name) = $this->output_save_process($output_type, $loaded_data); - $full_path .= DIRECTORY_SEPARATOR . $file_name; - break; - default: - if (!$uid) { - throw new \Exception("{$output_type}은 반드시 uid의 값이 필요합니다."); - } - $this->entity = $this->getModel()->getEntityByPK($uid); - if ($this->entity === null) { - throw new \Exception("{$uid} 정보를 찾을수 없습니다."); - } - list($file_name, $uploaded_filename) = $this->entity->getDownlaodFile(); - $full_path = WRITEPATH . DIRECTORY_SEPARATOR . "uploads" . DIRECTORY_SEPARATOR . $uploaded_filename; - break; - } - return $this->response->download($full_path, null)->setFileName($file_name); - } catch (\Exception $e) { - log_message("error", $e->getMessage()); - return $this->helper->alert($e->getMessage()); - } - } -} diff --git a/app/Controllers/UserController.php b/app/Controllers/UserController.php index 5b1bd31..a0a7def 100644 --- a/app/Controllers/UserController.php +++ b/app/Controllers/UserController.php @@ -7,27 +7,19 @@ use CodeIgniter\HTTP\RedirectResponse; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; use Psr\Log\LoggerInterface; -use App\Models\UserModel; use App\Services\UserService; use App\Helpers\UserHelper; use App\Services\Auth\GoogleService; use App\Services\Auth\LocalService; -class UserController extends MVController +class UserController extends CommonController { public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) { parent::initController($request, $response, $logger); - $this->title = lang("{$this->getService()->class_path}.title");; + $this->title = lang("{$this->getService()->getClassPath()}.title");; $this->helper = new UserHelper(); } - protected function getModel(): UserModel - { - if ($this->_model === null) { - $this->_model = new UserModel(); - } - return $this->_model; - } protected function getService(): UserService { if ($this->service === null) { @@ -35,7 +27,7 @@ class UserController extends MVController } return $this->service; } - private function init(string $action, array $fields = []): void + protected function init(string $action, array $fields = []): void { $this->action = $action; $this->fields = count($fields) ? $fields : ['id', 'passwd']; diff --git a/app/Controllers/Utils/RSSFeedController.php b/app/Controllers/Utils/RSSFeedController.php index f856c89..9ae344e 100644 --- a/app/Controllers/Utils/RSSFeedController.php +++ b/app/Controllers/Utils/RSSFeedController.php @@ -2,9 +2,9 @@ namespace App\Controllers\Utils; -use App\Controllers\CommonController; +use App\Controllers\BaseController; -class RSSFeedController extends CommonController +class RSSFeedController extends BaseController { public function getITWorld() { diff --git a/app/Controllers/Utils/WebhookController.php b/app/Controllers/Utils/WebhookController.php index a881a43..ecae437 100644 --- a/app/Controllers/Utils/WebhookController.php +++ b/app/Controllers/Utils/WebhookController.php @@ -2,9 +2,9 @@ namespace App\Controllers\Utils; -use App\Controllers\CommonController; +use App\Controllers\BaseController; -class WebhookController extends CommonController +class WebhookController extends BaseController { public function cloudflare() { diff --git a/app/Entities/MyLogEntity.php b/app/Entities/MyLogEntity.php new file mode 100644 index 0000000..c14eecb --- /dev/null +++ b/app/Entities/MyLogEntity.php @@ -0,0 +1,27 @@ +getPK()}:{$this->getTitle()}}"; + } + public function getPK(): int + { + return $this->attributes[MyLogModel::PK]; + } + public function getTitle(): string + { + return $this->attributes[MyLogModel::TITLE]; + } + public function setTitle(string $title): void + { + $this->attributes[MyLogModel::TITLE] = $title; + } + //Common Function +} diff --git a/app/Helpers/MyLogHelper.php b/app/Helpers/MyLogHelper.php new file mode 100644 index 0000000..167e46d --- /dev/null +++ b/app/Helpers/MyLogHelper.php @@ -0,0 +1,47 @@ +$field ?: DEFAULTS['EMPTY']; + switch ($field) { + case MyLogModel::TITLE: + $value = form_label( + $value, + 'view', + [ + "data-src" => current_url() . '/view/' . $viewDatas['entity']->getPK(), + "data-bs-toggle" => "modal", + "data-bs-target" => "#index_action_form", + "style" => "color: blue; cursor: pointer; font-weight:bold;", + ...$extras, + ] + ); + break; + case 'user_uid': + $roles = []; + foreach (explode(DEFAULTS["DELIMITER_ROLE"], $value) as $key) { + $roles[] = $viewDatas['field_options'][$field][$key]; + } + $value = implode(" , ", $roles); + break; + case 'content': + $value = nl2br($value); + break; + default: + $value = parent::getFieldView($field, $viewDatas, $extras); + break; + } + return $value; + } +} diff --git a/app/Language/en/MyLog.php b/app/Language/en/MyLog.php new file mode 100644 index 0000000..190a614 --- /dev/null +++ b/app/Language/en/MyLog.php @@ -0,0 +1,14 @@ + "Log 정보", + 'label' => [ + 'uid' => "번호", + 'class_name' => "클래스", + 'method_name' => "함수", + 'title' => "제목", + 'user_uid' => "사용자", + 'content' => "내용", + 'updated_at' => "수정일", + 'created_at' => "작성일", + ], +]; diff --git a/app/Models/Cloudflare/AccountModel.php b/app/Models/Cloudflare/AccountModel.php index d253626..7e3ac9c 100644 --- a/app/Models/Cloudflare/AccountModel.php +++ b/app/Models/Cloudflare/AccountModel.php @@ -26,6 +26,18 @@ class AccountModel extends CommonModel { return self::TITLE; } + public function getFields(): array + { + return [self::PARENT, self::TITLE, 'type', 'status', 'updated_at', 'created_at']; + } + public function getFilterFields(): array + { + return [self::PARENT, self::TITLE, 'type', 'status']; + } + public function getBatchJobFields(): array + { + return []; + } public function getFieldRule(string $action, string $field): string { switch ($field) { diff --git a/app/Models/Cloudflare/AuditLogModel.php b/app/Models/Cloudflare/AuditLogModel.php index 3c688d6..db6aaba 100644 --- a/app/Models/Cloudflare/AuditLogModel.php +++ b/app/Models/Cloudflare/AuditLogModel.php @@ -26,6 +26,18 @@ class AuditLogModel extends CommonModel { return self::TITLE; } + public function getFields(): array + { + return ['zone_name', self::TITLE, 'action_info', 'actor', 'interface', 'status', 'updated_at', 'created_at']; + } + public function getFilterFields(): array + { + return []; + } + public function getBatchJobFields(): array + { + return $this->getFilterFields(); + } public function getFieldRule(string $action, string $field): string { switch ($field) { diff --git a/app/Models/Cloudflare/AuthModel.php b/app/Models/Cloudflare/AuthModel.php index 23a9fd0..e18e077 100644 --- a/app/Models/Cloudflare/AuthModel.php +++ b/app/Models/Cloudflare/AuthModel.php @@ -24,6 +24,18 @@ class AuthModel extends CommonModel { return self::TITLE; } + public function getFields(): array + { + return [self::TITLE, 'authkey', 'status', 'updated_at', 'created_at']; + } + public function getFilterFields(): array + { + return ['status']; + } + public function getBatchJobFields(): array + { + return $this->getFilterFields(); + } public function getFieldRule(string $action, string $field): string { switch ($field) { diff --git a/app/Models/Cloudflare/FirewallModel.php b/app/Models/Cloudflare/FirewallModel.php index e2b6e50..41636b3 100644 --- a/app/Models/Cloudflare/FirewallModel.php +++ b/app/Models/Cloudflare/FirewallModel.php @@ -27,6 +27,18 @@ class FirewallModel extends CommonModel { return self::TITLE; } + public function getFields(): array + { + return [self::PARENT, 'mode', 'description', 'expression', 'enabled', 'updated_at', 'created_at']; + } + public function getFilterFields(): array + { + return [self::PARENT, 'mode', 'enabled']; + } + public function getBatchJobFields(): array + { + return []; + } public function getFieldRule(string $action, string $field): string { switch ($field) { diff --git a/app/Models/Cloudflare/RecordModel.php b/app/Models/Cloudflare/RecordModel.php index 559b56d..bb336f4 100644 --- a/app/Models/Cloudflare/RecordModel.php +++ b/app/Models/Cloudflare/RecordModel.php @@ -27,6 +27,18 @@ class RecordModel extends CommonModel { return self::TITLE; } + public function getFields(): array + { + return [self::PARENT, 'host', 'type', 'content', 'proxied', 'updated_at', 'created_at']; + } + public function getFilterFields(): array + { + return [self::PARENT, 'type', 'proxied', 'fixed']; + } + public function getBatchJobFields(): array + { + return ['type', 'proxied', 'fixed']; + } public function getFieldRule(string $action, string $field): string { switch ($field) { diff --git a/app/Models/Cloudflare/ZoneModel.php b/app/Models/Cloudflare/ZoneModel.php index c19fdf6..b9fb0a0 100644 --- a/app/Models/Cloudflare/ZoneModel.php +++ b/app/Models/Cloudflare/ZoneModel.php @@ -26,6 +26,18 @@ class ZoneModel extends CommonModel { return self::TITLE; } + public function getFields(): array + { + return [self::PARENT, self::TITLE, 'name_servers', 'original_name_servers', 'plan', 'development_mode', 'ipv6', 'security_level', 'ssl_mode', 'always_use_https', 'status', 'updated_at', 'created_at']; + } + public function getFilterFields(): array + { + return [self::PARENT, 'plan', 'development_mode', 'ipv6', 'security_level', 'ssl_mode', 'always_use_https']; + } + public function getBatchJobFields(): array + { + return ['development_mode', 'ipv6', 'security_level', 'ssl_mode', 'always_use_https']; + } public function getFieldRule(string $action, string $field): string { switch ($field) { diff --git a/app/Models/CommonModel.php b/app/Models/CommonModel.php index 4bec82a..252d495 100644 --- a/app/Models/CommonModel.php +++ b/app/Models/CommonModel.php @@ -51,17 +51,18 @@ abstract class CommonModel extends Model } abstract public function getTitleField(): string; + abstract public function getFields(): array; + abstract public function getFilterFields(): array; + abstract public function getBatchJobFields(): array; final public function getTable(): string { return $this->table; } - final public function getPKField(): string { return $this->primaryKey; } - public function getFieldRule(string $action, string $field): string { if (is_array($field)) { @@ -193,6 +194,7 @@ abstract class CommonModel extends Model foreach (array_keys($formDatas) as $field) { $entity->$field = $this->convertEntityData($field, $formDatas); } + // dd($entity); $entity = $this->save_process($entity); // primaryKey가 자동입력이면 if ($this->useAutoIncrement) { @@ -222,9 +224,9 @@ abstract class CommonModel extends Model $this->where($this->getTable() . '.' . $field, $value); } - public function setList_WordFilter(string $word, string $field = null): void + public function setList_WordFilter(string $word, string $field): void { - $this->like($this->getTable() . '.' . ($field ?? $this->getTitleField()), $word, 'both'); // before, after, both + $this->like($this->getTable() . '.' . $field, $word, 'both'); // before, after, both } final public function setList_DateFilter(string $start, string $end, $field = "created_at"): void diff --git a/app/Models/MapurlModel.php b/app/Models/MapurlModel.php index 9c683aa..febe8bd 100644 --- a/app/Models/MapurlModel.php +++ b/app/Models/MapurlModel.php @@ -26,6 +26,18 @@ class MapurlModel extends CommonModel { return self::TITLE; } + public function getFields(): array + { + return [self::TITLE, 'newurl', 'status', 'updated_at', 'created_at']; + } + public function getFilterFields(): array + { + return ['status']; + } + public function getBatchJobFields(): array + { + return $this->getFilterFields(); + } public function getFieldRule(string $action, string $field): string { if (is_array($field)) { diff --git a/app/Models/MyLogModel.php b/app/Models/MyLogModel.php new file mode 100644 index 0000000..49e71a0 --- /dev/null +++ b/app/Models/MyLogModel.php @@ -0,0 +1,69 @@ + field가 array 입니다.\n" . var_export($field, true)); + } + switch ($field) { + case "user_uid": + $rule = "if_exist|numeric"; + break; + default: + $rule = parent::getFieldRule($action, $field); + break; + } + return $rule; + } + public function getEntityByPK(string $uid): null|MyLogEntity + { + $this->where($this->getPKField(), intval($uid)); + return $this->getEntity(); + } + //create용 + public function create(array $formDatas = []): MyLogEntity + { + return $this->create_process(new MyLogEntity(), $formDatas); + } +} diff --git a/app/Models/UserModel.php b/app/Models/UserModel.php index 7c3590c..0ad7263 100644 --- a/app/Models/UserModel.php +++ b/app/Models/UserModel.php @@ -30,6 +30,18 @@ class UserModel extends CommonModel { return self::TITLE; } + public function getFields(): array + { + return ['id', self::TITLE, 'email', 'mobile', 'role', 'status', 'updated_at', 'created_at']; + } + public function getFilterFields(): array + { + return ['role', 'status']; + } + public function getBatchJobFields(): array + { + return ['status']; + } public function getFieldRule(string $action, string $field): string { if (is_array($field)) { diff --git a/app/Models/UserSNSModel.php b/app/Models/UserSNSModel.php index d0869e7..298b8a0 100644 --- a/app/Models/UserSNSModel.php +++ b/app/Models/UserSNSModel.php @@ -32,6 +32,18 @@ class UserSNSModel extends CommonModel { return self::TITLE; } + public function getFields(): array + { + return [self::PARENT, 'site', 'id', self::TITLE, 'email', 'updated_at', 'created_at']; + } + public function getFilterFields(): array + { + return [self::PARENT, 'status']; + } + public function getBatchJobFields(): array + { + return []; + } public function getFieldRule(string $action, string $field): string { switch ($field) { diff --git a/app/Services/Auth/AuthService.php b/app/Services/Auth/AuthService.php index 5b9bc67..efc7cb8 100644 --- a/app/Services/Auth/AuthService.php +++ b/app/Services/Auth/AuthService.php @@ -23,7 +23,7 @@ class AuthService extends CommonService return $this->_session; } - final protected function getModel(): UserModel + final public function getModel(): UserModel { if ($this->_model === null) { $this->_model = new UserModel(); @@ -31,7 +31,7 @@ class AuthService extends CommonService return $this->_model; } - final public function getAuthInfo(string $key = ""): array|string + private function getAuthInfo(string $key = ""): array|string { $authInfo = $this->getSession()->get(SESSION_NAMES['AUTH']); if ($key) { @@ -40,6 +40,28 @@ class AuthService extends CommonService return $authInfo; } + final public function getUIDByAuthInfo(): string + { + return $this->getAuthInfo('uid'); + } + + final public function getIDByAuthInfo(): string + { + return $this->getAuthInfo('id'); + } + + + final public function getNameByAuthInfo(): string + { + return $this->getAuthInfo('name'); + } + + final public function getRoleByAuthInfo(): string + { + return $this->getAuthInfo('role'); + } + + final public function isLoggedIn(): bool { return $this->getSession()->has(SESSION_NAMES['ISLOGIN']); @@ -47,7 +69,7 @@ class AuthService extends CommonService final public function isAccessRole(array $roles): bool { - $role = $this->getAuthInfo('role'); + $role = $this->getAuthInfo(key: 'role'); if ($role === "") { return false; } diff --git a/app/Services/Cloudflare/AccountService.php b/app/Services/Cloudflare/AccountService.php index 15866ec..47dfd3b 100644 --- a/app/Services/Cloudflare/AccountService.php +++ b/app/Services/Cloudflare/AccountService.php @@ -14,9 +14,7 @@ class AccountService extends CloudflareService public function __construct() { - $this->class_name = "Account"; - parent::__construct(); - $this->class_path .= $this->class_name; + parent::__construct("Account"); } private function getParentEntity(): AuthEntity @@ -33,7 +31,7 @@ class AccountService extends CloudflareService $this->setAuthEntity($this->getParentEntity()); } - protected function getModel(): AccountModel + public function getModel(): AccountModel { if ($this->_model === null) { $this->_model = new AccountModel(); diff --git a/app/Services/Cloudflare/AuditLogService.php b/app/Services/Cloudflare/AuditLogService.php index 8017147..9cd3a95 100644 --- a/app/Services/Cloudflare/AuditLogService.php +++ b/app/Services/Cloudflare/AuditLogService.php @@ -15,12 +15,10 @@ class AuditLogService extends CloudflareService public function __construct() { - $this->class_name = "AuditLog"; - parent::__construct(); - $this->class_path .= $this->class_name; + parent::__construct("AuditLog"); } - protected function getModel(): AuditLogModel + public function getModel(): AuditLogModel { if ($this->_model === null) { $this->_model = new AuditLogModel(); diff --git a/app/Services/Cloudflare/AuthService.php b/app/Services/Cloudflare/AuthService.php index 0fc8f68..ba44625 100644 --- a/app/Services/Cloudflare/AuthService.php +++ b/app/Services/Cloudflare/AuthService.php @@ -11,12 +11,10 @@ class AuthService extends CloudflareService public function __construct() { - $this->class_name = "Auth"; - parent::__construct(); - $this->class_path .= $this->class_name; + parent::__construct("Auth"); } - protected function getModel(): AuthModel + public function getModel(): AuthModel { if ($this->_model === null) { $this->_model = new AuthModel(); diff --git a/app/Services/Cloudflare/CloudflareService.php b/app/Services/Cloudflare/CloudflareService.php index bbb715f..2882772 100644 --- a/app/Services/Cloudflare/CloudflareService.php +++ b/app/Services/Cloudflare/CloudflareService.php @@ -13,11 +13,9 @@ abstract class CloudflareService extends CommonService private array $_mySockets = []; private ?AuthEntity $_auth_entity = null; private ?AuthModel $_authModel = null; - - protected function __construct() + protected function __construct(string $class_name, string $class_path = "") { - parent::__construct(); - $this->class_path = "Cloudflare/"; + parent::__construct($class_name, "Cloudflare/" . $class_path); } final public function getMySocket(): CloudflareSocket diff --git a/app/Services/Cloudflare/FirewallService.php b/app/Services/Cloudflare/FirewallService.php index fdd731e..ba6147c 100644 --- a/app/Services/Cloudflare/FirewallService.php +++ b/app/Services/Cloudflare/FirewallService.php @@ -6,6 +6,7 @@ use App\Models\Cloudflare\FirewallModel; use App\Models\Cloudflare\AccountModel; use App\Entities\Cloudflare\ZoneEntity; use App\Entities\Cloudflare\FirewallEntity; +use App\Services\MyLogService; class FirewallService extends CloudflareService { @@ -15,9 +16,7 @@ class FirewallService extends CloudflareService public function __construct() { - $this->class_name = "Firewall"; - parent::__construct(); - $this->class_path .= $this->class_name; + parent::__construct("Firewall"); } private function getParentEntity(): ZoneEntity @@ -42,7 +41,7 @@ class FirewallService extends CloudflareService $this->setAuthEntity($auth_entity); } - protected function getModel(): FirewallModel + public function getModel(): FirewallModel { if ($this->_model === null) { $this->_model = new FirewallModel(); @@ -90,9 +89,13 @@ class FirewallService extends CloudflareService $body = json_decode($response->getBody()); foreach ($body->result->rules as $rule) { if ($rule->id === $entity->getPK()) { - $formDatas = ['rulesetid' => $body->result->id]; - $formDatas = $this->getArrayByResult($rule, $formDatas); + $formDatas = $this->getArrayByResult($rule, ['rulesetid' => $body->result->id]); + //변경전 entity 값, 변경값 formDatas Log남기기 + MyLogService::add("info", "{$body->result->id}:{$entity->expression}=>{$rule}"); + //DB수정 $entity = $this->getModel()->modify($entity, $formDatas); + MyLogService::add("info", __FUNCTION__ . " {$entity->getTitle()} " . MESSAGES["UPDATED"]); + // log_message("debug", $this->getModel()->getLastQuery()); } } return $entity; diff --git a/app/Services/Cloudflare/RecordService.php b/app/Services/Cloudflare/RecordService.php index 7c4474e..7b2b6b9 100644 --- a/app/Services/Cloudflare/RecordService.php +++ b/app/Services/Cloudflare/RecordService.php @@ -6,6 +6,7 @@ use App\Entities\Cloudflare\RecordEntity; use App\Entities\Cloudflare\ZoneEntity; use App\Models\Cloudflare\AccountModel; use App\Models\Cloudflare\RecordModel; +use App\Services\MyLogService; class RecordService extends CloudflareService { @@ -15,9 +16,7 @@ class RecordService extends CloudflareService public function __construct() { - $this->class_name = "Record"; - parent::__construct(); - $this->class_path .= $this->class_name; + parent::__construct("Record"); } private function getParentEntity(): ZoneEntity @@ -42,7 +41,7 @@ class RecordService extends CloudflareService $this->setAuthEntity($auth_entity); } - protected function getModel(): RecordModel + public function getModel(): RecordModel { if ($this->_model === null) { $this->_model = new RecordModel(); @@ -90,9 +89,15 @@ class RecordService extends CloudflareService ]; $response = $this->getMySocket()->post("zones/{$this->getParentEntity()->getPK()}/dns_records", $datas); $body = json_decode($response->getBody()); + $formDatas = $this->getArrayByResult($body->result); + //생성값 formDatas Log남기기 + foreach ($formDatas as $field => $value) { + MyLogService::add("info", "{$field}:{$value}"); + } //DB생성 - $entity = $this->getModel()->create($this->getArrayByResult($body->result)); - log_message("debug", "Record:{$entity->getTitle()} 작업을 완료하였습니다."); + $entity = $this->getModel()->create($formDatas); + MyLogService::add("info", __FUNCTION__ . " {$entity->getTitle()} " . MESSAGES["CREATED"]); + // log_message("debug", $this->getModel()->getLastQuery()); return $entity; } @@ -129,8 +134,16 @@ class RecordService extends CloudflareService // throw new \Exception("Record:" . __FUNCTION__ . "\n" . json_encode($datas, JSON_PRETTY_PRINT) . "\n" . var_export($datas, true)); $response = $this->getMySocket()->put("zones/{$this->getParentEntity()->getPK()}/dns_records/{$entity->getPK()}", $datas); $body = json_decode($response->getBody()); - // DB 수정 - return $this->getModel()->modify($entity, $this->getArrayByResult($body->result)); + $formDatas = $this->getArrayByResult($body->result); + //변경전 entity 값, 변경값 formDatas Log남기기 + foreach ($formDatas as $field => $value) { + MyLogService::add("info", "{$field}:{$entity->$field}=>{$value}"); + } + //DB수정 + $entity = $this->getModel()->modify($entity, $formDatas); + MyLogService::add("info", __FUNCTION__ . " {$entity->getTitle()} " . MESSAGES["UPDATED"]); + // log_message("debug", $this->getModel()->getLastQuery()); + return $entity; } public function delete(ZoneEntity $parent_entity, RecordEntity $entity): RecordEntity @@ -140,7 +153,12 @@ class RecordService extends CloudflareService $this->getMySocket()->delete("zones/{$this->getParentEntity()->getPK()}/dns_records/{$entity->getPK()}"); //DB삭제 $this->getModel()->delete($entity->getPK()); - log_message("debug", $this->getModel()->getLastQuery()); + //삭제전 entity 값 Log남기기 + foreach ($this->getModel()->getAllowedFields() as $field) { + MyLogService::add("info", "{$field}:{$entity->$field}"); + } + MyLogService::add("info", __FUNCTION__ . " {$entity->getTitle()} " . MESSAGES["DELETED"]); + // log_message("debug", $this->getModel()->getLastQuery()); return $entity; } diff --git a/app/Services/Cloudflare/ZoneService.php b/app/Services/Cloudflare/ZoneService.php index c0bcce0..af1bdca 100644 --- a/app/Services/Cloudflare/ZoneService.php +++ b/app/Services/Cloudflare/ZoneService.php @@ -5,6 +5,7 @@ namespace App\Services\Cloudflare; use App\Entities\Cloudflare\AccountEntity; use App\Entities\Cloudflare\ZoneEntity; use App\Models\Cloudflare\ZoneModel; +use App\Services\MyLogService; class ZoneService extends CloudflareService { @@ -20,9 +21,7 @@ class ZoneService extends CloudflareService public function __construct() { - $this->class_name = "Zone"; - parent::__construct(); - $this->class_path .= $this->class_name; + parent::__construct("Zone"); } private function getParentEntity(): AccountEntity @@ -43,7 +42,7 @@ class ZoneService extends CloudflareService $this->setAuthEntity($auth_entity); } - protected function getModel(): ZoneModel + public function getModel(): ZoneModel { if ($this->_model === null) { $this->_model = new ZoneModel(); @@ -95,10 +94,10 @@ class ZoneService extends CloudflareService private function setCFSetting(string $uid, string $field, string $value): string { $field = ($field === 'ssl_mode') ? 'ssl' : $field; - $datas = ['value' => $value]; - $response = $this->getMySocket()->patch('zones/' . $uid . '/settings/' . $field, $datas); + $response = $this->getMySocket()->patch('zones/' . $uid . '/settings/' . $field, ['value' => $value]); $body = json_decode($response->getBody()); //최종 결과값은 body->result->id='필드명',body->result->value='on/off'이런식으로 받음 + MyLogService::add("debug", __FUNCTION__ . "에서 {$field}:{$body->result->value}을 설정하였습니다."); return $body->result->value; } @@ -108,21 +107,26 @@ class ZoneService extends CloudflareService $this->setParentEntity($parent_entity); //Socket용 //도메인생성을 위해 Cloudflare에 전송 - $datas = [ - 'accountId' => $this->getParentEntity()->getPK(), - 'name' => $domain, + $datas = [ + 'accountId' => $this->getParentEntity()->getPK(), + 'name' => $domain, 'jump_start' => $jump_start, ]; $response = $this->getMySocket()->post('zones/', $datas); - $body = json_decode($response->getBody()); - //DB생성 + $body = json_decode($response->getBody()); $formDatas = $this->getArrayByResult($body->result); + //Zone Setting Fields: ipv6 , development_mode , security_level foreach ($this->_setting_fields as $field => $default) { - //초기화값 추가셋팅 ipv6 , development_mode , security_level $formDatas[$field] = $this->setCFSetting($formDatas[ZoneModel::PK], $field, $default); } + //생성값 formDatas Log남기기 + foreach ($formDatas as $field => $value) { + MyLogService::add("info", "{$field}:{$value}"); + } + //DB생성 $entity = $this->getModel()->create($formDatas); - log_message("debug", "Zone:{$entity->getTitle()} 작업을 완료하였습니다."); + MyLogService::add("info", __FUNCTION__ . " {$entity->getTitle()} " . MESSAGES["CREATED"]); + // log_message("debug", $this->getModel()->getLastQuery()); return $entity; } @@ -130,13 +134,19 @@ class ZoneService extends CloudflareService { //부모데이터정의 $this->setParentEntity($parent_entity); - // throw new \Exception("zone:modify" . var_export($formDatas, true)); + //Zone Setting Fields: ipv6 , development_mode , security_level foreach ($formDatas as $field => $value) { - //modify,toggle,batchjob 사용 셋팅 ipv6 , //development_mode , //security_level $formDatas[$field] = $this->setCFSetting($entity->getPK(), $field, $value); } + //변경전 entity 값, 변경값 formDatas Log남기기 + foreach ($formDatas as $field => $value) { + MyLogService::add("info", "{$field}:{$entity->$field}=>{$value}"); + } //DB수정 - return $this->getModel()->modify($entity, $formDatas); + $entity = $this->getModel()->modify($entity, $formDatas); + MyLogService::add("info", __FUNCTION__ . " {$entity->getTitle()} " . MESSAGES["UPDATED"]); + // log_message("debug", $this->getModel()->getLastQuery()); + return $entity; } public function delete(AccountEntity $parent_entity, ZoneEntity $entity): ZoneEntity @@ -146,7 +156,12 @@ class ZoneService extends CloudflareService $this->getMySocket()->delete("zones/{$entity->getPK()}"); //DB삭제 $this->getModel()->delete($entity->getPK()); - log_message("debug", $this->getModel()->getLastQuery()); + //삭제전 entity 값 Log남기기 + foreach ($this->getModel()->getAllowedFields() as $field) { + MyLogService::add("info", "{$field}:{$entity->$field}"); + } + MyLogService::add("info", __FUNCTION__ . " {$entity->getTitle()} " . MESSAGES["DELETED"]); + // log_message("debug", $this->getModel()->getLastQuery()); return $entity; } @@ -164,7 +179,7 @@ class ZoneService extends CloudflareService return $entity; } - public function expire(AccountEntity $parent_entity, ZoneEntity $entity): ZoneEntity + public function expired(AccountEntity $parent_entity, ZoneEntity $entity): ZoneEntity { $this->setParentEntity($parent_entity); $response = $this->getMySocket()->get("accounts/{$entity->getParent()}/registrar/domains/{$entity->getTitle()}"); diff --git a/app/Services/CommonService.php b/app/Services/CommonService.php index f947d83..15dd03d 100644 --- a/app/Services/CommonService.php +++ b/app/Services/CommonService.php @@ -5,8 +5,15 @@ namespace App\Services; abstract class CommonService { private $_serviceDatas = []; - public function __construct() {} - abstract protected function getModel(): mixed; + private $class_name = ""; + private $class_path = ""; + public function __construct(string $class_name, string $class_path = "") + { + $this->class_name = $class_name; + $this->class_path = $class_path ? $class_path : $this->class_name; + } + + abstract public function getModel(): mixed; final public function __get($name) { if (!array_key_exists($name, $this->_serviceDatas)) { @@ -18,6 +25,14 @@ abstract class CommonService { $this->_serviceDatas[$name] = $value; } + final public function getClassName(): string + { + return $this->class_name; + } + final public function getClassPath(): string + { + return $this->class_path; + } final public function getServiceDatas(): array { return $this->_serviceDatas; diff --git a/app/Services/MYLogService.php b/app/Services/MYLogService.php new file mode 100644 index 0000000..069377f --- /dev/null +++ b/app/Services/MYLogService.php @@ -0,0 +1,39 @@ + $user_uid, + 'class_name' => $class_name, + 'method_name' => $method_name, + 'title' => $title, + 'content' => implode("\n", self::$_logBuffers), + ]; + self::$_logBuffers = []; + // dd($formDatas); + return self::getModel()->create($formDatas); + } +} diff --git a/app/Services/MapurlService.php b/app/Services/MapurlService.php index 5230438..e3d5ee2 100644 --- a/app/Services/MapurlService.php +++ b/app/Services/MapurlService.php @@ -10,11 +10,9 @@ class MapurlService extends CommonService private ?MapurlModel $_model = null; public function __construct() { - $this->class_name = "Mapurl"; - parent::__construct(); - $this->class_path .= $this->class_name; + parent::__construct("Mapurl"); } - protected function getModel(): MapurlModel + public function getModel(): MapurlModel { if ($this->_model === null) { $this->_model = new MapurlModel(); diff --git a/app/Services/UserSNSService.php b/app/Services/UserSNSService.php index d8ceeff..ace0f97 100644 --- a/app/Services/UserSNSService.php +++ b/app/Services/UserSNSService.php @@ -10,11 +10,9 @@ class UserSNSService extends CommonService private ?UserSNSModel $_model = null; public function __construct() { - $this->class_name = "UserSNS"; - parent::__construct(); - $this->class_path .= $this->class_name; + parent::__construct("UserSNS"); } - protected function getModel(): UserSNSModel + public function getModel(): UserSNSModel { if ($this->_model === null) { $this->_model = new UserSNSModel(); diff --git a/app/Services/UserService.php b/app/Services/UserService.php index 05fe789..06944f7 100644 --- a/app/Services/UserService.php +++ b/app/Services/UserService.php @@ -10,11 +10,9 @@ class UserService extends CommonService private ?UserModel $_model = null; public function __construct() { - $this->class_name = "User"; - parent::__construct(); - $this->class_path .= $this->class_name; + parent::__construct("User"); } - protected function getModel(): UserModel + public function getModel(): UserModel { if ($this->_model === null) { $this->_model = new UserModel(); diff --git a/app/Views/layouts/admin/left_menu/base.php b/app/Views/layouts/admin/left_menu/base.php index d13a1e9..b895b2a 100644 --- a/app/Views/layouts/admin/left_menu/base.php +++ b/app/Views/layouts/admin/left_menu/base.php @@ -4,6 +4,9 @@
SNS 계정 관리
+
+ Log 관리 +
MapURL 관리
\ No newline at end of file diff --git a/app/Views/layouts/admin/top.php b/app/Views/layouts/admin/top.php index efee2f8..9396ef5 100644 --- a/app/Views/layouts/admin/top.php +++ b/app/Views/layouts/admin/top.php @@ -22,7 +22,7 @@