cfmgrv3/app/Controllers/Admin/Cloudflare/API/ZoneController.php
2023-06-28 12:22:28 +09:00

294 lines
12 KiB
PHP

<?php
namespace App\Controllers\Admin\Cloudflare\API;
use App\Libraries\Log\Log;
use App\Models\Cloudflare\API\ZoneModel;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use App\Libraries\Cloudflare\API\Zone;
class ZoneController extends APIController
{
private $_account_uids = null;
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
$this->_className .= '/Zone';
$this->_model = new ZoneModel();
$this->_defines = [
'insert' => [
'fields' => ['account_uid', 'type', 'content', 'domains', 'proxied'],
'fieldFilters' => [],
'fieldRules' => [
'account_uid' => 'required|min_length[10]|max_length[200]',
'type' => 'required|in_list[A,CNAME,MX,SPF,TXT,NS,INFO]',
'content' => 'required|trim|min_length[4]',
'domains' => 'required|trim|min_length[4]',
'proxied' => 'required|string',
]
],
'index' => [
'fields' => ['account_uid', 'domain', 'name_servers', 'original_name_servers', 'plan', 'development_mode', 'ipv6', 'security_level', 'status', 'updated_at', 'created_at'],
'fieldFilters' => ['account_uid', 'development_mode', 'ipv6', 'security_level', 'status'],
'batchjobFilters' => ['development_mode', 'ipv6', 'security_level'],
],
'excel' => [
'fields' => ['account_uid', 'domain', 'name_servers', 'original_name_servers', 'plan', 'development_mode', 'ipv6', 'security_level', 'status', 'updated_at', 'created_at'],
'fieldFilters' => ['account_uid', 'development_mode', 'ipv6', 'security_level', 'status'],
],
];
helper($this->_className);
$this->_viewPath = strtolower($this->_className);
$this->_viewDatas['title'] = lang($this->_className . '.title');
$this->_viewDatas['className'] = $this->_className;
}
//Field별 Form Option용
protected function getFieldFormOption(string $field): array
{
switch ($field) {
case 'account_uid':
if (is_null($this->_account_uids)) {
//모든 필요한 FormOption등 조기화작업 필요
$this->_account_uids = [DEFAULT_EMPTY => lang($this->_className . '.label.' . $field) . ' 선택'];
foreach ($this->getAccountModel()->where('status', 'use')->orderBy('title', 'asc')->findAll() as $account) {
$this->_account_uids[$account['uid']] = $account['title'];
}
}
return $this->_account_uids;
break;
default:
return parent::getFieldFormOption($field);
break;
}
}
//Insert관련
protected function insert_validate()
{
parent::insert_validate();
//Content 검증 Type이 A 인경우 IP형식 검사
if ($this->_viewDatas['fieldDatas']['type'] === 'A') {
if (!isIPAddress_CommonHelper($this->_viewDatas['fieldDatas']['content'], $this->_viewDatas['fieldDatas']['type'])) {
throw new \Exception("{$this->_viewDatas['title']}{$this->_viewDatas['fieldDatas']['type']}, {$this->_viewDatas['fieldDatas']['content']} 형식 오류[사설IP 않됨]");
}
}
//Domain검증
$this->_viewDatas['fieldDatas']['domains'] = explode("\n", $this->_viewDatas['fieldDatas']['domains']);
$cnt = 1;
foreach ($this->_viewDatas['fieldDatas']['domains'] as $domain) {
if (!isDomain_CommonHelper($domain)) {
throw new \Exception("{$this->_viewDatas['title']}{$cnt}번째 {$domain} 형식 오류");
}
if (!$this->_model->isUniqueDomain($this->_viewDatas['fieldDatas'][$this->_model::PARENT_FIELD], $domain)) {
throw new \Exception("{$this->_viewDatas['title']}{$cnt}번째 {$domain}은 이미 등록된 도메인입니다.");
}
$cnt++;
}
//Host검증
$this->_viewDatas['fieldDatas']['hosts'] = $this->request->getVar('hosts');
if (!is_array($this->_viewDatas['fieldDatas']['hosts']) || count($this->_viewDatas['fieldDatas']['hosts']) === 0) {
throw new \Exception($this->_viewDatas['title'] . '가 호스트명이 선택되지 않았습니다.');
}
$cnt = 1;
foreach ($this->_viewDatas['fieldDatas']['hosts'] as $host) {
if (!isHost_CommonHelper($host)) {
throw new \Exception("{$this->_viewDatas['title']}{$cnt}번째 {$host} 호스트명 형식 오류");
}
$cnt++;
}
}
protected function insert_process()
{
foreach ($this->_viewDatas['fieldDatas']['domains'] as $domain) {
$account = $this->getAccountModel()->getEntity($this->_viewDatas['fieldDatas'][$this->_model::PARENT_FIELD]);
$zone = $this->insert_Zone($account, $domain);
foreach ($this->_viewDatas['fieldDatas']['hosts'] as $host) {
$this->insert_Host(
$zone,
$host,
$this->_viewDatas['fieldDatas']['type'],
$this->_viewDatas['fieldDatas']['content'],
$this->_viewDatas['fieldDatas']['proxied']
);
}
}
}
//Update관련
protected function update_process($entity)
{
$api = new Zone($this->getAccountModel()->getEntity($entity->getParentFieldData()));
$entity = $api->update($entity, $this->_viewDatas['fieldDatas']);
return parent::update_process($entity);
}
//Toggle관련
protected function toggle_process($entity)
{
$api = new Zone($this->getAccountModel()->getEntity($entity->getParentFieldData()));
$entity = $api->update($entity, $this->_viewDatas['fieldDatas']);
return parent::toggle_process($entity);
}
//Batchjob관련
protected function batchjob_process($entity)
{
$api = new Zone($this->getAccountModel()->getEntity($entity->getParentFieldData()));
$entity = $api->update($entity, $this->_viewDatas['fieldDatas']);
return parent::batchjob_process($entity);
}
//Delete 관련
protected function delete_process($entity)
{
//Zone삭제전에 Record부터 삭제하기위함
foreach ($this->getRecordModel()->getEntitysByZone($entity) as $record) {
$api = new \App\Libraries\Cloudflare\API\Record($entity);
$api->delete($record);
}
$api = new Zone($this->getAccountModel()->getEntity($entity->getParentFieldData()));
$api->delete($entity);
return parent::delete_process($entity);
}
//Index관련
private function index_setCondition_builder($builder)
{
foreach ($this->_viewDatas['fieldFilters'] as $field) {
$value = $this->request->getVar($field) ? $this->request->getVar($field) : false;
if ($value) {
$builder->where("cloudflarezone.{$field}", $value);
}
}
$word = $this->request->getVar('word') ? $this->request->getVar('word') : '';
if (isset($word) && $word !== '') {
$builder->like('domain', $word, 'after'); //befor , after , both
$builder->orWhere('cloudflarerecord.content', $word, 'both'); //befor , after , both
}
$start = $this->request->getVar('start') ? $this->request->getVar('start') : '';
$end = $this->request->getVar('end') ? $this->request->getVar('end') : '';
if (isset($start) && $start !== '' && isset($end) && $end !== '') {
$builder->where('cloudflarezone.created_at >=', $start);
$builder->where('cloudflarezone.created_at <=', $end);
}
return $builder;
}
private function index_getRows_builder(int $page = 0, int $per_page = 0): array
{
//Totalcount 처리
$builder = $this->_model->builder();
$builder->select("cloudflarezone.*");
$builder->join("cloudflarerecord", "cloudflarezone.uid = cloudflarerecord.zone_uid");
$builder = $this->index_setCondition_builder($builder);
// log_message("debug", __METHOD__ . "에서 호출\n" . $builder->getCompiledSelect(false));
$this->_viewDatas['total_count'] = $builder->countAllResults();
//Rows 처리
$builder = $this->_model->builder();
$builder->select("cloudflarezone.*");
$builder->join("cloudflarerecord", "cloudflarezone.uid = cloudflarerecord.zone_uid");
$builder = $this->index_setCondition_builder($builder);
//OrderBy
$order_field = $this->request->getVar('order_field') ? $this->request->getVar('order_field') : 'uid';
$order_value = $this->request->getVar('order_value') ? $this->request->getVar('order_value') : 'DESC';
$builder->orderBy("cloudflarezone.domain ASC, cloudflarezone.{$order_field} {$order_value}");
//Limit
$builder->limit($per_page, $page * $per_page - $per_page);
// log_message("debug", __METHOD__ . "에서 호출\n" . $builder->getCompiledSelect(false));
return $builder->get()->getResultArray();
}
protected function index_getRows(int $page = 0, int $per_page = 0): array
{
return $this->index_getRows_builder($page, $per_page);
}
////Action 모음
//Insert관련
final public function insert()
{
return $this->insert_procedure();
}
//Update관련
final public function update($uid)
{
return $this->update_procedure($uid);
}
//Toggle관련
final public function toggle($uid, string $field)
{
return $this->toggle_procedure($uid, $field);
}
//Batchjob 관련
final public function batchjob()
{
return $this->batchjob_procedure();
}
//Delete 관련
final public function delete($uid)
{
return $this->delete_procedure($uid);
}
//View 관련
// final public function view($uid)
// {
// return $this->view_procedure($uid);
// }
//Index 관련
final public function index()
{
return $this->index_procedure();
}
//Excel 관련
final public function excel()
{
return $this->excel_procedure();
}
////API Action
//Sync관련
protected function sync_process($entity)
{
$api = new Zone($this->getAccountModel()->getEntity($entity->getParentFieldData()));
$entity = $api->sync($entity);
return parent::sync_process($entity);
}
final public function sync($uid)
{
return $this->sync_procedure($uid);
}
//Reload관련
protected function reload_process($entity)
{
//Record Reload
$recordApi = new \App\Libraries\Cloudflare\API\Record($entity);
$recordApi->reload();
//Firewall Reload
// $firewallApi = new \App\Libraries\Cloudflare\API\Firewall($entity);
// $firewallApi->reload();
return $entity;
}
final public function reload($uid)
{
return $this->reload_procedure($uid);
}
////추가 Action
//일괄삭제관련
final public function batchjob_delete()
{
$message = "";
try {
$uids = $this->request->getVar('batchjob_uids');
if (!is_array($uids) || count($uids) === 0) {
throw new \Exception($this->_viewDatas['title'] . '가 uid가 선택되지 않았습니다.');
}
foreach ($uids as $uid) {
$this->delete_process($this->_model->getEntity($uid));
}
$message = "총:" . count($uids) . "개의 삭제 완료하였습니다.";
Log::save("{$this->_viewDatas['title']} {$message}");
return alert_CommonHelper($message, session()->get(RETURN_URL));
} catch (\Exception $e) {
$message = "삭제 실패하였습니다.";
Log::add("warning", $message . "\n" . $e->getMessage());
Log::save("{$this->_viewDatas['title']} {$message}", false);
return alert_CommonHelper($message . "\n" . $e->getMessage(), 'back');
}
}
}