cfmgrv4 init...1

This commit is contained in:
최준흠 2024-09-24 17:29:05 +09:00
commit ff65eb98a2
298 changed files with 15147 additions and 0 deletions

19
.gitignore vendored Normal file
View File

@ -0,0 +1,19 @@
#codeigniter4
composer.lock
/vendor/
public/vendors/
public/tinymce_uploads
.env
writable/caceh/*
!writable/caceh/index.html
writable/logs/*
!writable/logs/index.html
writable/session/*
!writable/session/index.html
writable/uploads/*
!writable/uploads/index.html
writable/debugbar/*
!writable/debugbar/index.html
writable/excel/*
!writable/excel/index.html

3
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,3 @@
{
"php.version": "8.3"
}

22
LICENSE Normal file
View File

@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2014-2019 British Columbia Institute of Technology
Copyright (c) 2019-2024 CodeIgniter Foundation
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

2
README.md Normal file
View File

@ -0,0 +1,2 @@
# Automation

6
app/.htaccess Normal file
View File

@ -0,0 +1,6 @@
<IfModule authz_core_module>
Require all denied
</IfModule>
<IfModule !authz_core_module>
Deny from all
</IfModule>

15
app/Common.php Normal file
View File

@ -0,0 +1,15 @@
<?php
/**
* The goal of this file is to allow developers a location
* where they can overwrite core procedural functions and
* replace them with their own. This file is loaded during
* the bootstrap process and is called during the framework's
* execution.
*
* This can be looked at as a `master helper` file that is
* loaded early on, and may also contain additional functions
* that you'd like to use throughout your entire application
*
* @see: https://codeigniter.com/user_guide/extending/common.html
*/

202
app/Config/App.php Normal file
View File

@ -0,0 +1,202 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class App extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Base Site URL
* --------------------------------------------------------------------------
*
* URL to your CodeIgniter root. Typically, this will be your base URL,
* WITH a trailing slash:
*
* E.g., http://example.com/
*/
public string $baseURL = 'http://localhost:8080/';
/**
* Allowed Hostnames in the Site URL other than the hostname in the baseURL.
* If you want to accept multiple Hostnames, set this.
*
* E.g.,
* When your site URL ($baseURL) is 'http://example.com/', and your site
* also accepts 'http://media.example.com/' and 'http://accounts.example.com/':
* ['media.example.com', 'accounts.example.com']
*
* @var list<string>
*/
public array $allowedHostnames = [];
/**
* --------------------------------------------------------------------------
* Index File
* --------------------------------------------------------------------------
*
* Typically, this will be your `index.php` file, unless you've renamed it to
* something else. If you have configured your web server to remove this file
* from your site URIs, set this variable to an empty string.
*/
public string $indexPage = 'index.php';
/**
* --------------------------------------------------------------------------
* URI PROTOCOL
* --------------------------------------------------------------------------
*
* This item determines which server global should be used to retrieve the
* URI string. The default setting of 'REQUEST_URI' works for most servers.
* If your links do not seem to work, try one of the other delicious flavors:
*
* 'REQUEST_URI': Uses $_SERVER['REQUEST_URI']
* 'QUERY_STRING': Uses $_SERVER['QUERY_STRING']
* 'PATH_INFO': Uses $_SERVER['PATH_INFO']
*
* WARNING: If you set this to 'PATH_INFO', URIs will always be URL-decoded!
*/
public string $uriProtocol = 'REQUEST_URI';
/*
|--------------------------------------------------------------------------
| Allowed URL Characters
|--------------------------------------------------------------------------
|
| This lets you specify which characters are permitted within your URLs.
| When someone tries to submit a URL with disallowed characters they will
| get a warning message.
|
| As a security measure you are STRONGLY encouraged to restrict URLs to
| as few characters as possible.
|
| By default, only these are allowed: `a-z 0-9~%.:_-`
|
| Set an empty string to allow all characters -- but only if you are insane.
|
| The configured value is actually a regular expression character group
| and it will be used as: '/\A[<permittedURIChars>]+\z/iu'
|
| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!!
|
*/
public string $permittedURIChars = 'a-z 0-9~%.:_\-';
/**
* --------------------------------------------------------------------------
* Default Locale
* --------------------------------------------------------------------------
*
* The Locale roughly represents the language and location that your visitor
* is viewing the site from. It affects the language strings and other
* strings (like currency markers, numbers, etc), that your program
* should run under for this request.
*/
public string $defaultLocale = 'en';
/**
* --------------------------------------------------------------------------
* Negotiate Locale
* --------------------------------------------------------------------------
*
* If true, the current Request object will automatically determine the
* language to use based on the value of the Accept-Language header.
*
* If false, no automatic detection will be performed.
*/
public bool $negotiateLocale = false;
/**
* --------------------------------------------------------------------------
* Supported Locales
* --------------------------------------------------------------------------
*
* If $negotiateLocale is true, this array lists the locales supported
* by the application in descending order of priority. If no match is
* found, the first locale will be used.
*
* IncomingRequest::setLocale() also uses this list.
*
* @var list<string>
*/
public array $supportedLocales = ['en'];
/**
* --------------------------------------------------------------------------
* Application Timezone
* --------------------------------------------------------------------------
*
* The default timezone that will be used in your application to display
* dates with the date helper, and can be retrieved through app_timezone()
*
* @see https://www.php.net/manual/en/timezones.php for list of timezones
* supported by PHP.
*/
public string $appTimezone = 'UTC';
/**
* --------------------------------------------------------------------------
* Default Character Set
* --------------------------------------------------------------------------
*
* This determines which character set is used by default in various methods
* that require a character set to be provided.
*
* @see http://php.net/htmlspecialchars for a list of supported charsets.
*/
public string $charset = 'UTF-8';
/**
* --------------------------------------------------------------------------
* Force Global Secure Requests
* --------------------------------------------------------------------------
*
* If true, this will force every request made to this application to be
* made via a secure connection (HTTPS). If the incoming request is not
* secure, the user will be redirected to a secure version of the page
* and the HTTP Strict Transport Security (HSTS) header will be set.
*/
public bool $forceGlobalSecureRequests = false;
/**
* --------------------------------------------------------------------------
* Reverse Proxy IPs
* --------------------------------------------------------------------------
*
* If your server is behind a reverse proxy, you must whitelist the proxy
* IP addresses from which CodeIgniter should trust headers such as
* X-Forwarded-For or Client-IP in order to properly identify
* the visitor's IP address.
*
* You need to set a proxy IP address or IP address with subnets and
* the HTTP header for the client IP address.
*
* Here are some examples:
* [
* '10.0.1.200' => 'X-Forwarded-For',
* '192.168.5.0/24' => 'X-Real-IP',
* ]
*
* @var array<string, string>
*/
public array $proxyIPs = [];
/**
* --------------------------------------------------------------------------
* Content Security Policy
* --------------------------------------------------------------------------
*
* Enables the Response's Content Secure Policy to restrict the sources that
* can be used for images, scripts, CSS files, audio, video, etc. If enabled,
* the Response object will populate default values for the policy from the
* `ContentSecurityPolicy.php` file. Controllers can always add to those
* restrictions at run time.
*
* For a better understanding of CSP, see these documents:
*
* @see http://www.html5rocks.com/en/tutorials/security/content-security-policy/
* @see http://www.w3.org/TR/CSP/
*/
public bool $CSPEnabled = false;
}

94
app/Config/Autoload.php Normal file
View File

@ -0,0 +1,94 @@
<?php
namespace Config;
use CodeIgniter\Config\AutoloadConfig;
/**
* -------------------------------------------------------------------
* AUTOLOADER CONFIGURATION
* -------------------------------------------------------------------
*
* This file defines the namespaces and class maps so the Autoloader
* can find the files as needed.
*
* NOTE: If you use an identical key in $psr4 or $classmap, then
* the values in this file will overwrite the framework's values.
*
* NOTE: This class is required prior to Autoloader instantiation,
* and does not extend BaseConfig.
*
* @immutable
*/
class Autoload extends AutoloadConfig
{
/**
* -------------------------------------------------------------------
* Namespaces
* -------------------------------------------------------------------
* This maps the locations of any namespaces in your application to
* their location on the file system. These are used by the autoloader
* to locate files the first time they have been instantiated.
*
* The 'Config' (APPPATH . 'Config') and 'CodeIgniter' (SYSTEMPATH) are
* already mapped for you.
*
* You may change the name of the 'App' namespace if you wish,
* but this should be done prior to creating any namespaced classes,
* else you will need to modify all of those classes for this to work.
*
* @var array<string, list<string>|string>
*/
public $psr4 = [
APP_NAMESPACE => APPPATH,
];
/**
* -------------------------------------------------------------------
* Class Map
* -------------------------------------------------------------------
* The class map provides a map of class names and their exact
* location on the drive. Classes loaded in this manner will have
* slightly faster performance because they will not have to be
* searched for within one or more directories as they would if they
* were being autoloaded through a namespace.
*
* Prototype:
* $classmap = [
* 'MyClass' => '/path/to/class/file.php'
* ];
*
* @var array<string, string>
*/
public $classmap = [];
/**
* -------------------------------------------------------------------
* Files
* -------------------------------------------------------------------
* The files array provides a list of paths to __non-class__ files
* that will be autoloaded. This can be useful for bootstrap operations
* or for loading functions.
*
* Prototype:
* $files = [
* '/path/to/my/file.php',
* ];
*
* @var list<string>
*/
public $files = [];
/**
* -------------------------------------------------------------------
* Helpers
* -------------------------------------------------------------------
* Prototype:
* $helpers = [
* 'form',
* ];
*
* @var list<string>
*/
public $helpers = [];
}

View File

@ -0,0 +1,34 @@
<?php
/*
|--------------------------------------------------------------------------
| ERROR DISPLAY
|--------------------------------------------------------------------------
| In development, we want to show as many errors as possible to help
| make sure they don't make it to production. And save us hours of
| painful debugging.
|
| If you set 'display_errors' to '1', CI4's detailed error report will show.
*/
error_reporting(E_ALL);
ini_set('display_errors', '1');
/*
|--------------------------------------------------------------------------
| DEBUG BACKTRACES
|--------------------------------------------------------------------------
| If true, this constant will tell the error screens to display debug
| backtraces along with the other error information. If you would
| prefer to not see this, set this value to false.
*/
defined('SHOW_DEBUG_BACKTRACE') || define('SHOW_DEBUG_BACKTRACE', true);
/*
|--------------------------------------------------------------------------
| DEBUG MODE
|--------------------------------------------------------------------------
| Debug mode is an experimental flag that can allow changes throughout
| the system. This will control whether Kint is loaded, and a few other
| items. It can always be used within your own application too.
*/
defined('CI_DEBUG') || define('CI_DEBUG', true);

View File

@ -0,0 +1,25 @@
<?php
/*
|--------------------------------------------------------------------------
| ERROR DISPLAY
|--------------------------------------------------------------------------
| Don't show ANY in production environments. Instead, let the system catch
| it and display a generic error message.
|
| If you set 'display_errors' to '1', CI4's detailed error report will show.
*/
error_reporting(E_ALL & ~E_DEPRECATED);
// If you want to suppress more types of errors.
// error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED);
ini_set('display_errors', '0');
/*
|--------------------------------------------------------------------------
| DEBUG MODE
|--------------------------------------------------------------------------
| Debug mode is an experimental flag that can allow changes throughout
| the system. It's not widely used currently, and may not survive
| release of the framework.
*/
defined('CI_DEBUG') || define('CI_DEBUG', false);

View File

@ -0,0 +1,38 @@
<?php
/*
* The environment testing is reserved for PHPUnit testing. It has special
* conditions built into the framework at various places to assist with that.
* You cant use it for your development.
*/
/*
|--------------------------------------------------------------------------
| ERROR DISPLAY
|--------------------------------------------------------------------------
| In development, we want to show as many errors as possible to help
| make sure they don't make it to production. And save us hours of
| painful debugging.
*/
error_reporting(E_ALL);
ini_set('display_errors', '1');
/*
|--------------------------------------------------------------------------
| DEBUG BACKTRACES
|--------------------------------------------------------------------------
| If true, this constant will tell the error screens to display debug
| backtraces along with the other error information. If you would
| prefer to not see this, set this value to false.
*/
defined('SHOW_DEBUG_BACKTRACE') || define('SHOW_DEBUG_BACKTRACE', true);
/*
|--------------------------------------------------------------------------
| DEBUG MODE
|--------------------------------------------------------------------------
| Debug mode is an experimental flag that can allow changes throughout
| the system. It's not widely used currently, and may not survive
| release of the framework.
*/
defined('CI_DEBUG') || define('CI_DEBUG', true);

View File

@ -0,0 +1,20 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class CURLRequest extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* CURLRequest Share Options
* --------------------------------------------------------------------------
*
* Whether share options between requests or not.
*
* If true, all the options won't be reset between requests.
* It may cause an error request with unnecessary headers.
*/
public bool $shareOptions = false;
}

171
app/Config/Cache.php Normal file
View File

@ -0,0 +1,171 @@
<?php
namespace Config;
use CodeIgniter\Cache\CacheInterface;
use CodeIgniter\Cache\Handlers\DummyHandler;
use CodeIgniter\Cache\Handlers\FileHandler;
use CodeIgniter\Cache\Handlers\MemcachedHandler;
use CodeIgniter\Cache\Handlers\PredisHandler;
use CodeIgniter\Cache\Handlers\RedisHandler;
use CodeIgniter\Cache\Handlers\WincacheHandler;
use CodeIgniter\Config\BaseConfig;
class Cache extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Primary Handler
* --------------------------------------------------------------------------
*
* The name of the preferred handler that should be used. If for some reason
* it is not available, the $backupHandler will be used in its place.
*/
public string $handler = 'file';
/**
* --------------------------------------------------------------------------
* Backup Handler
* --------------------------------------------------------------------------
*
* The name of the handler that will be used in case the first one is
* unreachable. Often, 'file' is used here since the filesystem is
* always available, though that's not always practical for the app.
*/
public string $backupHandler = 'dummy';
/**
* --------------------------------------------------------------------------
* Cache Directory Path
* --------------------------------------------------------------------------
*
* The path to where cache files should be stored, if using a file-based
* system.
*
* @deprecated Use the driver-specific variant under $file
*/
public string $storePath = WRITEPATH . 'cache/';
/**
* --------------------------------------------------------------------------
* Key Prefix
* --------------------------------------------------------------------------
*
* This string is added to all cache item names to help avoid collisions
* if you run multiple applications with the same cache engine.
*/
public string $prefix = '';
/**
* --------------------------------------------------------------------------
* Default TTL
* --------------------------------------------------------------------------
*
* The default number of seconds to save items when none is specified.
*
* WARNING: This is not used by framework handlers where 60 seconds is
* hard-coded, but may be useful to projects and modules. This will replace
* the hard-coded value in a future release.
*/
public int $ttl = 60;
/**
* --------------------------------------------------------------------------
* Reserved Characters
* --------------------------------------------------------------------------
*
* A string of reserved characters that will not be allowed in keys or tags.
* Strings that violate this restriction will cause handlers to throw.
* Default: {}()/\@:
*
* NOTE: The default set is required for PSR-6 compliance.
*/
public string $reservedCharacters = '{}()/\@:';
/**
* --------------------------------------------------------------------------
* File settings
* --------------------------------------------------------------------------
* Your file storage preferences can be specified below, if you are using
* the File driver.
*
* @var array<string, int|string|null>
*/
public array $file = [
'storePath' => WRITEPATH . 'cache/',
'mode' => 0640,
];
/**
* -------------------------------------------------------------------------
* Memcached settings
* -------------------------------------------------------------------------
* Your Memcached servers can be specified below, if you are using
* the Memcached drivers.
*
* @see https://codeigniter.com/user_guide/libraries/caching.html#memcached
*
* @var array<string, bool|int|string>
*/
public array $memcached = [
'host' => '127.0.0.1',
'port' => 11211,
'weight' => 1,
'raw' => false,
];
/**
* -------------------------------------------------------------------------
* Redis settings
* -------------------------------------------------------------------------
* Your Redis server can be specified below, if you are using
* the Redis or Predis drivers.
*
* @var array<string, int|string|null>
*/
public array $redis = [
'host' => '127.0.0.1',
'password' => null,
'port' => 6379,
'timeout' => 0,
'database' => 0,
];
/**
* --------------------------------------------------------------------------
* Available Cache Handlers
* --------------------------------------------------------------------------
*
* This is an array of cache engine alias' and class names. Only engines
* that are listed here are allowed to be used.
*
* @var array<string, class-string<CacheInterface>>
*/
public array $validHandlers = [
'dummy' => DummyHandler::class,
'file' => FileHandler::class,
'memcached' => MemcachedHandler::class,
'predis' => PredisHandler::class,
'redis' => RedisHandler::class,
'wincache' => WincacheHandler::class,
];
/**
* --------------------------------------------------------------------------
* Web Page Caching: Cache Include Query String
* --------------------------------------------------------------------------
*
* Whether to take the URL query string into consideration when generating
* output cache files. Valid options are:
*
* false = Disabled
* true = Enabled, take all query parameters into account.
* Please be aware that this may result in numerous cache
* files generated for the same page over and over again.
* ['q'] = Enabled, but only take into account the specified list
* of query parameters.
*
* @var bool|list<string>
*/
public $cacheQueryString = false;
}

275
app/Config/Constants.php Normal file
View File

@ -0,0 +1,275 @@
<?php
/*
| --------------------------------------------------------------------
| App Namespace
| --------------------------------------------------------------------
|
| This defines the default Namespace that is used throughout
| CodeIgniter to refer to the Application directory. Change
| this constant to change the namespace that all application
| classes should use.
|
| NOTE: changing this will require manually modifying the
| existing namespaces of App\* namespaced-classes.
*/
defined('APP_NAMESPACE') || define('APP_NAMESPACE', 'App');
/*
| --------------------------------------------------------------------------
| Composer Path
| --------------------------------------------------------------------------
|
| The path that Composer's autoload file is expected to live. By default,
| the vendor folder is in the Root directory, but you can customize that here.
*/
defined('COMPOSER_PATH') || define('COMPOSER_PATH', ROOTPATH . 'vendor/autoload.php');
/*
|--------------------------------------------------------------------------
| Timing Constants
|--------------------------------------------------------------------------
|
| Provide simple ways to work with the myriad of PHP functions that
| require information to be in seconds.
*/
defined('SECOND') || define('SECOND', 1);
defined('MINUTE') || define('MINUTE', 60);
defined('HOUR') || define('HOUR', 3600);
defined('DAY') || define('DAY', 86400);
defined('WEEK') || define('WEEK', 604800);
defined('MONTH') || define('MONTH', 2_592_000);
defined('YEAR') || define('YEAR', 31_536_000);
defined('DECADE') || define('DECADE', 315_360_000);
/*
| --------------------------------------------------------------------------
| Exit Status Codes
| --------------------------------------------------------------------------
|
| Used to indicate the conditions under which the script is exit()ing.
| While there is no universal standard for error codes, there are some
| broad conventions. Three such conventions are mentioned below, for
| those who wish to make use of them. The CodeIgniter defaults were
| chosen for the least overlap with these conventions, while still
| leaving room for others to be defined in future versions and user
| applications.
|
| The three main conventions used for determining exit status codes
| are as follows:
|
| Standard C/C++ Library (stdlibc):
| http://www.gnu.org/software/libc/manual/html_node/Exit-Status.html
| (This link also contains other GNU-specific conventions)
| BSD sysexits.h:
| http://www.gsp.com/cgi-bin/man.cgi?section=3&topic=sysexits
| Bash scripting:
| http://tldp.org/LDP/abs/html/exitcodes.html
|
*/
defined('EXIT_SUCCESS') || define('EXIT_SUCCESS', 0); // no errors
defined('EXIT_ERROR') || define('EXIT_ERROR', 1); // generic error
defined('EXIT_CONFIG') || define('EXIT_CONFIG', 3); // configuration error
defined('EXIT_UNKNOWN_FILE') || define('EXIT_UNKNOWN_FILE', 4); // file not found
defined('EXIT_UNKNOWN_CLASS') || define('EXIT_UNKNOWN_CLASS', 5); // unknown class
defined('EXIT_UNKNOWN_METHOD') || define('EXIT_UNKNOWN_METHOD', 6); // unknown class member
defined('EXIT_USER_INPUT') || define('EXIT_USER_INPUT', 7); // invalid user input
defined('EXIT_DATABASE') || define('EXIT_DATABASE', 8); // database error
defined('EXIT__AUTO_MIN') || define('EXIT__AUTO_MIN', 9); // lowest automatically-assigned error code
defined('EXIT__AUTO_MAX') || define('EXIT__AUTO_MAX', 125); // highest automatically-assigned error code
/**
* @deprecated Use \CodeIgniter\Events\Events::PRIORITY_LOW instead.
*/
define('EVENT_PRIORITY_LOW', 200);
/**
* @deprecated Use \CodeIgniter\Events\Events::PRIORITY_NORMAL instead.
*/
define('EVENT_PRIORITY_NORMAL', 100);
/**
* @deprecated Use \CodeIgniter\Events\Events::PRIORITY_HIGH instead.
*/
define('EVENT_PRIORITY_HIGH', 10);
//Default값 정의
define('DEFAULTS', [
'ROLE' => "guest",
'STATUS' => "use",
'EMPTY' => "",
'PERPAGE' => 20,
'DELIMITER_FILE' => "||",
'DELIMITER_ROLE' => ",",
]);
//URL
define('URLS', [
'LOGIN' => '/user/login',
'SIGNUP' => '/user/signup',
'LOGOUT' => '/user/logout',
]);
//회원ROLE
define('ROLES', [
'guest',
'user',
'vip',
'manager',
'cloudflare',
'director',
'master',
]);
//SESSION 관련
define('SESSION_NAMES', [
'RETURN_URL' => "return_url",
'RETURN_MSG' => "return_message",
'ISLOGIN' => "islogined",
'AUTH' => 'auth',
]);
//인증 관련
define('AUTH_FIELDS', [
'ID' => 'id',
'TITLE' => 'title',
'ROLE' => 'role',
]);
//DBAction
define('DB_ACTION', [
'CREATE' => 'create',
'MODIFY' => 'modify',
]);
define("MESSENGERS", [
"skype" => [
"url" => "https://join.skype.com/invite/uKUgXfZThSQC",
"icon" => '<img src="/images/common/top_skype.png" alt="스카이프">',
"id" => '',
],
"discord" => [
"url" => "https://discord.gg/k6nQg84N",
"icon" => '<img src="/images/common/discord.png" alt="디스코드">',
"id" => '',
],
"telegram" => [
"url" => "https://t.me/daemonidc",
"icon" => '<img src="/images/common/telegram.png" alt="텔레그램">',
"id" => '@daemonidc',
],
"kakaotalk" => [
"url" => "https://t.me/daemonidc",
"icon" => '<img src="/images/common/kakaotalk.png" alt="카카오톡">',
"id" => '',
],
]);
//아이콘 및 Sound관련
define('ICONS', [
'LOGO' => '<img src="/images/logo/android-icon-48x48.png">',
'LOGIN' => '<i class="bi bi-shield-check"></i>',
'LOGOUT' => '<i class="bi bi-sign-stop-fill"></i>',
'HOME' => '<i class="bi bi-house"></i>',
'MENU' => '<i class="bi bi-menu-button"></i>',
'LOCK' => '<i class="bi bi-shield-lock"></i>',
'NEW' => '<i class="bi bi-database-add"></i>',
'REPLY' => '<i class="bi bi-arrow-return-right"></i>',
'DELETE' => '<i class="bi bi-trash"></i>',
'RELOAD' => '<i class="bi bi-repeat"></i>',
'SETUP' => '<i class="bi bi-gear"></i>',
'FLAG' => '<i class="bi bi-send"></i>',
'SEARCH' => '<i class="bi bi-search"></i>',
'EXCEL' => '<img src="/images/common/excel.png"/>',
'PLAY' => '<i class="bi bi-play-fill"></i>',
'CART' => '<i class="bi bi-cart4"></i>',
'CARD' => '<i class="bi bi-credit-card"></i>',
'DEPOSIT' => '<i class="bi bi-cash-coin"></i>',
'DESKTOP' => '<i class="bi bi-pc-display-horizontal"></i>',
'UP' => '<i class="bi bi-arrow-up"></i>',
'DOWN' => '<i class="bi bi-arrow-down"></i>',
'LEFT' => '<i class="bi bi-arrow-left"></i>',
'RIGHT' => '<i class="bi bi-arrow-right"></i>',
'IMAGE_FILE' => '<i class="bi bi-file-earmark-image"></i>',
'GOOGLE' => '<i class="fa-brands fa-google"></i>',
]);
define('TOP_BANNER', [
'default' => '<img src="/images/banner/sub_visual1.jpg"/>',
'aboutus' => '<img src="/images/banner/sub_visual1.jpg"/>',
'member' => '<img src="/images/banner/sub_visual1.jpg"/>',
'hosting' => '<img src="/images/banner/sub_visual2.jpg"/>',
'serverdevice' => '<img src="/images/banner/sub_visual3.jpg"/>',
'service' => '<img src="/images/banner/sub_visual3.jpg"/>',
'support' => '<img src="/images/banner/sub_visual4.jpg"/>',
]);
define('AUDIOS', [
'Alram_GetEmail' => '<object width=0 height=0 data="/sound/jarvis_email.mp3" type="audio/mpeg"></object>',
]);
define('KEYWORD', '일본IDC 일본서버 일본 서버 일본호스팅 서버호스팅 디도스 공격 해외 호스팅 DDOS 방어 ddos 의뢰 디도스 보안 일본 단독서버 가상서버');
define('LAYOUTS', [
'empty' => [
'path' => 'layouts' . DIRECTORY_SEPARATOR . 'empty',
'stylesheets' => [
'<link rel="icon" href="/favicon.ico">',
'<link href="//cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">',
'<link rel="stylesheet" href="/css/style.css" />',
],
'javascripts' => [
'<script src="//cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" crossorigin="anonymous"></script>',
],
],
'front' => [
'title' => KEYWORD,
'path' => 'layouts' . DIRECTORY_SEPARATOR . 'front',
//'topmenus' => ['aboutus', 'hosting', 'serverdevice', 'service', 'support'],
'topmenus' => ['aboutus', 'hosting', 'service', 'support'],
'metas' => [
'<meta charset="utf-8">',
'<meta http-equiv="X-UA-Compatible" content="IE=Edge">',
'<meta name="viewport" id="viewport" content="width=1280">',
'<meta name="subject" content="Daemon IDC">',
'<meta name="description" content="' . KEYWORD . '">',
'<meta name="keywords" content="' . KEYWORD . '">',
'<meta property="og:type" content="website">',
'<meta property="og:title" content="Daemon IDC">',
'<meta property="og:description" content="' . KEYWORD . '">',
],
'stylesheets' => [
'<link rel="canonical" href="https://daemonidc.com/" />',
'<link rel="icon" href="/favicon.ico">',
'<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">',
'<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">',
'<link href="//cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">',
'<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css">',
'<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" />',
'<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/boxicons@latest/css/boxicons.min.css" />',
'<link rel="stylesheet" href="/css/style.css" />',
],
'javascripts' => [
'<script src="//cdn.jsdelivr.net/npm/jquery@3.7.0/dist/jquery.min.js"></script>',
'<script src="//code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>',
'<script src="//cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" crossorigin="anonymous"></script>',
'<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>',
'<script src="/vendors/tinymce/tinymce/tinymce.js" referrerpolicy="origin"></script>',
],
],
'admin' => [
'title' => '관리자화면',
'path' => 'layouts' . DIRECTORY_SEPARATOR . 'admin',
'stylesheets' => [
'<link rel="icon" href="/favicon.ico">',
'<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">',
'<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">',
'<link href="//cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">',
'<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css">',
'<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" />',
'<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/boxicons@latest/css/boxicons.min.css" />',
'<link rel="stylesheet" href="/css/style.css" />',
],
'javascripts' => [
'<script src="//cdn.jsdelivr.net/npm/jquery@3.7.0/dist/jquery.min.js"></script>',
'<script src="//code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>',
'<script src="//cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" crossorigin="anonymous"></script>',
'<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>',
'<script src="/vendors/tinymce/tinymce/tinymce.js" referrerpolicy="origin"></script>',
],
],
]);

View File

@ -0,0 +1,176 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Stores the default settings for the ContentSecurityPolicy, if you
* choose to use it. The values here will be read in and set as defaults
* for the site. If needed, they can be overridden on a page-by-page basis.
*
* Suggested reference for explanations:
*
* @see https://www.html5rocks.com/en/tutorials/security/content-security-policy/
*/
class ContentSecurityPolicy extends BaseConfig
{
// -------------------------------------------------------------------------
// Broadbrush CSP management
// -------------------------------------------------------------------------
/**
* Default CSP report context
*/
public bool $reportOnly = false;
/**
* Specifies a URL where a browser will send reports
* when a content security policy is violated.
*/
public ?string $reportURI = null;
/**
* Instructs user agents to rewrite URL schemes, changing
* HTTP to HTTPS. This directive is for websites with
* large numbers of old URLs that need to be rewritten.
*/
public bool $upgradeInsecureRequests = false;
// -------------------------------------------------------------------------
// Sources allowed
// NOTE: once you set a policy to 'none', it cannot be further restricted
// -------------------------------------------------------------------------
/**
* Will default to self if not overridden
*
* @var list<string>|string|null
*/
public $defaultSrc;
/**
* Lists allowed scripts' URLs.
*
* @var list<string>|string
*/
public $scriptSrc = 'self';
/**
* Lists allowed stylesheets' URLs.
*
* @var list<string>|string
*/
public $styleSrc = 'self';
/**
* Defines the origins from which images can be loaded.
*
* @var list<string>|string
*/
public $imageSrc = 'self';
/**
* Restricts the URLs that can appear in a page's `<base>` element.
*
* Will default to self if not overridden
*
* @var list<string>|string|null
*/
public $baseURI;
/**
* Lists the URLs for workers and embedded frame contents
*
* @var list<string>|string
*/
public $childSrc = 'self';
/**
* Limits the origins that you can connect to (via XHR,
* WebSockets, and EventSource).
*
* @var list<string>|string
*/
public $connectSrc = 'self';
/**
* Specifies the origins that can serve web fonts.
*
* @var list<string>|string
*/
public $fontSrc;
/**
* Lists valid endpoints for submission from `<form>` tags.
*
* @var list<string>|string
*/
public $formAction = 'self';
/**
* Specifies the sources that can embed the current page.
* This directive applies to `<frame>`, `<iframe>`, `<embed>`,
* and `<applet>` tags. This directive can't be used in
* `<meta>` tags and applies only to non-HTML resources.
*
* @var list<string>|string|null
*/
public $frameAncestors;
/**
* The frame-src directive restricts the URLs which may
* be loaded into nested browsing contexts.
*
* @var list<string>|string|null
*/
public $frameSrc;
/**
* Restricts the origins allowed to deliver video and audio.
*
* @var list<string>|string|null
*/
public $mediaSrc;
/**
* Allows control over Flash and other plugins.
*
* @var list<string>|string
*/
public $objectSrc = 'self';
/**
* @var list<string>|string|null
*/
public $manifestSrc;
/**
* Limits the kinds of plugins a page may invoke.
*
* @var list<string>|string|null
*/
public $pluginTypes;
/**
* List of actions allowed.
*
* @var list<string>|string|null
*/
public $sandbox;
/**
* Nonce tag for style
*/
public string $styleNonceTag = '{csp-style-nonce}';
/**
* Nonce tag for script
*/
public string $scriptNonceTag = '{csp-script-nonce}';
/**
* Replace nonce tag automatically
*/
public bool $autoNonce = true;
}

107
app/Config/Cookie.php Normal file
View File

@ -0,0 +1,107 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use DateTimeInterface;
class Cookie extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Cookie Prefix
* --------------------------------------------------------------------------
*
* Set a cookie name prefix if you need to avoid collisions.
*/
public string $prefix = '';
/**
* --------------------------------------------------------------------------
* Cookie Expires Timestamp
* --------------------------------------------------------------------------
*
* Default expires timestamp for cookies. Setting this to `0` will mean the
* cookie will not have the `Expires` attribute and will behave as a session
* cookie.
*
* @var DateTimeInterface|int|string
*/
public $expires = 0;
/**
* --------------------------------------------------------------------------
* Cookie Path
* --------------------------------------------------------------------------
*
* Typically will be a forward slash.
*/
public string $path = '/';
/**
* --------------------------------------------------------------------------
* Cookie Domain
* --------------------------------------------------------------------------
*
* Set to `.your-domain.com` for site-wide cookies.
*/
public string $domain = '';
/**
* --------------------------------------------------------------------------
* Cookie Secure
* --------------------------------------------------------------------------
*
* Cookie will only be set if a secure HTTPS connection exists.
*/
public bool $secure = false;
/**
* --------------------------------------------------------------------------
* Cookie HTTPOnly
* --------------------------------------------------------------------------
*
* Cookie will only be accessible via HTTP(S) (no JavaScript).
*/
public bool $httponly = true;
/**
* --------------------------------------------------------------------------
* Cookie SameSite
* --------------------------------------------------------------------------
*
* Configure cookie SameSite setting. Allowed values are:
* - None
* - Lax
* - Strict
* - ''
*
* Alternatively, you can use the constant names:
* - `Cookie::SAMESITE_NONE`
* - `Cookie::SAMESITE_LAX`
* - `Cookie::SAMESITE_STRICT`
*
* Defaults to `Lax` for compatibility with modern browsers. Setting `''`
* (empty string) means default SameSite attribute set by browsers (`Lax`)
* will be set on cookies. If set to `None`, `$secure` must also be set.
*
* @phpstan-var 'None'|'Lax'|'Strict'|''
*/
public string $samesite = 'Lax';
/**
* --------------------------------------------------------------------------
* Cookie Raw
* --------------------------------------------------------------------------
*
* This flag allows setting a "raw" cookie, i.e., its name and value are
* not URL encoded using `rawurlencode()`.
*
* If this is set to `true`, cookie names should be compliant of RFC 2616's
* list of allowed characters.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#attributes
* @see https://tools.ietf.org/html/rfc2616#section-2.2
*/
public bool $raw = false;
}

105
app/Config/Cors.php Normal file
View File

@ -0,0 +1,105 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Cross-Origin Resource Sharing (CORS) Configuration
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
*/
class Cors extends BaseConfig
{
/**
* The default CORS configuration.
*
* @var array{
* allowedOrigins: list<string>,
* allowedOriginsPatterns: list<string>,
* supportsCredentials: bool,
* allowedHeaders: list<string>,
* exposedHeaders: list<string>,
* allowedMethods: list<string>,
* maxAge: int,
* }
*/
public array $default = [
/**
* Origins for the `Access-Control-Allow-Origin` header.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
*
* E.g.:
* - ['http://localhost:8080']
* - ['https://www.example.com']
*/
'allowedOrigins' => [],
/**
* Origin regex patterns for the `Access-Control-Allow-Origin` header.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
*
* NOTE: A pattern specified here is part of a regular expression. It will
* be actually `#\A<pattern>\z#`.
*
* E.g.:
* - ['https://\w+\.example\.com']
*/
'allowedOriginsPatterns' => [],
/**
* Weather to send the `Access-Control-Allow-Credentials` header.
*
* The Access-Control-Allow-Credentials response header tells browsers whether
* the server allows cross-origin HTTP requests to include credentials.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
*/
'supportsCredentials' => false,
/**
* Set headers to allow.
*
* The Access-Control-Allow-Headers response header is used in response to
* a preflight request which includes the Access-Control-Request-Headers to
* indicate which HTTP headers can be used during the actual request.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
*/
'allowedHeaders' => [],
/**
* Set headers to expose.
*
* The Access-Control-Expose-Headers response header allows a server to
* indicate which response headers should be made available to scripts running
* in the browser, in response to a cross-origin request.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
*/
'exposedHeaders' => [],
/**
* Set methods to allow.
*
* The Access-Control-Allow-Methods response header specifies one or more
* methods allowed when accessing a resource in response to a preflight
* request.
*
* E.g.:
* - ['GET', 'POST', 'PUT', 'DELETE']
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods
*/
'allowedMethods' => [],
/**
* Set how many seconds the results of a preflight request can be cached.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age
*/
'maxAge' => 7200,
];
}

201
app/Config/Database.php Normal file
View File

@ -0,0 +1,201 @@
<?php
namespace Config;
use CodeIgniter\Database\Config;
/**
* Database Configuration
*/
class Database extends Config
{
/**
* The directory that holds the Migrations and Seeds directories.
*/
public string $filesPath = APPPATH . 'Database' . DIRECTORY_SEPARATOR;
/**
* Lets you choose which connection group to use if no other is specified.
*/
public string $defaultGroup = 'default';
/**
* The default database connection.
*
* @var array<string, mixed>
*/
public array $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => '',
'password' => '',
'database' => '',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => true,
'charset' => 'utf8mb4',
'DBCollat' => 'utf8mb4_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
'numberNative' => false,
'dateFormat' => [
'date' => 'Y-m-d',
'datetime' => 'Y-m-d H:i:s',
'time' => 'H:i:s',
],
];
// /**
// * Sample database connection for SQLite3.
// *
// * @var array<string, mixed>
// */
// public array $default = [
// 'database' => 'database.db',
// 'DBDriver' => 'SQLite3',
// 'DBPrefix' => '',
// 'DBDebug' => true,
// 'swapPre' => '',
// 'failover' => [],
// 'foreignKeys' => true,
// 'busyTimeout' => 1000,
// 'dateFormat' => [
// 'date' => 'Y-m-d',
// 'datetime' => 'Y-m-d H:i:s',
// 'time' => 'H:i:s',
// ],
// ];
// /**
// * Sample database connection for Postgre.
// *
// * @var array<string, mixed>
// */
// public array $default = [
// 'DSN' => '',
// 'hostname' => 'localhost',
// 'username' => 'root',
// 'password' => 'root',
// 'database' => 'ci4',
// 'schema' => 'public',
// 'DBDriver' => 'Postgre',
// 'DBPrefix' => '',
// 'pConnect' => false,
// 'DBDebug' => true,
// 'charset' => 'utf8',
// 'swapPre' => '',
// 'failover' => [],
// 'port' => 5432,
// 'dateFormat' => [
// 'date' => 'Y-m-d',
// 'datetime' => 'Y-m-d H:i:s',
// 'time' => 'H:i:s',
// ],
// ];
// /**
// * Sample database connection for SQLSRV.
// *
// * @var array<string, mixed>
// */
// public array $default = [
// 'DSN' => '',
// 'hostname' => 'localhost',
// 'username' => 'root',
// 'password' => 'root',
// 'database' => 'ci4',
// 'schema' => 'dbo',
// 'DBDriver' => 'SQLSRV',
// 'DBPrefix' => '',
// 'pConnect' => false,
// 'DBDebug' => true,
// 'charset' => 'utf8',
// 'swapPre' => '',
// 'encrypt' => false,
// 'failover' => [],
// 'port' => 1433,
// 'dateFormat' => [
// 'date' => 'Y-m-d',
// 'datetime' => 'Y-m-d H:i:s',
// 'time' => 'H:i:s',
// ],
// ];
// /**
// * Sample database connection for OCI8.
// *
// * You may need the following environment variables:
// * NLS_LANG = 'AMERICAN_AMERICA.UTF8'
// * NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS'
// * NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS'
// * NLS_TIMESTAMP_TZ_FORMAT = 'YYYY-MM-DD HH24:MI:SS'
// *
// * @var array<string, mixed>
// */
// public array $default = [
// 'DSN' => 'localhost:1521/XEPDB1',
// 'username' => 'root',
// 'password' => 'root',
// 'DBDriver' => 'OCI8',
// 'DBPrefix' => '',
// 'pConnect' => false,
// 'DBDebug' => true,
// 'charset' => 'AL32UTF8',
// 'swapPre' => '',
// 'failover' => [],
// 'dateFormat' => [
// 'date' => 'Y-m-d',
// 'datetime' => 'Y-m-d H:i:s',
// 'time' => 'H:i:s',
// ],
// ];
/**
* This database connection is used when running PHPUnit database tests.
*
* @var array<string, mixed>
*/
public array $tests = [
'DSN' => '',
'hostname' => '127.0.0.1',
'username' => '',
'password' => '',
'database' => ':memory:',
'DBDriver' => 'SQLite3',
'DBPrefix' => 'db_', // Needed to ensure we're working correctly with prefixes live. DO NOT REMOVE FOR CI DEVS
'pConnect' => false,
'DBDebug' => true,
'charset' => 'utf8',
'DBCollat' => '',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
'foreignKeys' => true,
'busyTimeout' => 1000,
'dateFormat' => [
'date' => 'Y-m-d',
'datetime' => 'Y-m-d H:i:s',
'time' => 'H:i:s',
],
];
public function __construct()
{
parent::__construct();
// Ensure that we always set the database group to 'tests' if
// we are currently running an automated test suite, so that
// we don't overwrite live data on accident.
if (ENVIRONMENT === 'testing') {
$this->defaultGroup = 'tests';
}
}
}

46
app/Config/DocTypes.php Normal file
View File

@ -0,0 +1,46 @@
<?php
namespace Config;
/**
* @immutable
*/
class DocTypes
{
/**
* List of valid document types.
*
* @var array<string, string>
*/
public array $list = [
'xhtml11' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">',
'xhtml1-strict' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
'xhtml1-trans' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
'xhtml1-frame' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">',
'xhtml-basic11' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">',
'html5' => '<!DOCTYPE html>',
'html4-strict' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">',
'html4-trans' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">',
'html4-frame' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">',
'mathml1' => '<!DOCTYPE math SYSTEM "http://www.w3.org/Math/DTD/mathml1/mathml.dtd">',
'mathml2' => '<!DOCTYPE math PUBLIC "-//W3C//DTD MathML 2.0//EN" "http://www.w3.org/Math/DTD/mathml2/mathml2.dtd">',
'svg10' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">',
'svg11' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">',
'svg11-basic' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1 Basic//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-basic.dtd">',
'svg11-tiny' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1 Tiny//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd">',
'xhtml-math-svg-xh' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">',
'xhtml-math-svg-sh' => '<!DOCTYPE svg:svg PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">',
'xhtml-rdfa-1' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">',
'xhtml-rdfa-2' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.1//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-2.dtd">',
];
/**
* Whether to remove the solidus (`/`) character for void HTML elements (e.g. `<input>`)
* for HTML5 compatibility.
*
* Set to:
* `true` - to be HTML5 compatible
* `false` - to be XHTML compatible
*/
public bool $html5 = true;
}

121
app/Config/Email.php Normal file
View File

@ -0,0 +1,121 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Email extends BaseConfig
{
public string $fromEmail = '';
public string $fromName = '';
public string $recipients = '';
/**
* The "user agent"
*/
public string $userAgent = 'CodeIgniter';
/**
* The mail sending protocol: mail, sendmail, smtp
*/
public string $protocol = 'mail';
/**
* The server path to Sendmail.
*/
public string $mailPath = '/usr/sbin/sendmail';
/**
* SMTP Server Hostname
*/
public string $SMTPHost = '';
/**
* SMTP Username
*/
public string $SMTPUser = '';
/**
* SMTP Password
*/
public string $SMTPPass = '';
/**
* SMTP Port
*/
public int $SMTPPort = 25;
/**
* SMTP Timeout (in seconds)
*/
public int $SMTPTimeout = 5;
/**
* Enable persistent SMTP connections
*/
public bool $SMTPKeepAlive = false;
/**
* SMTP Encryption.
*
* @var string '', 'tls' or 'ssl'. 'tls' will issue a STARTTLS command
* to the server. 'ssl' means implicit SSL. Connection on port
* 465 should set this to ''.
*/
public string $SMTPCrypto = 'tls';
/**
* Enable word-wrap
*/
public bool $wordWrap = true;
/**
* Character count to wrap at
*/
public int $wrapChars = 76;
/**
* Type of mail, either 'text' or 'html'
*/
public string $mailType = 'text';
/**
* Character set (utf-8, iso-8859-1, etc.)
*/
public string $charset = 'UTF-8';
/**
* Whether to validate the email address
*/
public bool $validate = false;
/**
* Email Priority. 1 = highest. 5 = lowest. 3 = normal
*/
public int $priority = 3;
/**
* Newline character. (Use “\r\n” to comply with RFC 822)
*/
public string $CRLF = "\r\n";
/**
* Newline character. (Use “\r\n” to comply with RFC 822)
*/
public string $newline = "\r\n";
/**
* Enable BCC Batch Mode.
*/
public bool $BCCBatchMode = false;
/**
* Number of emails in each BCC batch
*/
public int $BCCBatchSize = 200;
/**
* Enable notify message from server
*/
public bool $DSN = false;
}

92
app/Config/Encryption.php Normal file
View File

@ -0,0 +1,92 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Encryption configuration.
*
* These are the settings used for encryption, if you don't pass a parameter
* array to the encrypter for creation/initialization.
*/
class Encryption extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Encryption Key Starter
* --------------------------------------------------------------------------
*
* If you use the Encryption class you must set an encryption key (seed).
* You need to ensure it is long enough for the cipher and mode you plan to use.
* See the user guide for more info.
*/
public string $key = '';
/**
* --------------------------------------------------------------------------
* Encryption Driver to Use
* --------------------------------------------------------------------------
*
* One of the supported encryption drivers.
*
* Available drivers:
* - OpenSSL
* - Sodium
*/
public string $driver = 'OpenSSL';
/**
* --------------------------------------------------------------------------
* SodiumHandler's Padding Length in Bytes
* --------------------------------------------------------------------------
*
* This is the number of bytes that will be padded to the plaintext message
* before it is encrypted. This value should be greater than zero.
*
* See the user guide for more information on padding.
*/
public int $blockSize = 16;
/**
* --------------------------------------------------------------------------
* Encryption digest
* --------------------------------------------------------------------------
*
* HMAC digest to use, e.g. 'SHA512' or 'SHA256'. Default value is 'SHA512'.
*/
public string $digest = 'SHA512';
/**
* Whether the cipher-text should be raw. If set to false, then it will be base64 encoded.
* This setting is only used by OpenSSLHandler.
*
* Set to false for CI3 Encryption compatibility.
*/
public bool $rawData = true;
/**
* Encryption key info.
* This setting is only used by OpenSSLHandler.
*
* Set to 'encryption' for CI3 Encryption compatibility.
*/
public string $encryptKeyInfo = '';
/**
* Authentication key info.
* This setting is only used by OpenSSLHandler.
*
* Set to 'authentication' for CI3 Encryption compatibility.
*/
public string $authKeyInfo = '';
/**
* Cipher to use.
* This setting is only used by OpenSSLHandler.
*
* Set to 'AES-128-CBC' to decrypt encrypted data that encrypted
* by CI3 Encryption default configuration.
*/
public string $cipher = 'AES-256-CTR';
}

55
app/Config/Events.php Normal file
View File

@ -0,0 +1,55 @@
<?php
namespace Config;
use CodeIgniter\Events\Events;
use CodeIgniter\Exceptions\FrameworkException;
use CodeIgniter\HotReloader\HotReloader;
/*
* --------------------------------------------------------------------
* Application Events
* --------------------------------------------------------------------
* Events allow you to tap into the execution of the program without
* modifying or extending core files. This file provides a central
* location to define your events, though they can always be added
* at run-time, also, if needed.
*
* You create code that can execute by subscribing to events with
* the 'on()' method. This accepts any form of callable, including
* Closures, that will be executed when the event is triggered.
*
* Example:
* Events::on('create', [$myInstance, 'myMethod']);
*/
Events::on('pre_system', static function (): void {
if (ENVIRONMENT !== 'testing') {
if (ini_get('zlib.output_compression')) {
throw FrameworkException::forEnabledZlibOutputCompression();
}
while (ob_get_level() > 0) {
ob_end_flush();
}
ob_start(static fn ($buffer) => $buffer);
}
/*
* --------------------------------------------------------------------
* Debug Toolbar Listeners.
* --------------------------------------------------------------------
* If you delete, they will no longer be collected.
*/
if (CI_DEBUG && ! is_cli()) {
Events::on('DBQuery', 'CodeIgniter\Debug\Toolbar\Collectors\Database::collect');
Services::toolbar()->respond();
// Hot Reload route - for framework use on the hot reloader.
if (ENVIRONMENT === 'development') {
Services::routes()->get('__hot-reload', static function (): void {
(new HotReloader())->run();
});
}
}
});

106
app/Config/Exceptions.php Normal file
View File

@ -0,0 +1,106 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Debug\ExceptionHandler;
use CodeIgniter\Debug\ExceptionHandlerInterface;
use Psr\Log\LogLevel;
use Throwable;
/**
* Setup how the exception handler works.
*/
class Exceptions extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* LOG EXCEPTIONS?
* --------------------------------------------------------------------------
* If true, then exceptions will be logged
* through Services::Log.
*
* Default: true
*/
public bool $log = true;
/**
* --------------------------------------------------------------------------
* DO NOT LOG STATUS CODES
* --------------------------------------------------------------------------
* Any status codes here will NOT be logged if logging is turned on.
* By default, only 404 (Page Not Found) exceptions are ignored.
*
* @var list<int>
*/
public array $ignoreCodes = [404];
/**
* --------------------------------------------------------------------------
* Error Views Path
* --------------------------------------------------------------------------
* This is the path to the directory that contains the 'cli' and 'html'
* directories that hold the views used to generate errors.
*
* Default: APPPATH.'Views/errors'
*/
public string $errorViewPath = APPPATH . 'Views/errors';
/**
* --------------------------------------------------------------------------
* HIDE FROM DEBUG TRACE
* --------------------------------------------------------------------------
* Any data that you would like to hide from the debug trace.
* In order to specify 2 levels, use "/" to separate.
* ex. ['server', 'setup/password', 'secret_token']
*
* @var list<string>
*/
public array $sensitiveDataInTrace = [];
/**
* --------------------------------------------------------------------------
* WHETHER TO THROW AN EXCEPTION ON DEPRECATED ERRORS
* --------------------------------------------------------------------------
* If set to `true`, DEPRECATED errors are only logged and no exceptions are
* thrown. This option also works for user deprecations.
*/
public bool $logDeprecations = true;
/**
* --------------------------------------------------------------------------
* LOG LEVEL THRESHOLD FOR DEPRECATIONS
* --------------------------------------------------------------------------
* If `$logDeprecations` is set to `true`, this sets the log level
* to which the deprecation will be logged. This should be one of the log
* levels recognized by PSR-3.
*
* The related `Config\Logger::$threshold` should be adjusted, if needed,
* to capture logging the deprecations.
*/
public string $deprecationLogLevel = LogLevel::WARNING;
/*
* DEFINE THE HANDLERS USED
* --------------------------------------------------------------------------
* Given the HTTP status code, returns exception handler that
* should be used to deal with this error. By default, it will run CodeIgniter's
* default handler and display the error information in the expected format
* for CLI, HTTP, or AJAX requests, as determined by is_cli() and the expected
* response format.
*
* Custom handlers can be returned if you want to handle one or more specific
* error codes yourself like:
*
* if (in_array($statusCode, [400, 404, 500])) {
* return new \App\Libraries\MyExceptionHandler();
* }
* if ($exception instanceOf PageNotFoundException) {
* return new \App\Libraries\MyExceptionHandler();
* }
*/
public function handler(int $statusCode, Throwable $exception): ExceptionHandlerInterface
{
return new ExceptionHandler($this);
}
}

29
app/Config/Feature.php Normal file
View File

@ -0,0 +1,29 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Enable/disable backward compatibility breaking features.
*/
class Feature extends BaseConfig
{
/**
* Use improved new auto routing instead of the default legacy version.
*/
public bool $autoRoutesImproved = false;
/**
* Use filter execution order in 4.4 or before.
*/
public bool $oldFilterOrder = false;
/**
* The behavior of `limit(0)` in Query Builder.
*
* If true, `limit(0)` returns all records. (the behavior of 4.4.x or before in version 4.x.)
* If false, `limit(0)` returns no records. (the behavior of 3.1.9 or later in version 3.x.)
*/
public bool $limitZeroAsAll = true;
}

109
app/Config/Filters.php Normal file
View File

@ -0,0 +1,109 @@
<?php
namespace Config;
use CodeIgniter\Config\Filters as BaseFilters;
use CodeIgniter\Filters\Cors;
use CodeIgniter\Filters\CSRF;
use CodeIgniter\Filters\DebugToolbar;
use CodeIgniter\Filters\ForceHTTPS;
use CodeIgniter\Filters\Honeypot;
use CodeIgniter\Filters\InvalidChars;
use CodeIgniter\Filters\PageCache;
use CodeIgniter\Filters\PerformanceMetrics;
use CodeIgniter\Filters\SecureHeaders;
use App\Filters\AuthFilter;
class Filters extends BaseFilters
{
/**
* Configures aliases for Filter classes to
* make reading things nicer and simpler.
*
* @var array<string, class-string|list<class-string>>
*
* [filter_name => classname]
* or [filter_name => [classname1, classname2, ...]]
*/
public array $aliases = [
'csrf' => CSRF::class,
'toolbar' => DebugToolbar::class,
'honeypot' => Honeypot::class,
'invalidchars' => InvalidChars::class,
'secureheaders' => SecureHeaders::class,
'cors' => Cors::class,
'forcehttps' => ForceHTTPS::class,
'pagecache' => PageCache::class,
'performance' => PerformanceMetrics::class,
'authFilter' => AuthFilter::class,
];
/**
* List of special required filters.
*
* The filters listed here are special. They are applied before and after
* other kinds of filters, and always applied even if a route does not exist.
*
* Filters set by default provide framework functionality. If removed,
* those functions will no longer work.
*
* @see https://codeigniter.com/user_guide/incoming/filters.html#provided-filters
*
* @var array{before: list<string>, after: list<string>}
*/
public array $required = [
'before' => [
'forcehttps', // Force Global Secure Requests
'pagecache', // Web Page Caching
],
'after' => [
'pagecache', // Web Page Caching
'performance', // Performance Metrics
'toolbar', // Debug Toolbar
],
];
/**
* List of filter aliases that are always
* applied before and after every request.
*
* @var array<string, array<string, array<string, string>>>|array<string, list<string>>
*/
public array $globals = [
'before' => [
// 'honeypot',
// 'csrf',
// 'invalidchars',
],
'after' => [
// 'honeypot',
// 'secureheaders',
],
];
/**
* List of filter aliases that works on a
* particular HTTP method (GET, POST, etc.).
*
* Example:
* 'POST' => ['foo', 'bar']
*
* If you use this, you should disable auto-routing because auto-routing
* permits any HTTP method to access a controller. Accessing the controller
* with a method you don't expect could bypass the filter.
*
* @var array<string, list<string>>
*/
public array $methods = [];
/**
* List of filter aliases that should run on any
* before or after URI patterns.
*
* Example:
* 'isLoggedIn' => ['before' => ['account/*', 'profiles/*']]
*
* @var array<string, array<string, list<string>>>
*/
public array $filters = [];
}

View File

@ -0,0 +1,12 @@
<?php
namespace Config;
use CodeIgniter\Config\ForeignCharacters as BaseForeignCharacters;
/**
* @immutable
*/
class ForeignCharacters extends BaseForeignCharacters
{
}

77
app/Config/Format.php Normal file
View File

@ -0,0 +1,77 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Format\FormatterInterface;
use CodeIgniter\Format\JSONFormatter;
use CodeIgniter\Format\XMLFormatter;
class Format extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Available Response Formats
* --------------------------------------------------------------------------
*
* When you perform content negotiation with the request, these are the
* available formats that your application supports. This is currently
* only used with the API\ResponseTrait. A valid Formatter must exist
* for the specified format.
*
* These formats are only checked when the data passed to the respond()
* method is an array.
*
* @var list<string>
*/
public array $supportedResponseFormats = [
'application/json',
'application/xml', // machine-readable XML
'text/xml', // human-readable XML
];
/**
* --------------------------------------------------------------------------
* Formatters
* --------------------------------------------------------------------------
*
* Lists the class to use to format responses with of a particular type.
* For each mime type, list the class that should be used. Formatters
* can be retrieved through the getFormatter() method.
*
* @var array<string, string>
*/
public array $formatters = [
'application/json' => JSONFormatter::class,
'application/xml' => XMLFormatter::class,
'text/xml' => XMLFormatter::class,
];
/**
* --------------------------------------------------------------------------
* Formatters Options
* --------------------------------------------------------------------------
*
* Additional Options to adjust default formatters behaviour.
* For each mime type, list the additional options that should be used.
*
* @var array<string, int>
*/
public array $formatterOptions = [
'application/json' => JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES,
'application/xml' => 0,
'text/xml' => 0,
];
/**
* A Factory method to return the appropriate formatter for the given mime type.
*
* @return FormatterInterface
*
* @deprecated This is an alias of `\CodeIgniter\Format\Format::getFormatter`. Use that instead.
*/
public function getFormatter(string $mime)
{
return Services::format()->getFormatter($mime);
}
}

44
app/Config/Generators.php Normal file
View File

@ -0,0 +1,44 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Generators extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Generator Commands' Views
* --------------------------------------------------------------------------
*
* This array defines the mapping of generator commands to the view files
* they are using. If you need to customize them for your own, copy these
* view files in your own folder and indicate the location here.
*
* You will notice that the views have special placeholders enclosed in
* curly braces `{...}`. These placeholders are used internally by the
* generator commands in processing replacements, thus you are warned
* not to delete them or modify the names. If you will do so, you may
* end up disrupting the scaffolding process and throw errors.
*
* YOU HAVE BEEN WARNED!
*
* @var array<string, array<string, string>|string>
*/
public array $views = [
'make:cell' => [
'class' => 'CodeIgniter\Commands\Generators\Views\cell.tpl.php',
'view' => 'CodeIgniter\Commands\Generators\Views\cell_view.tpl.php',
],
'make:command' => 'CodeIgniter\Commands\Generators\Views\command.tpl.php',
'make:config' => 'CodeIgniter\Commands\Generators\Views\config.tpl.php',
'make:controller' => 'CodeIgniter\Commands\Generators\Views\controller.tpl.php',
'make:entity' => 'CodeIgniter\Commands\Generators\Views\entity.tpl.php',
'make:filter' => 'CodeIgniter\Commands\Generators\Views\filter.tpl.php',
'make:migration' => 'CodeIgniter\Commands\Generators\Views\migration.tpl.php',
'make:model' => 'CodeIgniter\Commands\Generators\Views\model.tpl.php',
'make:seeder' => 'CodeIgniter\Commands\Generators\Views\seeder.tpl.php',
'make:validation' => 'CodeIgniter\Commands\Generators\Views\validation.tpl.php',
'session:migration' => 'CodeIgniter\Commands\Generators\Views\migration.tpl.php',
];
}

42
app/Config/Honeypot.php Normal file
View File

@ -0,0 +1,42 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Honeypot extends BaseConfig
{
/**
* Makes Honeypot visible or not to human
*/
public bool $hidden = true;
/**
* Honeypot Label Content
*/
public string $label = 'Fill This Field';
/**
* Honeypot Field Name
*/
public string $name = 'honeypot';
/**
* Honeypot HTML Template
*/
public string $template = '<label>{label}</label><input type="text" name="{name}" value="">';
/**
* Honeypot container
*
* If you enabled CSP, you can remove `style="display:none"`.
*/
public string $container = '<div style="display:none">{template}</div>';
/**
* The id attribute for Honeypot container tag
*
* Used when CSP is enabled.
*/
public string $containerId = 'hpc';
}

31
app/Config/Images.php Normal file
View File

@ -0,0 +1,31 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Images\Handlers\GDHandler;
use CodeIgniter\Images\Handlers\ImageMagickHandler;
class Images extends BaseConfig
{
/**
* Default handler used if no other handler is specified.
*/
public string $defaultHandler = 'gd';
/**
* The path to the image library.
* Required for ImageMagick, GraphicsMagick, or NetPBM.
*/
public string $libraryPath = '/usr/local/bin/convert';
/**
* The available handler classes.
*
* @var array<string, string>
*/
public array $handlers = [
'gd' => GDHandler::class,
'imagick' => ImageMagickHandler::class,
];
}

65
app/Config/Kint.php Normal file
View File

@ -0,0 +1,65 @@
<?php
namespace Config;
use Kint\Parser\ConstructablePluginInterface;
use Kint\Renderer\AbstractRenderer;
use Kint\Renderer\Rich\TabPluginInterface;
use Kint\Renderer\Rich\ValuePluginInterface;
/**
* --------------------------------------------------------------------------
* Kint
* --------------------------------------------------------------------------
*
* We use Kint's `RichRenderer` and `CLIRenderer`. This area contains options
* that you can set to customize how Kint works for you.
*
* @see https://kint-php.github.io/kint/ for details on these settings.
*/
class Kint
{
/*
|--------------------------------------------------------------------------
| Global Settings
|--------------------------------------------------------------------------
*/
/**
* @var list<class-string<ConstructablePluginInterface>|ConstructablePluginInterface>|null
*/
public $plugins;
public int $maxDepth = 6;
public bool $displayCalledFrom = true;
public bool $expanded = false;
/*
|--------------------------------------------------------------------------
| RichRenderer Settings
|--------------------------------------------------------------------------
*/
public string $richTheme = 'aante-light.css';
public bool $richFolder = false;
public int $richSort = AbstractRenderer::SORT_FULL;
/**
* @var array<string, class-string<ValuePluginInterface>>|null
*/
public $richObjectPlugins;
/**
* @var array<string, class-string<TabPluginInterface>>|null
*/
public $richTabPlugins;
/*
|--------------------------------------------------------------------------
| CLI Settings
|--------------------------------------------------------------------------
*/
public bool $cliColors = true;
public bool $cliForceUTF8 = false;
public bool $cliDetectWidth = true;
public int $cliMinWidth = 40;
}

150
app/Config/Logger.php Normal file
View File

@ -0,0 +1,150 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Log\Handlers\FileHandler;
class Logger extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Error Logging Threshold
* --------------------------------------------------------------------------
*
* You can enable error logging by setting a threshold over zero. The
* threshold determines what gets logged. Any values below or equal to the
* threshold will be logged.
*
* Threshold options are:
*
* - 0 = Disables logging, Error logging TURNED OFF
* - 1 = Emergency Messages - System is unusable
* - 2 = Alert Messages - Action Must Be Taken Immediately
* - 3 = Critical Messages - Application component unavailable, unexpected exception.
* - 4 = Runtime Errors - Don't need immediate action, but should be monitored.
* - 5 = Warnings - Exceptional occurrences that are not errors.
* - 6 = Notices - Normal but significant events.
* - 7 = Info - Interesting events, like user logging in, etc.
* - 8 = Debug - Detailed debug information.
* - 9 = All Messages
*
* You can also pass an array with threshold levels to show individual error types
*
* array(1, 2, 3, 8) = Emergency, Alert, Critical, and Debug messages
*
* For a live site you'll usually enable Critical or higher (3) to be logged otherwise
* your log files will fill up very fast.
*
* @var int|list<int>
*/
public $threshold = (ENVIRONMENT === 'production') ? 6 : 9;
/**
* --------------------------------------------------------------------------
* Date Format for Logs
* --------------------------------------------------------------------------
*
* Each item that is logged has an associated date. You can use PHP date
* codes to set your own date formatting
*/
public string $dateFormat = 'Y-m-d H:i:s';
/**
* --------------------------------------------------------------------------
* Log Handlers
* --------------------------------------------------------------------------
*
* The logging system supports multiple actions to be taken when something
* is logged. This is done by allowing for multiple Handlers, special classes
* designed to write the log to their chosen destinations, whether that is
* a file on the getServer, a cloud-based service, or even taking actions such
* as emailing the dev team.
*
* Each handler is defined by the class name used for that handler, and it
* MUST implement the `CodeIgniter\Log\Handlers\HandlerInterface` interface.
*
* The value of each key is an array of configuration items that are sent
* to the constructor of each handler. The only required configuration item
* is the 'handles' element, which must be an array of integer log levels.
* This is most easily handled by using the constants defined in the
* `Psr\Log\LogLevel` class.
*
* Handlers are executed in the order defined in this array, starting with
* the handler on top and continuing down.
*
* @var array<class-string, array<string, int|list<string>|string>>
*/
public array $handlers = [
/*
* --------------------------------------------------------------------
* File Handler
* --------------------------------------------------------------------
*/
FileHandler::class => [
// The log levels that this handler will handle.
'handles' => [
'critical',
'alert',
'emergency',
'debug',
'error',
'info',
'notice',
'warning',
],
/*
* The default filename extension for log files.
* An extension of 'php' allows for protecting the log files via basic
* scripting, when they are to be stored under a publicly accessible directory.
*
* NOTE: Leaving it blank will default to 'log'.
*/
'fileExtension' => '',
/*
* The file system permissions to be applied on newly created log files.
*
* IMPORTANT: This MUST be an integer (no quotes) and you MUST use octal
* integer notation (i.e. 0700, 0644, etc.)
*/
'filePermissions' => 0644,
/*
* Logging Directory Path
*
* By default, logs are written to WRITEPATH . 'logs/'
* Specify a different destination here, if desired.
*/
'path' => '',
],
/*
* The ChromeLoggerHandler requires the use of the Chrome web browser
* and the ChromeLogger extension. Uncomment this block to use it.
*/
// 'CodeIgniter\Log\Handlers\ChromeLoggerHandler' => [
// /*
// * The log levels that this handler will handle.
// */
// 'handles' => ['critical', 'alert', 'emergency', 'debug',
// 'error', 'info', 'notice', 'warning'],
// ],
/*
* The ErrorlogHandler writes the logs to PHP's native `error_log()` function.
* Uncomment this block to use it.
*/
// 'CodeIgniter\Log\Handlers\ErrorlogHandler' => [
// /* The log levels this handler can handle. */
// 'handles' => ['critical', 'alert', 'emergency', 'debug', 'error', 'info', 'notice', 'warning'],
//
// /*
// * The message type where the error should go. Can be 0 or 4, or use the
// * class constants: `ErrorlogHandler::TYPE_OS` (0) or `ErrorlogHandler::TYPE_SAPI` (4)
// */
// 'messageType' => 0,
// ],
];
}

50
app/Config/Migrations.php Normal file
View File

@ -0,0 +1,50 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Migrations extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Enable/Disable Migrations
* --------------------------------------------------------------------------
*
* Migrations are enabled by default.
*
* You should enable migrations whenever you intend to do a schema migration
* and disable it back when you're done.
*/
public bool $enabled = true;
/**
* --------------------------------------------------------------------------
* Migrations Table
* --------------------------------------------------------------------------
*
* This is the name of the table that will store the current migrations state.
* When migrations runs it will store in a database table which migration
* files have already been run.
*/
public string $table = 'migrations';
/**
* --------------------------------------------------------------------------
* Timestamp Format
* --------------------------------------------------------------------------
*
* This is the format that will be used when creating new migrations
* using the CLI command:
* > php spark make:migration
*
* NOTE: if you set an unsupported format, migration runner will not find
* your migration files.
*
* Supported formats:
* - YmdHis_
* - Y-m-d-His_
* - Y_m_d_His_
*/
public string $timestampFormat = 'Y-m-d-His_';
}

536
app/Config/Mimes.php Normal file
View File

@ -0,0 +1,536 @@
<?php
namespace Config;
/**
* Mimes
*
* This file contains an array of mime types. It is used by the
* Upload class to help identify allowed file types.
*
* When more than one variation for an extension exist (like jpg, jpeg, etc)
* the most common one should be first in the array to aid the guess*
* methods. The same applies when more than one mime-type exists for a
* single extension.
*
* When working with mime types, please make sure you have the ´fileinfo´
* extension enabled to reliably detect the media types.
*
* @immutable
*/
class Mimes
{
/**
* Map of extensions to mime types.
*
* @var array<string, list<string>|string>
*/
public static array $mimes = [
'hqx' => [
'application/mac-binhex40',
'application/mac-binhex',
'application/x-binhex40',
'application/x-mac-binhex40',
],
'cpt' => 'application/mac-compactpro',
'csv' => [
'text/csv',
'text/x-comma-separated-values',
'text/comma-separated-values',
'application/vnd.ms-excel',
'application/x-csv',
'text/x-csv',
'application/csv',
'application/excel',
'application/vnd.msexcel',
'text/plain',
],
'bin' => [
'application/macbinary',
'application/mac-binary',
'application/octet-stream',
'application/x-binary',
'application/x-macbinary',
],
'dms' => 'application/octet-stream',
'lha' => 'application/octet-stream',
'lzh' => 'application/octet-stream',
'exe' => [
'application/octet-stream',
'application/vnd.microsoft.portable-executable',
'application/x-dosexec',
'application/x-msdownload',
],
'class' => 'application/octet-stream',
'psd' => [
'application/x-photoshop',
'image/vnd.adobe.photoshop',
],
'so' => 'application/octet-stream',
'sea' => 'application/octet-stream',
'dll' => 'application/octet-stream',
'oda' => 'application/oda',
'pdf' => [
'application/pdf',
'application/force-download',
'application/x-download',
],
'ai' => [
'application/pdf',
'application/postscript',
],
'eps' => 'application/postscript',
'ps' => 'application/postscript',
'smi' => 'application/smil',
'smil' => 'application/smil',
'mif' => 'application/vnd.mif',
'xls' => [
'application/vnd.ms-excel',
'application/msexcel',
'application/x-msexcel',
'application/x-ms-excel',
'application/x-excel',
'application/x-dos_ms_excel',
'application/xls',
'application/x-xls',
'application/excel',
'application/download',
'application/vnd.ms-office',
'application/msword',
],
'ppt' => [
'application/vnd.ms-powerpoint',
'application/powerpoint',
'application/vnd.ms-office',
'application/msword',
],
'pptx' => [
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
],
'wbxml' => 'application/wbxml',
'wmlc' => 'application/wmlc',
'dcr' => 'application/x-director',
'dir' => 'application/x-director',
'dxr' => 'application/x-director',
'dvi' => 'application/x-dvi',
'gtar' => 'application/x-gtar',
'gz' => 'application/x-gzip',
'gzip' => 'application/x-gzip',
'php' => [
'application/x-php',
'application/x-httpd-php',
'application/php',
'text/php',
'text/x-php',
'application/x-httpd-php-source',
],
'php4' => 'application/x-httpd-php',
'php3' => 'application/x-httpd-php',
'phtml' => 'application/x-httpd-php',
'phps' => 'application/x-httpd-php-source',
'js' => [
'application/x-javascript',
'text/plain',
],
'swf' => 'application/x-shockwave-flash',
'sit' => 'application/x-stuffit',
'tar' => 'application/x-tar',
'tgz' => [
'application/x-tar',
'application/x-gzip-compressed',
],
'z' => 'application/x-compress',
'xhtml' => 'application/xhtml+xml',
'xht' => 'application/xhtml+xml',
'zip' => [
'application/x-zip',
'application/zip',
'application/x-zip-compressed',
'application/s-compressed',
'multipart/x-zip',
],
'rar' => [
'application/vnd.rar',
'application/x-rar',
'application/rar',
'application/x-rar-compressed',
],
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mpga' => 'audio/mpeg',
'mp2' => 'audio/mpeg',
'mp3' => [
'audio/mpeg',
'audio/mpg',
'audio/mpeg3',
'audio/mp3',
],
'aif' => [
'audio/x-aiff',
'audio/aiff',
],
'aiff' => [
'audio/x-aiff',
'audio/aiff',
],
'aifc' => 'audio/x-aiff',
'ram' => 'audio/x-pn-realaudio',
'rm' => 'audio/x-pn-realaudio',
'rpm' => 'audio/x-pn-realaudio-plugin',
'ra' => 'audio/x-realaudio',
'rv' => 'video/vnd.rn-realvideo',
'wav' => [
'audio/x-wav',
'audio/wave',
'audio/wav',
],
'bmp' => [
'image/bmp',
'image/x-bmp',
'image/x-bitmap',
'image/x-xbitmap',
'image/x-win-bitmap',
'image/x-windows-bmp',
'image/ms-bmp',
'image/x-ms-bmp',
'application/bmp',
'application/x-bmp',
'application/x-win-bitmap',
],
'gif' => 'image/gif',
'jpg' => [
'image/jpeg',
'image/pjpeg',
],
'jpeg' => [
'image/jpeg',
'image/pjpeg',
],
'jpe' => [
'image/jpeg',
'image/pjpeg',
],
'jp2' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'j2k' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'jpf' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'jpg2' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'jpx' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'jpm' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'mj2' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'mjp2' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'png' => [
'image/png',
'image/x-png',
],
'webp' => 'image/webp',
'tif' => 'image/tiff',
'tiff' => 'image/tiff',
'css' => [
'text/css',
'text/plain',
],
'html' => [
'text/html',
'text/plain',
],
'htm' => [
'text/html',
'text/plain',
],
'shtml' => [
'text/html',
'text/plain',
],
'txt' => 'text/plain',
'text' => 'text/plain',
'log' => [
'text/plain',
'text/x-log',
],
'rtx' => 'text/richtext',
'rtf' => 'text/rtf',
'xml' => [
'application/xml',
'text/xml',
'text/plain',
],
'xsl' => [
'application/xml',
'text/xsl',
'text/xml',
],
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpe' => 'video/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
'avi' => [
'video/x-msvideo',
'video/msvideo',
'video/avi',
'application/x-troff-msvideo',
],
'movie' => 'video/x-sgi-movie',
'doc' => [
'application/msword',
'application/vnd.ms-office',
],
'docx' => [
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/zip',
'application/msword',
'application/x-zip',
],
'dot' => [
'application/msword',
'application/vnd.ms-office',
],
'dotx' => [
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/zip',
'application/msword',
],
'xlsx' => [
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/zip',
'application/vnd.ms-excel',
'application/msword',
'application/x-zip',
],
'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12',
'word' => [
'application/msword',
'application/octet-stream',
],
'xl' => 'application/excel',
'eml' => 'message/rfc822',
'json' => [
'application/json',
'text/json',
],
'pem' => [
'application/x-x509-user-cert',
'application/x-pem-file',
'application/octet-stream',
],
'p10' => [
'application/x-pkcs10',
'application/pkcs10',
],
'p12' => 'application/x-pkcs12',
'p7a' => 'application/x-pkcs7-signature',
'p7c' => [
'application/pkcs7-mime',
'application/x-pkcs7-mime',
],
'p7m' => [
'application/pkcs7-mime',
'application/x-pkcs7-mime',
],
'p7r' => 'application/x-pkcs7-certreqresp',
'p7s' => 'application/pkcs7-signature',
'crt' => [
'application/x-x509-ca-cert',
'application/x-x509-user-cert',
'application/pkix-cert',
],
'crl' => [
'application/pkix-crl',
'application/pkcs-crl',
],
'der' => 'application/x-x509-ca-cert',
'kdb' => 'application/octet-stream',
'pgp' => 'application/pgp',
'gpg' => 'application/gpg-keys',
'sst' => 'application/octet-stream',
'csr' => 'application/octet-stream',
'rsa' => 'application/x-pkcs7',
'cer' => [
'application/pkix-cert',
'application/x-x509-ca-cert',
],
'3g2' => 'video/3gpp2',
'3gp' => [
'video/3gp',
'video/3gpp',
],
'mp4' => 'video/mp4',
'm4a' => 'audio/x-m4a',
'f4v' => [
'video/mp4',
'video/x-f4v',
],
'flv' => 'video/x-flv',
'webm' => 'video/webm',
'aac' => 'audio/x-acc',
'm4u' => 'application/vnd.mpegurl',
'm3u' => 'text/plain',
'xspf' => 'application/xspf+xml',
'vlc' => 'application/videolan',
'wmv' => [
'video/x-ms-wmv',
'video/x-ms-asf',
],
'au' => 'audio/x-au',
'ac3' => 'audio/ac3',
'flac' => 'audio/x-flac',
'ogg' => [
'audio/ogg',
'video/ogg',
'application/ogg',
],
'kmz' => [
'application/vnd.google-earth.kmz',
'application/zip',
'application/x-zip',
],
'kml' => [
'application/vnd.google-earth.kml+xml',
'application/xml',
'text/xml',
],
'ics' => 'text/calendar',
'ical' => 'text/calendar',
'zsh' => 'text/x-scriptzsh',
'7zip' => [
'application/x-compressed',
'application/x-zip-compressed',
'application/zip',
'multipart/x-zip',
],
'cdr' => [
'application/cdr',
'application/coreldraw',
'application/x-cdr',
'application/x-coreldraw',
'image/cdr',
'image/x-cdr',
'zz-application/zz-winassoc-cdr',
],
'wma' => [
'audio/x-ms-wma',
'video/x-ms-asf',
],
'jar' => [
'application/java-archive',
'application/x-java-application',
'application/x-jar',
'application/x-compressed',
],
'svg' => [
'image/svg+xml',
'image/svg',
'application/xml',
'text/xml',
],
'vcf' => 'text/x-vcard',
'srt' => [
'text/srt',
'text/plain',
],
'vtt' => [
'text/vtt',
'text/plain',
],
'ico' => [
'image/x-icon',
'image/x-ico',
'image/vnd.microsoft.icon',
],
'stl' => [
'application/sla',
'application/vnd.ms-pki.stl',
'application/x-navistyle',
],
];
/**
* Attempts to determine the best mime type for the given file extension.
*
* @return string|null The mime type found, or none if unable to determine.
*/
public static function guessTypeFromExtension(string $extension)
{
$extension = trim(strtolower($extension), '. ');
if (! array_key_exists($extension, static::$mimes)) {
return null;
}
return is_array(static::$mimes[$extension]) ? static::$mimes[$extension][0] : static::$mimes[$extension];
}
/**
* Attempts to determine the best file extension for a given mime type.
*
* @param string|null $proposedExtension - default extension (in case there is more than one with the same mime type)
*
* @return string|null The extension determined, or null if unable to match.
*/
public static function guessExtensionFromType(string $type, ?string $proposedExtension = null)
{
$type = trim(strtolower($type), '. ');
$proposedExtension = trim(strtolower($proposedExtension ?? ''));
if (
$proposedExtension !== ''
&& array_key_exists($proposedExtension, static::$mimes)
&& in_array($type, (array) static::$mimes[$proposedExtension], true)
) {
// The detected mime type matches with the proposed extension.
return $proposedExtension;
}
// Reverse check the mime type list if no extension was proposed.
// This search is order sensitive!
foreach (static::$mimes as $ext => $types) {
if (in_array($type, (array) $types, true)) {
return $ext;
}
}
return null;
}
}

84
app/Config/Modules.php Normal file
View File

@ -0,0 +1,84 @@
<?php
namespace Config;
use CodeIgniter\Modules\Modules as BaseModules;
/**
* Modules Configuration.
*
* NOTE: This class is required prior to Autoloader instantiation,
* and does not extend BaseConfig.
*
* @immutable
*/
class Modules extends BaseModules
{
/**
* --------------------------------------------------------------------------
* Enable Auto-Discovery?
* --------------------------------------------------------------------------
*
* If true, then auto-discovery will happen across all elements listed in
* $aliases below. If false, no auto-discovery will happen at all,
* giving a slight performance boost.
*
* @var bool
*/
public $enabled = true;
/**
* --------------------------------------------------------------------------
* Enable Auto-Discovery Within Composer Packages?
* --------------------------------------------------------------------------
*
* If true, then auto-discovery will happen across all namespaces loaded
* by Composer, as well as the namespaces configured locally.
*
* @var bool
*/
public $discoverInComposer = true;
/**
* The Composer package list for Auto-Discovery
* This setting is optional.
*
* E.g.:
* [
* 'only' => [
* // List up all packages to auto-discover
* 'codeigniter4/shield',
* ],
* ]
* or
* [
* 'exclude' => [
* // List up packages to exclude.
* 'pestphp/pest',
* ],
* ]
*
* @var array{only?: list<string>, exclude?: list<string>}
*/
public $composerPackages = [];
/**
* --------------------------------------------------------------------------
* Auto-Discovery Rules
* --------------------------------------------------------------------------
*
* Aliases list of all discovery classes that will be active and used during
* the current application request.
*
* If it is not listed, only the base application elements will be used.
*
* @var list<string>
*/
public $aliases = [
'events',
'filters',
'registrars',
'routes',
'services',
];
}

32
app/Config/Optimize.php Normal file
View File

@ -0,0 +1,32 @@
<?php
namespace Config;
/**
* Optimization Configuration.
*
* NOTE: This class does not extend BaseConfig for performance reasons.
* So you cannot replace the property values with Environment Variables.
*
* @immutable
*/
class Optimize
{
/**
* --------------------------------------------------------------------------
* Config Caching
* --------------------------------------------------------------------------
*
* @see https://codeigniter.com/user_guide/concepts/factories.html#config-caching
*/
public bool $configCacheEnabled = false;
/**
* --------------------------------------------------------------------------
* Config Caching
* --------------------------------------------------------------------------
*
* @see https://codeigniter.com/user_guide/concepts/autoloader.html#file-locator-caching
*/
public bool $locatorCacheEnabled = false;
}

37
app/Config/Pager.php Normal file
View File

@ -0,0 +1,37 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Pager extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Templates
* --------------------------------------------------------------------------
*
* Pagination links are rendered out using views to configure their
* appearance. This array contains aliases and the view names to
* use when rendering the links.
*
* Within each view, the Pager object will be available as $pager,
* and the desired group as $pagerGroup;
*
* @var array<string, string>
*/
public array $templates = [
'default_full' => 'CodeIgniter\Pager\Views\default_full',
'default_simple' => 'CodeIgniter\Pager\Views\default_simple',
'default_head' => 'CodeIgniter\Pager\Views\default_head',
];
/**
* --------------------------------------------------------------------------
* Items Per Page
* --------------------------------------------------------------------------
*
* The default number of results shown in a single page.
*/
public int $perPage = 20;
}

75
app/Config/Paths.php Normal file
View File

@ -0,0 +1,75 @@
<?php
namespace Config;
/**
* Paths
*
* Holds the paths that are used by the system to
* locate the main directories, app, system, etc.
*
* Modifying these allows you to restructure your application,
* share a system folder between multiple applications, and more.
*
* All paths are relative to the project's root folder.
*/
class Paths
{
/**
* ---------------------------------------------------------------
* SYSTEM FOLDER NAME
* ---------------------------------------------------------------
*
* This must contain the name of your "system" folder. Include
* the path if the folder is not in the same directory as this file.
*/
public string $systemDirectory = __DIR__ . '/../../vendor/codeigniter4/framework/system';
/**
* ---------------------------------------------------------------
* APPLICATION FOLDER NAME
* ---------------------------------------------------------------
*
* If you want this front controller to use a different "app"
* folder than the default one you can set its name here. The folder
* can also be renamed or relocated anywhere on your server. If
* you do, use a full server path.
*
* @see http://codeigniter.com/user_guide/general/managing_apps.html
*/
public string $appDirectory = __DIR__ . '/..';
/**
* ---------------------------------------------------------------
* WRITABLE DIRECTORY NAME
* ---------------------------------------------------------------
*
* This variable must contain the name of your "writable" directory.
* The writable directory allows you to group all directories that
* need write permission to a single place that can be tucked away
* for maximum security, keeping it out of the app and/or
* system directories.
*/
public string $writableDirectory = __DIR__ . '/../../writable';
/**
* ---------------------------------------------------------------
* TESTS DIRECTORY NAME
* ---------------------------------------------------------------
*
* This variable must contain the name of your "tests" directory.
*/
public string $testsDirectory = __DIR__ . '/../../tests';
/**
* ---------------------------------------------------------------
* VIEW DIRECTORY NAME
* ---------------------------------------------------------------
*
* This variable must contain the name of the directory that
* contains the view files used by your application. By
* default this is in `app/Views`. This value
* is used when no value is provided to `Services::renderer()`.
*/
public string $viewDirectory = __DIR__ . '/../Views';
}

28
app/Config/Publisher.php Normal file
View File

@ -0,0 +1,28 @@
<?php
namespace Config;
use CodeIgniter\Config\Publisher as BasePublisher;
/**
* Publisher Configuration
*
* Defines basic security restrictions for the Publisher class
* to prevent abuse by injecting malicious files into a project.
*/
class Publisher extends BasePublisher
{
/**
* A list of allowed destinations with a (pseudo-)regex
* of allowed files for each destination.
* Attempts to publish to directories not in this list will
* result in a PublisherException. Files that do no fit the
* pattern will cause copy/merge to fail.
*
* @var array<string, string>
*/
public $restrictions = [
ROOTPATH => '*',
FCPATH => '#\.(s?css|js|map|html?|xml|json|webmanifest|ttf|eot|woff2?|gif|jpe?g|tiff?|png|webp|bmp|ico|svg)$#i',
];
}

48
app/Config/Routes.php Normal file
View File

@ -0,0 +1,48 @@
<?php
use CodeIgniter\Router\RouteCollection;
/**
* @var RouteCollection $routes
*/
//추가 Custom RULE 만들때 : ex)UUID형식
$routes->addPlaceholder('uuid', '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}');
//authFilter는 추가적인 작업이 필요
//1. app/Filters/AuthFilter.php
//2. Config/Filters.php -> $aliases = ['authFilter' => AuthFilter::class]
$routes->get('/', 'Home::index');
$routes->group('admin', ['namespace' => 'App\Controllers\Admin', 'filter' => 'authFilter:manager'], function ($routes) {
$routes->get('/', 'Home::index');
$routes->group('user', function ($routes) {
$routes->get('/', 'UserController::index');
});
});
$routes->group('mangboard', ['namespace' => 'App\Controllers\Mangboard'], function ($routes) {
$routes->group('user', function ($routes) {
$routes->get('/', 'UserController::index');
$routes->cli('point/(:alpha)/(:num)', 'UserController::point/$1/$2');
$routes->cli('point/(:alpha)/(:num)/(:any)', 'UserController::point/$1/$2/$3');
$routes->cli('level/(:alpha)/(:num)', 'UserController::level/$1/$2');
$routes->cli('check_level', 'UserController::check_level');
$routes->cli('check_level/(:alpha)', 'UserController::check_level/$1');
});
$routes->group('crawler', function ($routes) {
$routes->cli('(:alpha)/(:any)', 'CrawlerController::$1/$2');
$routes->cli('(:alpha)/(:any)/(:any)', 'CrawlerController::$1/$2');
});
});
$routes->group('cloudflare', ['namespace' => 'App\Controllers\Cloudflare'], function ($routes) {
$routes->group('account', function ($routes) {
$routes->get('/', 'AccountController::index');
$routes->post('create', 'AccountController::create');
});
$routes->group('zone', function ($routes) {
$routes->get('/', 'ZoneController::index');
$routes->post('create/(:uuid)', 'RecordController::create/$1');
});
$routes->group('record', function ($routes) {
$routes->get('/', 'RecordController::index');
$routes->post('create/(:uuid)', 'RecordController::create/$1');
});
});

140
app/Config/Routing.php Normal file
View File

@ -0,0 +1,140 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Config;
use CodeIgniter\Config\Routing as BaseRouting;
/**
* Routing configuration
*/
class Routing extends BaseRouting
{
/**
* For Defined Routes.
* An array of files that contain route definitions.
* Route files are read in order, with the first match
* found taking precedence.
*
* Default: APPPATH . 'Config/Routes.php'
*
* @var list<string>
*/
public array $routeFiles = [
APPPATH . 'Config/Routes.php',
];
/**
* For Defined Routes and Auto Routing.
* The default namespace to use for Controllers when no other
* namespace has been specified.
*
* Default: 'App\Controllers'
*/
public string $defaultNamespace = 'App\Controllers';
/**
* For Auto Routing.
* The default controller to use when no other controller has been
* specified.
*
* Default: 'Home'
*/
public string $defaultController = 'Home';
/**
* For Defined Routes and Auto Routing.
* The default method to call on the controller when no other
* method has been set in the route.
*
* Default: 'index'
*/
public string $defaultMethod = 'index';
/**
* For Auto Routing.
* Whether to translate dashes in URIs for controller/method to underscores.
* Primarily useful when using the auto-routing.
*
* Default: false
*/
public bool $translateURIDashes = false;
/**
* Sets the class/method that should be called if routing doesn't
* find a match. It can be the controller/method name like: Users::index
*
* This setting is passed to the Router class and handled there.
*
* If you want to use a closure, you will have to set it in the
* routes file by calling:
*
* $routes->set404Override(function() {
* // Do something here
* });
*
* Example:
* public $override404 = 'App\Errors::show404';
*/
public ?string $override404 = null;
/**
* If TRUE, the system will attempt to match the URI against
* Controllers by matching each segment against folders/files
* in APPPATH/Controllers, when a match wasn't found against
* defined routes.
*
* If FALSE, will stop searching and do NO automatic routing.
*/
public bool $autoRoute = false;
/**
* For Defined Routes.
* If TRUE, will enable the use of the 'prioritize' option
* when defining routes.
*
* Default: false
*/
public bool $prioritize = false;
/**
* For Defined Routes.
* If TRUE, matched multiple URI segments will be passed as one parameter.
*
* Default: false
*/
public bool $multipleSegmentsOneParam = false;
/**
* For Auto Routing (Improved).
* Map of URI segments and namespaces.
*
* The key is the first URI segment. The value is the controller namespace.
* E.g.,
* [
* 'blog' => 'Acme\Blog\Controllers',
* ]
*
* @var array<string, string>
*/
public array $moduleRoutes = [];
/**
* For Auto Routing (Improved).
* Whether to translate dashes in URIs for controller/method to CamelCase.
* E.g., blog-controller -> BlogController
*
* If you enable this, $translateURIDashes is ignored.
*
* Default: false
*/
public bool $translateUriToCamelCase = false;
}

103
app/Config/Security.php Normal file
View File

@ -0,0 +1,103 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Security extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* CSRF Protection Method
* --------------------------------------------------------------------------
*
* Protection Method for Cross Site Request Forgery protection.
*
* @var string 'cookie' or 'session'
*/
public string $csrfProtection = 'cookie';
/**
* --------------------------------------------------------------------------
* CSRF Token Randomization
* --------------------------------------------------------------------------
*
* Randomize the CSRF Token for added security.
*/
public bool $tokenRandomize = false;
/**
* --------------------------------------------------------------------------
* CSRF Token Name
* --------------------------------------------------------------------------
*
* Token name for Cross Site Request Forgery protection.
*/
public string $tokenName = 'csrf_test_name';
/**
* --------------------------------------------------------------------------
* CSRF Header Name
* --------------------------------------------------------------------------
*
* Header name for Cross Site Request Forgery protection.
*/
public string $headerName = 'X-CSRF-TOKEN';
/**
* --------------------------------------------------------------------------
* CSRF Cookie Name
* --------------------------------------------------------------------------
*
* Cookie name for Cross Site Request Forgery protection.
*/
public string $cookieName = 'csrf_cookie_name';
/**
* --------------------------------------------------------------------------
* CSRF Expires
* --------------------------------------------------------------------------
*
* Expiration time for Cross Site Request Forgery protection cookie.
*
* Defaults to two hours (in seconds).
*/
public int $expires = 7200;
/**
* --------------------------------------------------------------------------
* CSRF Regenerate
* --------------------------------------------------------------------------
*
* Regenerate CSRF Token on every submission.
*/
public bool $regenerate = true;
/**
* --------------------------------------------------------------------------
* CSRF Redirect
* --------------------------------------------------------------------------
*
* Redirect to previous page with error on failure.
*
* @see https://codeigniter4.github.io/userguide/libraries/security.html#redirection-on-failure
*/
public bool $redirect = (ENVIRONMENT === 'production');
/**
* --------------------------------------------------------------------------
* CSRF SameSite
* --------------------------------------------------------------------------
*
* Setting for CSRF SameSite cookie token.
*
* Allowed values are: None - Lax - Strict - ''.
*
* Defaults to `Lax` as recommended in this link:
*
* @see https://portswigger.net/web-security/csrf/samesite-cookies
*
* @deprecated `Config\Cookie` $samesite property is used.
*/
public string $samesite = 'Lax';
}

32
app/Config/Services.php Normal file
View File

@ -0,0 +1,32 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseService;
/**
* Services Configuration file.
*
* Services are simply other classes/libraries that the system uses
* to do its job. This is used by CodeIgniter to allow the core of the
* framework to be swapped out easily without affecting the usage within
* the rest of your application.
*
* This file holds any application-specific services, or service overrides
* that you might need. An example has been included with the general
* method format you should use for your service methods. For more examples,
* see the core Services file at system/Config/Services.php.
*/
class Services extends BaseService
{
/*
* public static function example($getShared = true)
* {
* if ($getShared) {
* return static::getSharedInstance('example');
* }
*
* return new \CodeIgniter\Example();
* }
*/
}

127
app/Config/Session.php Normal file
View File

@ -0,0 +1,127 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Session\Handlers\BaseHandler;
use CodeIgniter\Session\Handlers\FileHandler;
class Session extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Session Driver
* --------------------------------------------------------------------------
*
* The session storage driver to use:
* - `CodeIgniter\Session\Handlers\FileHandler`
* - `CodeIgniter\Session\Handlers\DatabaseHandler`
* - `CodeIgniter\Session\Handlers\MemcachedHandler`
* - `CodeIgniter\Session\Handlers\RedisHandler`
*
* @var class-string<BaseHandler>
*/
public string $driver = FileHandler::class;
/**
* --------------------------------------------------------------------------
* Session Cookie Name
* --------------------------------------------------------------------------
*
* The session cookie name, must contain only [0-9a-z_-] characters
*/
public string $cookieName = 'ci_session';
/**
* --------------------------------------------------------------------------
* Session Expiration
* --------------------------------------------------------------------------
*
* The number of SECONDS you want the session to last.
* Setting to 0 (zero) means expire when the browser is closed.
*/
public int $expiration = 7200;
/**
* --------------------------------------------------------------------------
* Session Save Path
* --------------------------------------------------------------------------
*
* The location to save sessions to and is driver dependent.
*
* For the 'files' driver, it's a path to a writable directory.
* WARNING: Only absolute paths are supported!
*
* For the 'database' driver, it's a table name.
* Please read up the manual for the format with other session drivers.
*
* IMPORTANT: You are REQUIRED to set a valid save path!
*/
public string $savePath = WRITEPATH . 'session';
/**
* --------------------------------------------------------------------------
* Session Match IP
* --------------------------------------------------------------------------
*
* Whether to match the user's IP address when reading the session data.
*
* WARNING: If you're using the database driver, don't forget to update
* your session table's PRIMARY KEY when changing this setting.
*/
public bool $matchIP = false;
/**
* --------------------------------------------------------------------------
* Session Time to Update
* --------------------------------------------------------------------------
*
* How many seconds between CI regenerating the session ID.
*/
public int $timeToUpdate = 300;
/**
* --------------------------------------------------------------------------
* Session Regenerate Destroy
* --------------------------------------------------------------------------
*
* Whether to destroy session data associated with the old session ID
* when auto-regenerating the session ID. When set to FALSE, the data
* will be later deleted by the garbage collector.
*/
public bool $regenerateDestroy = false;
/**
* --------------------------------------------------------------------------
* Session Database Group
* --------------------------------------------------------------------------
*
* DB Group for the database session.
*/
public ?string $DBGroup = null;
/**
* --------------------------------------------------------------------------
* Lock Retry Interval (microseconds)
* --------------------------------------------------------------------------
*
* This is used for RedisHandler.
*
* Time (microseconds) to wait if lock cannot be acquired.
* The default is 100,000 microseconds (= 0.1 seconds).
*/
public int $lockRetryInterval = 100_000;
/**
* --------------------------------------------------------------------------
* Lock Max Retries
* --------------------------------------------------------------------------
*
* This is used for RedisHandler.
*
* Maximum number of lock acquisition attempts.
* The default is 300 times. That is lock timeout is about 30 (0.1 * 300)
* seconds.
*/
public int $lockMaxRetries = 300;
}

122
app/Config/Toolbar.php Normal file
View File

@ -0,0 +1,122 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Debug\Toolbar\Collectors\Database;
use CodeIgniter\Debug\Toolbar\Collectors\Events;
use CodeIgniter\Debug\Toolbar\Collectors\Files;
use CodeIgniter\Debug\Toolbar\Collectors\Logs;
use CodeIgniter\Debug\Toolbar\Collectors\Routes;
use CodeIgniter\Debug\Toolbar\Collectors\Timers;
use CodeIgniter\Debug\Toolbar\Collectors\Views;
/**
* --------------------------------------------------------------------------
* Debug Toolbar
* --------------------------------------------------------------------------
*
* The Debug Toolbar provides a way to see information about the performance
* and state of your application during that page display. By default it will
* NOT be displayed under production environments, and will only display if
* `CI_DEBUG` is true, since if it's not, there's not much to display anyway.
*/
class Toolbar extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Toolbar Collectors
* --------------------------------------------------------------------------
*
* List of toolbar collectors that will be called when Debug Toolbar
* fires up and collects data from.
*
* @var list<class-string>
*/
public array $collectors = [
Timers::class,
Database::class,
Logs::class,
Views::class,
// \CodeIgniter\Debug\Toolbar\Collectors\Cache::class,
Files::class,
Routes::class,
Events::class,
];
/**
* --------------------------------------------------------------------------
* Collect Var Data
* --------------------------------------------------------------------------
*
* If set to false var data from the views will not be collected. Useful to
* avoid high memory usage when there are lots of data passed to the view.
*/
public bool $collectVarData = true;
/**
* --------------------------------------------------------------------------
* Max History
* --------------------------------------------------------------------------
*
* `$maxHistory` sets a limit on the number of past requests that are stored,
* helping to conserve file space used to store them. You can set it to
* 0 (zero) to not have any history stored, or -1 for unlimited history.
*/
public int $maxHistory = 20;
/**
* --------------------------------------------------------------------------
* Toolbar Views Path
* --------------------------------------------------------------------------
*
* The full path to the the views that are used by the toolbar.
* This MUST have a trailing slash.
*/
public string $viewsPath = SYSTEMPATH . 'Debug/Toolbar/Views/';
/**
* --------------------------------------------------------------------------
* Max Queries
* --------------------------------------------------------------------------
*
* If the Database Collector is enabled, it will log every query that the
* the system generates so they can be displayed on the toolbar's timeline
* and in the query log. This can lead to memory issues in some instances
* with hundreds of queries.
*
* `$maxQueries` defines the maximum amount of queries that will be stored.
*/
public int $maxQueries = 100;
/**
* --------------------------------------------------------------------------
* Watched Directories
* --------------------------------------------------------------------------
*
* Contains an array of directories that will be watched for changes and
* used to determine if the hot-reload feature should reload the page or not.
* We restrict the values to keep performance as high as possible.
*
* NOTE: The ROOTPATH will be prepended to all values.
*
* @var list<string>
*/
public array $watchedDirectories = [
'app',
];
/**
* --------------------------------------------------------------------------
* Watched File Extensions
* --------------------------------------------------------------------------
*
* Contains an array of file extensions that will be watched for changes and
* used to determine if the hot-reload feature should reload the page or not.
*
* @var list<string>
*/
public array $watchedExtensions = [
'php', 'css', 'js', 'html', 'svg', 'json', 'env',
];
}

252
app/Config/UserAgents.php Normal file
View File

@ -0,0 +1,252 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* -------------------------------------------------------------------
* User Agents
* -------------------------------------------------------------------
*
* This file contains four arrays of user agent data. It is used by the
* User Agent Class to help identify browser, platform, robot, and
* mobile device data. The array keys are used to identify the device
* and the array values are used to set the actual name of the item.
*/
class UserAgents extends BaseConfig
{
/**
* -------------------------------------------------------------------
* OS Platforms
* -------------------------------------------------------------------
*
* @var array<string, string>
*/
public array $platforms = [
'windows nt 10.0' => 'Windows 10',
'windows nt 6.3' => 'Windows 8.1',
'windows nt 6.2' => 'Windows 8',
'windows nt 6.1' => 'Windows 7',
'windows nt 6.0' => 'Windows Vista',
'windows nt 5.2' => 'Windows 2003',
'windows nt 5.1' => 'Windows XP',
'windows nt 5.0' => 'Windows 2000',
'windows nt 4.0' => 'Windows NT 4.0',
'winnt4.0' => 'Windows NT 4.0',
'winnt 4.0' => 'Windows NT',
'winnt' => 'Windows NT',
'windows 98' => 'Windows 98',
'win98' => 'Windows 98',
'windows 95' => 'Windows 95',
'win95' => 'Windows 95',
'windows phone' => 'Windows Phone',
'windows' => 'Unknown Windows OS',
'android' => 'Android',
'blackberry' => 'BlackBerry',
'iphone' => 'iOS',
'ipad' => 'iOS',
'ipod' => 'iOS',
'os x' => 'Mac OS X',
'ppc mac' => 'Power PC Mac',
'freebsd' => 'FreeBSD',
'ppc' => 'Macintosh',
'linux' => 'Linux',
'debian' => 'Debian',
'sunos' => 'Sun Solaris',
'beos' => 'BeOS',
'apachebench' => 'ApacheBench',
'aix' => 'AIX',
'irix' => 'Irix',
'osf' => 'DEC OSF',
'hp-ux' => 'HP-UX',
'netbsd' => 'NetBSD',
'bsdi' => 'BSDi',
'openbsd' => 'OpenBSD',
'gnu' => 'GNU/Linux',
'unix' => 'Unknown Unix OS',
'symbian' => 'Symbian OS',
];
/**
* -------------------------------------------------------------------
* Browsers
* -------------------------------------------------------------------
*
* The order of this array should NOT be changed. Many browsers return
* multiple browser types so we want to identify the subtype first.
*
* @var array<string, string>
*/
public array $browsers = [
'OPR' => 'Opera',
'Flock' => 'Flock',
'Edge' => 'Spartan',
'Edg' => 'Edge',
'Chrome' => 'Chrome',
// Opera 10+ always reports Opera/9.80 and appends Version/<real version> to the user agent string
'Opera.*?Version' => 'Opera',
'Opera' => 'Opera',
'MSIE' => 'Internet Explorer',
'Internet Explorer' => 'Internet Explorer',
'Trident.* rv' => 'Internet Explorer',
'Shiira' => 'Shiira',
'Firefox' => 'Firefox',
'Chimera' => 'Chimera',
'Phoenix' => 'Phoenix',
'Firebird' => 'Firebird',
'Camino' => 'Camino',
'Netscape' => 'Netscape',
'OmniWeb' => 'OmniWeb',
'Safari' => 'Safari',
'Mozilla' => 'Mozilla',
'Konqueror' => 'Konqueror',
'icab' => 'iCab',
'Lynx' => 'Lynx',
'Links' => 'Links',
'hotjava' => 'HotJava',
'amaya' => 'Amaya',
'IBrowse' => 'IBrowse',
'Maxthon' => 'Maxthon',
'Ubuntu' => 'Ubuntu Web Browser',
'Vivaldi' => 'Vivaldi',
];
/**
* -------------------------------------------------------------------
* Mobiles
* -------------------------------------------------------------------
*
* @var array<string, string>
*/
public array $mobiles = [
// legacy array, old values commented out
'mobileexplorer' => 'Mobile Explorer',
// 'openwave' => 'Open Wave',
// 'opera mini' => 'Opera Mini',
// 'operamini' => 'Opera Mini',
// 'elaine' => 'Palm',
'palmsource' => 'Palm',
// 'digital paths' => 'Palm',
// 'avantgo' => 'Avantgo',
// 'xiino' => 'Xiino',
'palmscape' => 'Palmscape',
// 'nokia' => 'Nokia',
// 'ericsson' => 'Ericsson',
// 'blackberry' => 'BlackBerry',
// 'motorola' => 'Motorola'
// Phones and Manufacturers
'motorola' => 'Motorola',
'nokia' => 'Nokia',
'palm' => 'Palm',
'iphone' => 'Apple iPhone',
'ipad' => 'iPad',
'ipod' => 'Apple iPod Touch',
'sony' => 'Sony Ericsson',
'ericsson' => 'Sony Ericsson',
'blackberry' => 'BlackBerry',
'cocoon' => 'O2 Cocoon',
'blazer' => 'Treo',
'lg' => 'LG',
'amoi' => 'Amoi',
'xda' => 'XDA',
'mda' => 'MDA',
'vario' => 'Vario',
'htc' => 'HTC',
'samsung' => 'Samsung',
'sharp' => 'Sharp',
'sie-' => 'Siemens',
'alcatel' => 'Alcatel',
'benq' => 'BenQ',
'ipaq' => 'HP iPaq',
'mot-' => 'Motorola',
'playstation portable' => 'PlayStation Portable',
'playstation 3' => 'PlayStation 3',
'playstation vita' => 'PlayStation Vita',
'hiptop' => 'Danger Hiptop',
'nec-' => 'NEC',
'panasonic' => 'Panasonic',
'philips' => 'Philips',
'sagem' => 'Sagem',
'sanyo' => 'Sanyo',
'spv' => 'SPV',
'zte' => 'ZTE',
'sendo' => 'Sendo',
'nintendo dsi' => 'Nintendo DSi',
'nintendo ds' => 'Nintendo DS',
'nintendo 3ds' => 'Nintendo 3DS',
'wii' => 'Nintendo Wii',
'open web' => 'Open Web',
'openweb' => 'OpenWeb',
// Operating Systems
'android' => 'Android',
'symbian' => 'Symbian',
'SymbianOS' => 'SymbianOS',
'elaine' => 'Palm',
'series60' => 'Symbian S60',
'windows ce' => 'Windows CE',
// Browsers
'obigo' => 'Obigo',
'netfront' => 'Netfront Browser',
'openwave' => 'Openwave Browser',
'mobilexplorer' => 'Mobile Explorer',
'operamini' => 'Opera Mini',
'opera mini' => 'Opera Mini',
'opera mobi' => 'Opera Mobile',
'fennec' => 'Firefox Mobile',
// Other
'digital paths' => 'Digital Paths',
'avantgo' => 'AvantGo',
'xiino' => 'Xiino',
'novarra' => 'Novarra Transcoder',
'vodafone' => 'Vodafone',
'docomo' => 'NTT DoCoMo',
'o2' => 'O2',
// Fallback
'mobile' => 'Generic Mobile',
'wireless' => 'Generic Mobile',
'j2me' => 'Generic Mobile',
'midp' => 'Generic Mobile',
'cldc' => 'Generic Mobile',
'up.link' => 'Generic Mobile',
'up.browser' => 'Generic Mobile',
'smartphone' => 'Generic Mobile',
'cellphone' => 'Generic Mobile',
];
/**
* -------------------------------------------------------------------
* Robots
* -------------------------------------------------------------------
*
* There are hundred of bots but these are the most common.
*
* @var array<string, string>
*/
public array $robots = [
'googlebot' => 'Googlebot',
'msnbot' => 'MSNBot',
'baiduspider' => 'Baiduspider',
'bingbot' => 'Bing',
'slurp' => 'Inktomi Slurp',
'yahoo' => 'Yahoo',
'ask jeeves' => 'Ask Jeeves',
'fastcrawler' => 'FastCrawler',
'infoseek' => 'InfoSeek Robot 1.0',
'lycos' => 'Lycos',
'yandex' => 'YandexBot',
'mediapartners-google' => 'MediaPartners Google',
'CRAZYWEBCRAWLER' => 'Crazy Webcrawler',
'adsbot-google' => 'AdsBot Google',
'feedfetcher-google' => 'Feedfetcher Google',
'curious george' => 'Curious George',
'ia_archiver' => 'Alexa Crawler',
'MJ12bot' => 'Majestic-12',
'Uptimebot' => 'Uptimebot',
];
}

44
app/Config/Validation.php Normal file
View File

@ -0,0 +1,44 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Validation\StrictRules\CreditCardRules;
use CodeIgniter\Validation\StrictRules\FileRules;
use CodeIgniter\Validation\StrictRules\FormatRules;
use CodeIgniter\Validation\StrictRules\Rules;
class Validation extends BaseConfig
{
// --------------------------------------------------------------------
// Setup
// --------------------------------------------------------------------
/**
* Stores the classes that contain the
* rules that are available.
*
* @var list<string>
*/
public array $ruleSets = [
Rules::class,
FormatRules::class,
FileRules::class,
CreditCardRules::class,
];
/**
* Specifies the views that are used to display the
* errors.
*
* @var array<string, string>
*/
public array $templates = [
'list' => 'CodeIgniter\Validation\Views\list',
'single' => 'CodeIgniter\Validation\Views\single',
];
// --------------------------------------------------------------------
// Rules
// --------------------------------------------------------------------
}

62
app/Config/View.php Normal file
View File

@ -0,0 +1,62 @@
<?php
namespace Config;
use CodeIgniter\Config\View as BaseView;
use CodeIgniter\View\ViewDecoratorInterface;
/**
* @phpstan-type parser_callable (callable(mixed): mixed)
* @phpstan-type parser_callable_string (callable(mixed): mixed)&string
*/
class View extends BaseView
{
/**
* When false, the view method will clear the data between each
* call. This keeps your data safe and ensures there is no accidental
* leaking between calls, so you would need to explicitly pass the data
* to each view. You might prefer to have the data stick around between
* calls so that it is available to all views. If that is the case,
* set $saveData to true.
*
* @var bool
*/
public $saveData = true;
/**
* Parser Filters map a filter name with any PHP callable. When the
* Parser prepares a variable for display, it will chain it
* through the filters in the order defined, inserting any parameters.
* To prevent potential abuse, all filters MUST be defined here
* in order for them to be available for use within the Parser.
*
* Examples:
* { title|esc(js) }
* { created_on|date(Y-m-d)|esc(attr) }
*
* @var array<string, string>
* @phpstan-var array<string, parser_callable_string>
*/
public $filters = [];
/**
* Parser Plugins provide a way to extend the functionality provided
* by the core Parser by creating aliases that will be replaced with
* any callable. Can be single or tag pair.
*
* @var array<string, callable|list<string>|string>
* @phpstan-var array<string, list<parser_callable_string>|parser_callable_string|parser_callable>
*/
public $plugins = [];
/**
* View Decorators are class methods that will be run in sequence to
* have a chance to alter the generated output just prior to caching
* the results.
*
* All classes must implement CodeIgniter\View\ViewDecoratorInterface
*
* @var list<class-string<ViewDecoratorInterface>>
*/
public array $decorators = [];
}

View File

@ -0,0 +1,13 @@
<?php
namespace App\Controllers\Admin;
use App\Controllers\CommonController;
class Home extends CommonController
{
public function index(): string
{
return view('welcome_message');
}
}

View File

@ -0,0 +1,29 @@
<?php
namespace App\Controllers\Admin;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use App\Controllers\CommonController;
use App\Models\UserModel;
use App\Traits\AuthTrait;
class UserController extends CommonController
{
use AuthTrait;
private $_model = null;
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
$this->session = $this->session_AuthTrait();
}
private function getModel(): UserModel
{
if ($this->_model === null) {
$this->_model = new UserModel();
}
return $this->_model;
}
}

View File

@ -0,0 +1,58 @@
<?php
namespace App\Controllers;
use App\Entities\UserEntity;
use App\Models\UserModel;
class AuthController extends CommonController
{
public function login()
{
helper(['form']);
$viewDatas = [
'layout' => LAYOUTS['empty'],
'title' => '로그인',
'forms' => [
'attributes' => ['action' => 'post', 'class' => 'row g-3'],
'hiddens' => [RETURN_URL => session()->get(RETURN_URL)],
]
];
return view('auth/login', $viewDatas);
}
public function signin()
{
$id = $this->request->getVar('id');
$passwd = $this->request->getVar('passwd');
$model = new UserModel();
$user = $model->asObject(UserEntity::class)->where('id', $id)->first();
if (is_null($user) || !isset($user->passwd)) {
session()->setFlashdata('error', "사용자ID: {$id}가 존재하지 않습니다.");
return redirect()->back()->withInput();
}
if (password_verify($passwd, $user->passwd)) {
//Session에 Login 정보전달
$authData = [
'uid' => $user->uid,
'name' => $user->name,
'email' => $user->email,
'role' => $user->role,
ISLOGIN => true
];
session()->set($authData);
return redirect()->to($this->request->getVar(RETURN_URL) ? $this->request->getVar(RETURN_URL) : "/");
} else {
session()->setFlashdata('error', '암호가 맞지 않습니다.');
return redirect()->back()->withInput();
}
}
public function logout()
{
//Session에 Login 정보 삭제
session()->set([ISLOGIN => false]);
session_destroy();
return redirect()->route('/');
}
}

View File

@ -0,0 +1,58 @@
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
/**
* Class BaseController
*
* BaseController provides a convenient place for loading components
* and performing functions that are needed by all your controllers.
* Extend this class in any new controllers:
* class Home extends BaseController
*
* For security be sure to declare any new methods as protected or private.
*/
abstract class BaseController extends Controller
{
/**
* Instance of the main Request object.
*
* @var CLIRequest|IncomingRequest
*/
protected $request;
/**
* An array of helpers to be loaded automatically upon
* class instantiation. These helpers will be available
* to all other controllers that extend BaseController.
*
* @var list<string>
*/
protected $helpers = [];
/**
* Be sure to declare properties for any property fetch you initialized.
* The creation of dynamic property is deprecated in PHP 8.2.
*/
// protected $session;
/**
* @return void
*/
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
// Do Not Edit This Line
parent::initController($request, $response, $logger);
// Preload any models, libraries, etc, here.
// E.g.: $this->session = \Config\Services::session();
}
}

View File

@ -0,0 +1,71 @@
<?php
namespace App\Controllers\Cloudflare;
use Psr\Log\LoggerInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\RedirectResponse;
use App\Libraries\MyCloudflare\Account;
use App\Entities\Cloudflare\AccountEntity;
class AccountController extends CloudflareController
{
private $_myLibrary = null;
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
$this->class_name .= "Account";
$this->layout = LAYOUTS['admin'];
$this->title = lang("{$this->class_name}.title");
helper($this->class_name);
}
final protected function getMyLibrary(): Account
{
if ($this->_myLibrary === null) {
$this->_myLibrary = new Account();
}
return $this->_myLibrary;
}
protected function create_init(): void
{
$this->fields = [$this->getMyLibrary()->getMyStorage()::TITLE, 'apikey', 'status'];
$this->filter_fields = ['status'];
$this->action = DB_ACTION['CREATE'];
$this->getMyLibrary()->getMyStorage()->setAction($this->action);
}
// public function create_form(): RedirectResponse|string
// {
// $this->create_init();
// return $this->create_form_process();
// }
protected function create_process_submit(): void
{
$entity = $this->getMyLibrary()->create($this->formDatas);
}
public function create(): RedirectResponse
{
$this->create_init();
$this->formDatas = [];
$this->getFormDatas();
$this->convertFormDatas();
$this->validateFormDatas();
return parent::create_process();
}
protected function index_init(): void
{
$this->fields = [$this->getMyLibrary()->getMyStorage()::TITLE, 'apikey', 'status'];
$this->filter_fields = ['status'];
$this->action = DB_ACTION['CREATE'];
$this->getMyLibrary()->getMyStorage()->setAction($this->action);
helper(['form']);
$this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []];
}
public function index(): string
{
$this->create_init();
return parent::list_process();
}
}

View File

@ -0,0 +1,51 @@
<?php
namespace App\Controllers\Cloudflare;
use App\Controllers\MVController;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use App\Models\Cloudflare\AccountModel;
use App\Models\Cloudflare\API\RecordModel;
use App\Models\Cloudflare\ZoneModel;
use App\Traits\AuthTrait;
abstract class CloudflareController extends MVController
{
use AuthTrait;
private $_accountModel = null;
private $_zoneModel = null;
private $_recordModel = null;
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
$this->class_name = "Cloudflare/";
$this->layout = LAYOUTS['admin'];
$this->session = $this->session_AuthTrait();
}
final protected function getAccountModel(): AccountModel
{
if ($this->_accountModel === null) {
$this->_accountModel = new AccountModel();
}
return $this->_accountModel;
}
final protected function getZoneModel(): ZoneModel
{
if ($this->_zoneModel === null) {
$this->_zoneModel = new ZoneModel();
}
return $this->_zoneModel;
}
final protected function getRecordModel(): RecordModel
{
if ($this->_recordModel === null) {
$this->_recordModel = new RecordModel();
}
return $this->_recordModel;
}
protected function modify_process_submit(): void
{
}
}

View File

@ -0,0 +1,109 @@
<?php
namespace App\Controllers\Cloudflare;
use Psr\Log\LoggerInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\RedirectResponse;
use App\Libraries\MyCloudflare\Record;
use App\Entities\Cloudflare\RecordEntity;
class RecordController extends CloudflareController
{
private $_myLibrary = null;
private $_account_entity = null;
private $_zone_entity = null;
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
$this->class_name .= "Record";
$this->layout = LAYOUTS['admin'];
$this->title = lang("{$this->class_name}.title");
helper($this->class_name);
}
final protected function getMyLibrary(): Record
{
if ($this->_myLibrary === null) {
$this->_myLibrary = new Record($this->_account_entity, $this->_zone_entity);
}
return $this->_myLibrary;
}
protected function getFormFieldInputOption(string $field, array $options = []): array
{
switch ($field) {
case $this->getMyLibrary()->getMyStorage()::PARENT:
$options = [
DEFAULTS['EMPTY'] => lang($this->_className . '.label.' . $field) . ' 선택'
];
$this->getZoneModel()->where('status', DEFAULTS['STATUS']);
$options = $this->getZoneModel()->getFormFieldInputOption($field, $options);
break;
default:
$options = parent::getFormFieldInputOption($field, $options);
break;
}
return $options;
}
//전송된 데이터
protected function getFormData(string $field): void
{
switch ($field) {
case 'hosts':
$this->formDatas[$field] = explode("\n", $this->request->getVar($field));
if (!is_array($this->formDatas[$field]) || !count($this->formDatas[$field])) {
throw new \Exception("호스트명이 정의되지 않았습니다.");
}
break;
default:
$this->formDatas[$field] = $this->request->getVar($field);
break;
}
}
//전송된 데이터 검증
protected function validateFormData(string $field): void
{
switch ($field) {
case 'hosts':
break;
default:
parent::validateFormData($field);
break;
}
}
protected function create_init(): void
{
$this->fields = [
$this->getMyLibrary()->getMyStorage()::PARENT,
'type',
'content',
'proxied',
'hosts',
];
$this->filter_fields = [$this->getMyLibrary()->getMyStorage()::PARENT, 'type', 'proxied'];
$this->action = 'create';
$this->getMyLibrary()->getMyStorage()->setAction($this->action);
}
// public function create_form(): RedirectResponse|string
// {
// return $this->create_form_process();
// }
protected function create_process_submit(): void
{
//Record생성
foreach ($this->formDatas['hosts'] as $host) {
$this->getMyLibrary()->create($host, $this->formDatas);
}
}
public function create(string $zone_uid): RedirectResponse
{
$this->_zone_entity = $this->getZoneModel()->getEntityByPK($zone_uid);
$this->_account_entity = $this->getAccountModel()->getEntityByPK($this->_zone_entity->getParent());
$this->formDatas = [];
$this->getFormDatas();
$this->convertFormDatas();
$this->validateFormDatas();
return parent::create_process();
}
}

View File

@ -0,0 +1,144 @@
<?php
namespace App\Controllers\Cloudflare;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use App\Libraries\MyCloudflare\Zone;
use App\Libraries\MyCloudflare\Record;
class ZoneController extends CloudflareController
{
private $_myLibrary = null;
private $_account_entity = null;
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
$this->class_name .= "Zone";
$this->layout = LAYOUTS['admin'];
$this->title = lang("{$this->class_name}.title");
helper($this->class_name);
}
final protected function getMyLibrary(): Zone
{
if ($this->_myLibrary === null) {
$this->_myLibrary = new Zone($this->_account_entity);
}
return $this->_myLibrary;
}
protected function getFormFieldInputOption(string $field, array $options = []): array
{
switch ($field) {
case $this->getMyLibrary()->getMyStorage()::PARENT:
$options = [
DEFAULTS['EMPTY'] => lang($this->_className . '.label.' . $field) . ' 선택'
];
$this->getAccountModel()->where('status', DEFAULTS['STATUS']);
$options = $this->getAccountModel()->getFormFieldInputOption($field, $options);
break;
case 'type':
case 'proxied':
$options = [
DEFAULTS['EMPTY'] => lang("Cloudflare/Record.label." . $field) . ' 선택',
...lang("Cloudflare/Record.label." . strtoupper($field)),
];
break;
default:
$options = parent::getFormFieldInputOption($field, $options);
break;
}
return $options;
}
protected function getFormFieldRule(string $field, array $rules): array
{
if (is_array($field)) {
throw new \Exception(__FUNCTION__ . "=> field가 array 입니다.\n" . var_export($field, true));
}
switch ($field) {
default:
$rules[$field] = $this->getMyLibrary()->getMyStorage()->getFieldRule($field, $rules);
;
break;
}
return $rules;
}
//전송된 데이터
protected function getFormData(string $field): void
{
switch ($field) {
case 'domains':
$this->formDatas[$field] = explode("\n", $this->request->getVar($field));
if (!is_array($this->formDatas[$field]) || !count($this->formDatas[$field])) {
throw new \Exception("도메인명이 정의되지 않았습니다.");
}
break;
case 'hosts':
$this->formDatas[$field] = $this->request->getVar($field);
if (!is_array($this->formDatas[$field]) || !count($this->formDatas[$field])) {
throw new \Exception("호스트명이 정의되지 않았습니다");
}
break;
default:
$this->formDatas[$field] = $this->request->getVar($field);
break;
}
}
//전송된 데이터 검증
protected function validateFormData(string $field): void
{
switch ($field) {
case 'domains':
case 'hosts':
break;
default:
parent::validateFormData($field);
break;
}
}
protected function create_init(): void
{
$this->fields = [
$this->getMyLibrary()->getMyStorage()::PARENT,
'domains',
'hosts',
'type',
'content',
'proxied',
];
$this->filter_fields = [$this->getMyLibrary()->getMyStorage()::PARENT, 'type', 'proxied'];
$this->action = 'create';
$this->getMyLibrary()->getMyStorage()->setAction($this->action);
}
// public function create_form(): RedirectResponse|string
// {
// return $this->create_form_process();
// }
protected function create_process_submit(): void
{
foreach ($this->formDatas['domains'] as $domain) {
//Zone생성
$zone_entity = $this->getMyLibrary()->create($domain);
//Record생성
$record = new Record($this->_account_entity, $zone_entity);
foreach ($this->formDatas['hosts'] as $host) {
$record->create($host, [
'type' => $this->formDatas['type'],
'content' => $this->formDatas['content'],
'proxied' => $this->formDatas['proxied'],
]);
}
}
}
public function create(string $account_uid): RedirectResponse
{
$this->_account_entity = $this->getAccountModel()->getEntityByPK($account_uid);
$this->formDatas = [];
$this->getFormDatas();
$this->convertFormDatas();
$this->validateFormDatas();
return parent::create_process();
}
}

View File

@ -0,0 +1,32 @@
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
abstract class CommonController extends BaseController
{
private $_attributes = [];
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
}
final public function __get($name)
{
if (!array_key_exists($name, $this->_attributes)) {
return null;
}
return $this->_attributes[$name];
}
final public function __set($name, $value): void
{
$this->_attributes[$name] = $value;
}
final public function getAttributes(): array
{
return $this->_attributes;
}
}

11
app/Controllers/Home.php Normal file
View File

@ -0,0 +1,11 @@
<?php
namespace App\Controllers;
class Home extends CommonController
{
public function index(): string
{
return view('welcome_message');
}
}

View File

@ -0,0 +1,302 @@
<?php
namespace App\Controllers;
use Psr\Log\LoggerInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\RedirectResponse;
abstract class MVController extends CommonController
{
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
helper('common');
}
abstract protected function getMyLibrary(): mixed;
abstract protected function create_process_submit(): void;
abstract protected function modify_process_submit(): void;
//Field별 Form Input Option용
protected function getFormFieldInputOption(string $field, array $options = []): array
{
switch ($field) {
default:
$options = [
"" => lang($this->class_name . '.label.' . $field) . ' 선택',
...lang($this->class_name . '.' . strtoupper($field)),
];
break;
}
return $options;
}
//Field별 Form Input용
protected function getFormFieldInput(string $field, string $value, array $inputs = []): array
{
switch ($field) {
case 'status':
$inputs[$field] = form_dropdown(
$field,
$this->getFormFieldInputOption($field),
$value
);
break;
case 'updated_at':
case 'created_at':
$inputs[$field] = form_input($field, $value, ["class" => " calender"]);
break;
default:
$inputs[$field] = form_input($field, $value);
break;
}
return $inputs;
}
final protected function getFormFieldInputs(array $inputs = []): array
{
foreach ($this->fields as $field) {
if (is_array($field)) {
throw new \Exception(__FUNCTION__ . "에서 field array 입니다.\n" . var_export($field, true));
}
$inputs = $this->getFormFieldInput($field, old($field) ?? DEFAULTS['EMPTY'], $inputs);
}
return $inputs;
}
//전송된 데이터 Rule
protected function getFormFieldRule(string $field, array $rules): array
{
if (is_array($field)) {
throw new \Exception(__FUNCTION__ . "=> field가 array 입니다.\n" . var_export($field, true));
}
switch ($field) {
default:
$rules[$field] = $this->getMyLibrary()->getMyStorage()->getFieldRule($field, $rules);
break;
}
return $rules;
}
final protected function getFormFieldRules(array $rules = []): array
{
foreach ($this->fields as $field) {
$rules = $this->getFormFieldRule($field, $rules);
}
return $rules;
}
//전송된 데이터
protected function getFormData(string $field): void
{
switch ($field) {
default:
$this->formDatas[$field] = $this->request->getVar($field);
break;
}
}
final protected function getFormDatas(): void
{
foreach ($this->fields as $field) {
$this->getFormData($field);
}
}
//전송된 데이터 재정의
protected function convertFormData(string $field): void
{
switch ($field) {
default:
break;
}
}
final protected function convertFormDatas(): void
{
foreach ($this->fields as $field) {
$this->convertFormData($field);
}
}
//전송된 데이터 검증
protected function validateFormData(string $field): void
{
switch ($field) {
default:
if (
!$this->validation->check(
$this->formDatas[$field],
$this->getMyLibrary()->getMyStorage()->getFieldRule($field)
)
) {
throw new \Exception("데이터 검증 오류발생\n" . implode("\n", $this->validation->getError()));
}
break;
}
}
final protected function validateFormDatas(): void
{
//변경할 값 확인 : Upload된 파일 검증시 $this->request->getVar()보다 먼처 체크필요
$this->validation = service('validation');
foreach ($this->fields as $field) {
$this->validateFormData($field);
}
}
// 생성
final protected function create_form_process(): RedirectResponse|string
{
helper(['form']);
try {
$this->forminputs = $this->getFormFieldInputs();
$this->session->keepFlashdata(SESSION_NAMES['RETURN_URL']);
$this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []];
return view(
strtolower($this->class_name) . "/create",
['viewDatas' => $this->getAttributes()]
);
} catch (\Exception $e) {
log_message("error", $e->getMessage());
return redirect()->to($this->session->getFlashdata(SESSION_NAMES['RETURN_URL']) ?: "/")->with(SESSION_NAMES['RETURN_MSG'], $e->getMessage());
}
}
final protected function create_process(): mixed
{
$this->getMyLibrary()->getMyStorage()->transStart();
try {
$this->create_process_submit();
return redirect()->to($this->session->getFlashdata(SESSION_NAMES['RETURN_URL']) ?: "/");
} catch (\Exception $e) {
//Transaction Rollback
$this->getMyLibrary()->getMyStorage()->transRollback();
log_message("error", $e->getMessage());
$this->session->setFlashdata(SESSION_NAMES['RETURN_MSG'], __FUNCTION__ . " 실패하였습니다.\n" . $e->getMessage());
$this->session->keepFlashdata(SESSION_NAMES['RETURN_URL']);
return redirect()->back()->withInput();
}
}
// 수정
final protected function modify_form_process(): RedirectResponse|string
{
helper(['form']);
try {
$this->forminputs = $this->getFormFieldInputs();
$this->session->keepFlashdata(SESSION_NAMES['RETURN_URL']);
$this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []];
return view(
strtolower($this->class_name) . "/modify",
['viewDatas' => $this->getAttributes()]
);
} catch (\Exception $e) {
log_message("error", $e->getMessage());
return redirect()->to($this->session->getFlashdata(SESSION_NAMES['RETURN_URL']) ?: "/")->with(SESSION_NAMES['RETURN_MSG'], $e->getMessage());
}
}
final protected function modify_process(): mixed
{
$this->getMyLibrary()->getMyStorage()->transStart();
try {
$this->modify_process_submit();
return redirect()->to($this->session->getFlashdata(SESSION_NAMES['RETURN_URL']) ?: "/");
} catch (\Exception $e) {
//Transaction Rollback
$this->getMyLibrary()->getMyStorage()->transRollback();
log_message("error", $e->getMessage());
$this->session->setFlashdata(SESSION_NAMES['RETURN_MSG'], __FUNCTION__ . " 실패하였습니다.\n" . $e->getMessage());
$this->session->keepFlashdata(SESSION_NAMES['RETURN_URL']);
return redirect()->back()->withInput();
}
}
// 리스트
protected function list_condition($isTotalCount = false): void
{
//조건절 처리
foreach ($this->filter_fields as $field) {
$this->$field = $this->request->getVar($field) ?? DEFAULTS['EMPTY'];
if ($this->$field !== DEFAULTS['EMPTY']) {
$this->getMyLibrary()->getMyStorage()->setList_FieldFilter($field, $this->$field);
}
}
//검색어 처리
$this->word = $this->request->getVar('word') ?? DEFAULTS['EMPTY'];
if ($this->word !== DEFAULTS['EMPTY']) {
$this->getMyLibrary()->getMyStorage()->setList_WordFilter($this->word);
}
//검색일 처리
$this->start = $this->request->getVar('start') ?? DEFAULTS['EMPTY'];
$this->end = $this->request->getVar('end') ?? DEFAULTS['EMPTY'];
if ($this->start !== DEFAULTS['EMPTY'] && $this->end !== DEFAULTS['EMPTY']) {
$this->getMyLibrary()->getMyStorage()->setList_DateFilter($this->start, $this->end);
}
if (!$isTotalCount) {
//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->getMyLibrary()->getMyStorage()->setList_OrderBy("{$this->order_field} {$this->order_value}");
}
}
}
//Totalcount 처리
protected function list_total(): int
{
$this->list_condition(true);
return $this->getMyLibrary()->getMyStorage()->countAllResults();
}
//PageNation 처리
protected function list_pagination($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') ?: $this->_per_page;
//줄수 처리용
$this->pageOptions = array("" => "줄수선택");
for ($i = 10; $i <= $this->total_count + $this->per_page; $i += 10) {
$this->pageOptions[$i] = $i;
}
// 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 = \Config\Services::pager();
// $this->getMyLibrary()->getMyStorage()->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(): array
{
$this->list_condition();
if (array_key_exists('page', $this->_viewDatas)) {
$this->getMyLibrary()->getMyStorage()->limit(
$this->per_page,
$this->page * $this->per_page - $this->per_page
);
}
return $this->getMyLibrary()->getMyStorage()->findAll();
}
public function list_process(): string
{
try {
//URL처리
$this->uri = $this->request->getUri();
//total 처리
$this->total_count = $this->list_total();
//pagenation 처리
$this->pagination = $this->list_pagination();
//모델 처리
$this->entitys = $this->list_entitys();
// dd($this->getMyLibrary()->getMyStorage()->getLastQuery());
//setting return_url to session flashdata
$this->session->setFlashdata(SESSION_NAMES['RETURN_URL'], current_url() . '?' . $this->request->getUri()->getQuery() ?: "");
return view(
strtolower($this->class_name) . "/index",
['viewDatas' => $this->getAttributes()]
);
} catch (\Exception $e) {
log_message("error", $e->getMessage());
return alert_CommonHelper($e->getMessage(), "back");
// return redirect()->back()->with('return_message', $e->getMessage());
}
}
}

View File

@ -0,0 +1,131 @@
<?php
namespace App\Controllers\Mangboard;
use App\Controllers\CommonController;
use Psr\Log\LoggerInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\HTTP\RequestInterface;
use App\Libraries\MyCrawler\Yamap;
use App\Libraries\MyCrawler\Yamoon;
use App\Libraries\MyCrawler\Sir;
use App\Libraries\MyCrawler\Inven;
use App\Models\Mangboard\UserModel;
use App\Entities\Mangboard\UserEntity;
class CrawlerController extends CommonController
{
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
}
final protected function getUserModel(): UserModel
{
if ($this->_user_model === null) {
return $this->_user_model = new UserModel();
}
return $this->_user_model;
}
final protected function login_process(string $user_id = null): UserEntity
{
$user_id = $user_id ?? getenv("mangboard.login.default.id");
$password = getenv("mangboard.login.default.password");
// $response = $this->getWebLibrary($host)->getResponse(
// getenv("mangboard.host.url") . getenv("mangboard.login.url"),
// "post",
// [
// 'form_params' => [
// 'user_id' => $id,
// 'password' => $password,
// ],
// ]
// );
// if ($response->getStatusCode() == 200) {
// $entity = $this->getUserModel()->getEntityByLoginCheck($id, $password);
// if ($entity === null) {
// throw new \Exception("{$id}는 회원이 아니거나 암호가 맞지 않습니다.");
// }
// } else {
// throw new \Exception("연결실패:" . $response->getStatusCode());
// }
$entity = $this->getUserModel()->getEntityByID($user_id);
if ($entity === null) {
throw new \Exception("{$user_id}로 로그인 실패");
}
log_message("notice", "{$user_id}로 로그인 성공");
return $entity;
}
public function yamap(string $board_name, string $user_id = null, ...$params): void
{
try {
$user_entity = $this->login_process($user_id);
$myCrawler = new Yamap(getenv("yamap.host.url"), $board_name, $user_entity);
//추가옵션
$myCrawler->isDebug = in_array('debug', $params);
$myCrawler->isCopy = in_array('copy', $params);
$myCrawler->execute();
} catch (\Exception $e) {
log_message("warning", sprintf(
"\n---%s 오류---\n%s\n-----------------------------------------\n",
__FUNCTION__,
$e->getMessage()
));
}
}
public function yamoon(string $board_name, string $user_id = null, ...$params): void
{
try {
$user_entity = $this->login_process($user_id);
$myCrawler = new Yamoon(getenv("yamoon.host.url"), $board_name, $user_entity);
//추가옵션
$myCrawler->isDebug = in_array('debug', $params);
$myCrawler->isCopy = in_array('copy', $params);
$myCrawler->execute();
} catch (\Exception $e) {
log_message("warning", sprintf(
"\n---%s 오류---\n%s\n-----------------------------------------\n",
__FUNCTION__,
$e->getMessage()
));
}
}
public function sir(string $board_name, string $user_id = null, ...$params): void
{
try {
$user_entity = $this->login_process($user_id);
$myCrawler = new Sir(getenv("sir.host.url"), $board_name, $user_entity);
//추가옵션
$myCrawler->isDebug = in_array('debug', $params);
$myCrawler->isCopy = in_array('copy', $params);
$myCrawler->execute();
} catch (\Exception $e) {
log_message("warning", sprintf(
"\n---%s 오류---\n%s\n-----------------------------------------\n",
__FUNCTION__,
$e->getMessage()
));
}
}
public function inven(string $board_name, string $user_id = null, ...$params): void
{
// echo "{$board_name}|{$user_id}|", implode("|", $params);
// exit;
try {
$user_entity = $this->login_process($user_id);
$myCrawler = new Inven(getenv("inven.host.url"), $board_name, $user_entity);
//추가옵션
$myCrawler->isDebug = in_array('debug', $params);
$myCrawler->isCopy = in_array('copy', $params);
$myCrawler->execute();
} catch (\Exception $e) {
log_message("warning", sprintf(
"\n---%s 오류---\n%s\n-----------------------------------------\n",
__FUNCTION__,
$e->getMessage()
));
}
}
}

View File

@ -0,0 +1,80 @@
<?php
namespace App\Controllers\Mangboard\Admin;
use App\Controllers\CommonController;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use App\Models\Mangboard\UserModel;
class UserController extends CommonController
{
private $_model = null;
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
}
private function getModel(): UserModel
{
if ($this->_model === null) {
$this->_model = new UserModel();
}
return $this->_model;
}
public function point(string $id, string $point, string $sign = "+"): string
{
try {
$entity = is_numeric($id) ? $this->getModel()->getEntityByPK(intval($id)) : $this->getModel()->getEntityByID($id);
if (!$entity) {
throw new \Exception("해당 {$id}의 회원이 없습니다.");
}
$this->getModel()->setPoint($entity, intval($point), $sign);
return __FUNCTION__ . " 작업이 완료되었습니다.";
} catch (\Exception $e) {
log_message("error", $e->getMessage());
return $e->getMessage();
}
}
public function level(string $id, string $level): string
{
try {
$entity = is_numeric($id) ? $this->getModel()->getEntityByPK(intval($id)) : $this->getModel()->getEntityByID($id);
if (!$entity) {
throw new \Exception("해당 {$id}의 회원이 없습니다.");
}
$this->getModel()->setLevel($entity, intval($level));
log_message("notice", "Mangboard->level 작업이 완료되었습니다.");
return __FUNCTION__ . " 작업이 완료되었습니다.";
} catch (\Exception $e) {
log_message("error", $e->getMessage());
return $e->getMessage();
}
}
public function check_level($id = false): string
{
try {
if (!$id) {
foreach ($this->getModel()->getEntitys() as $entity) {
$level = $this->getModel->checkLevel($entity);
$this->getModel()->setLevel($entity, intval($level));
}
} else {
$entity = is_numeric($id) ? $this->getModel()->getEntityByPK(intval($id)) : $this->getModel()->getEntityByID($id);
if (!$entity) {
throw new \Exception("해당 {$id}의 회원이 없습니다.");
}
$level = $this->getModel->checkLevel($entity);
$this->getModel()->setLevel($entity, intval($level));
}
return __FUNCTION__ . " 작업이 완료되었습니다.";
} catch (\Exception $e) {
log_message("error", $e->getMessage());
return $e->getMessage();
}
}
}

View File

View File

View File

@ -0,0 +1,31 @@
<?php
namespace App\Entities\Cloudflare;
use App\Models\Cloudflare\AccountModel;
use App\Entities\CommonEntity;
class AccountEntity extends CommonEntity
{
public function __toString()
{
return "{$this->getPK()}|{$this->getTitle()}|{$this->getAPIKey()}|{$this->attributes['type']}|{$this->attributes['status']}";
}
public function getPK(): int
{
return $this->attributes[AccountModel::PK];
}
public function getTitle(): string
{
return $this->attributes[AccountModel::TITLE];
}
public function setTitle(string $title): void
{
$this->attributes[AccountModel::TITLE] = $title;
}
//Common Function
public function getAPIKey(): string
{
return $this->attributes['apikey'];
}
}

View File

@ -0,0 +1,31 @@
<?php
namespace App\Entities\Cloudflare;
use App\Models\Cloudflare\API\RecordModel;
use App\Entities\CommonEntity;
class RecordEntity extends CommonEntity
{
public function __toString()
{
return "{$this->getPK()}|{$this->getParent()}|{$this->getTitle()}|{$this->attributes['host']}|{$this->attributes['content']}|{$this->attributes['proxied']}|{$this->attributes['fixed']}|{$this->attributes['locked']}";
}
public function getPK(): int
{
return $this->attributes[RecordModel::PK];
}
public function getTitle(): string
{
return $this->attributes[RecordModel::TITLE];
}
public function setTitle(string $title): void
{
$this->attributes[RecordModel::TITLE] = $title;
}
//Common Function
public function getParent(): string
{
return $this->attributes[RecordModel::PARENT];
}
}

View File

@ -0,0 +1,31 @@
<?php
namespace App\Entities\Cloudflare;
use App\Models\Cloudflare\ZoneModel;
use App\Entities\CommonEntity;
class ZoneEntity extends CommonEntity
{
public function __toString()
{
return "{$this->getPK()}|{$this->getParent()}|{$this->getTitle()}|{$this->attributes['development_mode']}|{$this->attributes['ipv6']}|{$this->attributes['security_level']}";
}
public function getPK(): int
{
return $this->attributes[ZoneModel::PK];
}
public function getTitle(): string
{
return $this->attributes[ZoneModel::TITLE];
}
public function setTitle(string $title): void
{
$this->attributes[ZoneModel::TITLE] = $title;
}
//Common Function
public function getParent(): string
{
return $this->attributes[ZoneModel::PARENT];
}
}

View File

@ -0,0 +1,22 @@
<?php
namespace App\Entities;
use CodeIgniter\Entity\Entity;
abstract class CommonEntity extends Entity
{
protected $datamap = [];
protected $dates = ['created_at', 'updated_at', 'deleted_at'];
protected $casts = [];
public function __construct(array|null $data = null)
{
parent::__construct($data);
}
abstract public function __toString();
abstract public function getPK();
abstract public function getTitle();
abstract public function setTitle(string $tile): void;
}

View File

@ -0,0 +1,44 @@
<?php
namespace App\Entities\Mangboard;
use App\Entities\CommonEntity;
use App\Models\Mangboard\BoardModel;
class BoardEntity extends CommonEntity
{
public function __toString(): string
{
return "{$this->getPK()}|{$this->getTitle()}";
}
public function getTitle(): string
{
return $this->attributes[BoardModel::TITLE];
}
public function setTitle(string $title): void
{
$this->attributes[BoardModel::TITLE] = $title;
}
//Common Function
public function getPK(): int
{
return $this->attributes[BoardModel::PK];
}
public function getImagePath(): string
{
return $this->attributes['image_path'];
}
public function setImagePath(string $image_path): void
{
$this->attributes['image_path'] = $image_path;
}
public function getContent(): string
{
return $this->attributes['content'];
}
public function setContent(string $content): void
{
$this->attributes['content'] = $content;
}
}

View File

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

View File

@ -0,0 +1,60 @@
<?php
namespace App\Entities\Mangboard;
use App\Models\Mangboard\FileModel;
use App\Entities\CommonEntity;
class FileEntity extends CommonEntity
{
public function __toString(): string
{
return "{$this->getPK()}|{$this->getPath()}|{$this->getTitle()}|{$this->getMimeType()}}|{$this->getSequence()}번째";
}
public function getTitle(): string
{
return $this->attributes[FileModel::TITLE];
}
public function setTitle(string $file_name): void
{
$this->attributes[FileModel::TITLE] = $file_name;
}
//Common Function
public function getPK(): int
{
return $this->attributes[FileModel::PK];
}
public function getPath(): string
{
return $this->attributes['file_path'];
}
public function setPath(string $file_path): void
{
$this->attributes['file_path'] = $file_path;
}
final public function getMimeType(): string
{
return $this->attributes['file_type'];
}
public function setMimeType(string $mimetype): void
{
$this->attributes['file_type'] = $mimetype;
}
final public function getSize(): int
{
return $this->attributes['file_size'];
}
public function setSize(int $file_size): void
{
$this->attributes['file_size'] = $file_size;
}
//한게시물에 여러개가 있을경우 번호
final public function getSequence(): int
{
return $this->attributes['file_sequence'];
}
public function setSequence(int $file_sequence): void
{
$this->attributes['file_sequence'] = $file_sequence;
}
}

View File

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

View File

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

View File

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

0
app/Filters/.gitkeep Normal file
View File

View File

@ -0,0 +1,65 @@
<?php
namespace App\Filters;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
class AuthFilter implements FilterInterface
{
/**
* Do whatever processing this filter needs to do.
* By default it should not return anything during
* normal execution. However, when an abnormal state
* is found, it should return an instance of
* CodeIgniter\HTTP\Response. If it does, script
* execution will end and that Response will be
* sent back to the client, allowing for error pages,
* redirects, etc.
*
* @param RequestInterface $request
* @param array|null $arguments
*
* @return mixed
*/
public function before(RequestInterface $request, $arguments = null)
{
// 로그인을 했으면
if (session()->get(SESSION['NAMES']['ISLOGIN'])) {
$auth = session()->get(SESSION['NAMES']['AUTH']);
// 회원 ROLES이 필요ROLE($arguments[0]) 목록에 존재하지 않으면(ACL)
if (!in_array($arguments[0], explode(DEFAULTS['DELIMITER_ROLE'], $auth[AUTH['FIELDS']['ROLE']]))) {
return redirect()->to(URLS['LOGIN'])->with(
'return_message',
sprintf(
"%s,%s회원님은 접속에 필요한 권한[%s]이 없습니다. ",
$auth[AUTH['FIELDS']['ROLE']],
$auth[AUTH['FIELDS']['TITLE']],
implode(",", $arguments)
)
);
}
} else {
session()->setFlashdata(SESSION['NAMES']['RETURN_URL'], $request->getUri()->getPath() . '?' . $request->getUri()->getQuery());
return redirect()->to(URLS['LOGIN'])->with('return_message', '로그인을하셔야합니다.');
}
}
/**
* Allows After filters to inspect and modify the response
* object as needed. This method does not allow any way
* to stop execution of other after filters, short of
* throwing an Exception or Error.
*
* @param RequestInterface $request
* @param ResponseInterface $response
* @param array|null $arguments
*
* @return mixed
*/
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
//
}
}

0
app/Helpers/.gitkeep Normal file
View File

View File

@ -0,0 +1 @@
<?php

View File

@ -0,0 +1,223 @@
<?php
//로그인체크 한후 권한체크
function isRole_CommonHelper(array $userRoles, $categoryEntity, $roleField = 'isaccess')
{
return in_array($categoryEntity->getRole($roleField), $userRoles);
}
function getValueByKey_CommonHelper($key, array $attributes)
{
$options = array();
$replace_attributes = array();
foreach ($attributes as $idx => $value) {
if ($idx == $key) {
$replace_attributes[$idx] = $value;
} else {
array_push($options, $value);
}
}
return array($replace_attributes, $options);
}
function getRandomString_CommonHelper($length = 10, $characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
{
return substr(str_shuffle($characters), 0, $length);
}
function getPasswordString_CommonHelper($length = 8)
{
return getRandomString_CommonHelper($length, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-=+;:,.?");
} //
//byte값을 알아보기 쉽게 변환
function getSizeForHuman_CommonHelper($bytes)
{
$ext = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
$unitCount = 0;
for (; $bytes > 1024; $unitCount++) {
$bytes /= 1024;
}
return floor($bytes) . $ext[$unitCount];
} //
//Proxy등을 통하여 Client_IP가 알수없는경우 실제사용자의 IP를 가져오기 위한것
function getClientIP_CommonHelper($clientIP = false)
{
if (isset($_SERVER['HTTP_CLIENT_IP'])) {
$clientIP = $_SERVER['HTTP_CLIENT_IP'];
} else if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$clientIP = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else if (isset($_SERVER['HTTP_X_FORWARDED'])) {
$clientIP = $_SERVER['HTTP_X_FORWARDED'];
} else if (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
$clientIP = $_SERVER['HTTP_FORWARDED_FOR'];
} else if (isset($_SERVER['HTTP_FORWARDED'])) {
$clientIP = $_SERVER['HTTP_FORWARDED'];
} else if (isset($_SERVER['REMOTE_ADDR'])) {
$clientIP = $_SERVER['REMOTE_ADDR'];
}
return $clientIP;
} //
function isDomain_CommonHelper(string $domain): bool
{
$parttern_validation = '/((http|https)\:\/\/)?[a-zA-Z0-9\.\/\?\:@\-_=#]+\.([a-zA-Z0-9\&\.\/\?\:@\-_=#])*/';
return preg_match("$parttern_validation", $domain);
}
function isIPAddress_CommonHelper(string $ip, $type = false): bool
{
switch ($type) {
case 'ipv4':
return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
break;
case 'ipv6':
return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
break;
case 'all':
return filter_var($ip, FILTER_VALIDATE_IP);
break;
default:
return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
break;
}
}
function isHost_CommonHelper(string $host): bool
{
$parttern_validation = '/[a-zA-Z0-9\.\/\?\:@\*\-_=#]/';
return preg_match($parttern_validation, $host);
}
//(EX:192.168.1.0 -> 192.168.001.000)
function convertIPV4toCIDR_CommonHelper($cidr)
{
$temps = explode(".", $cidr);
return sprintf("%03d.%03d.%03d.%03d", $temps[0], $temps[1], $temps[2], $temps[3]);
} //
//(EX:192.168.001.0000 -> 192.168.1.0)
function convertCIDRtoIPV4_CommonHelper($ipv4)
{
$temps = explode(".", $ipv4);
return sprintf("%d.%d.%d.%d", $temps[0], $temps[1], $temps[2], $temps[3]);
} //
function isMobile_CommonHelper()
{
// Check the server headers to see if they're mobile friendly
if (isset($_SERVER["HTTP_X_WAP_PROFILE"])) {
return true;
}
// If the http_accept header supports wap then it's a mobile too
if (preg_match("/wap\.|\.wap/i", $_SERVER["HTTP_ACCEPT"])) {
return true;
}
// Still no luck? Let's have a look at the user agent on the browser. If it contains
// any of the following, it's probably a mobile device. Kappow!
if (isset($_SERVER["HTTP_USER_AGENT"])) {
$user_agents = array("midp", "j2me", "avantg", "docomo", "novarra", "palmos", "palmsource", "240x320", "opwv", "chtml", "pda", "windows\ ce", "mmp\/", "blackberry", "mib\/", "symbian", "wireless", "nokia", "hand", "mobi", "phone", "cdm", "up\.b", "audio", "SIE\-", "SEC\-", "samsung", "HTC", "mot\-", "mitsu", "sagem", "sony", "alcatel", "lg", "erics", "vx", "NEC", "philips", "mmm", "xx", "panasonic", "sharp", "wap", "sch", "rover", "pocket", "benq", "java", "pt", "pg", "vox", "amoi", "bird", "compal", "kg", "voda", "sany", "kdd", "dbt", "sendo", "sgh", "gradi", "jb", "\d\d\di", "moto");
foreach ($user_agents as $user_string) {
if (preg_match("/" . $user_string . "/i", $_SERVER["HTTP_USER_AGENT"])) {
return true;
}
}
}
// Let's NOT return "mobile" if it's an iPhone, because the iPhone can render normal pages quite well.
if (preg_match("/iphone/i", $_SERVER["HTTP_USER_AGENT"])) {
return false;
}
// None of the above? Then it's probably not a mobile device.
return false;
} //
function alert_CommonHelper(string $msg, $url = null)
{
$msg = preg_replace("/\r/", "\\r", $msg);
$msg = preg_replace("/\n/", "\\n", $msg);
$msg = preg_replace("/\'/", "\'", $msg);
$msg = preg_replace("/\"/", "\'", $msg);
$msg = "alert(\"{$msg}\");";
switch ($url) {
case 'close':
$msg .= "window.close();";
break;
case 'back':
$msg .= "history.back();";
break;
default:
$msg .= $url ? "location.href=\"{$url}\";" : "";
break;
}
return "<script type=\"text/javascript\">{$msg}</script>";
} //
// STATUS가 use가 아닐때 option을 disabled되게 하기위함 (override form_dropdown)
function form_dropdown_test($data = '', $options = [], $selected = [], $extra = ''): string
{
$defaults = [];
if (is_array($data)) {
if (isset($data['selected'])) {
$selected = $data['selected'];
unset($data['selected']); // select tags don't have a selected attribute
}
if (isset($data['options'])) {
$options = $data['options'];
unset($data['options']); // select tags don't use an options attribute
}
} else {
$defaults = ['name' => $data];
}
if (!is_array($selected)) {
$selected = [$selected];
}
if (!is_array($options)) {
$options = [$options];
}
// If no selected state was submitted we will attempt to set it automatically
if (empty($selected)) {
if (is_array($data)) {
if (isset($data['name'], $_POST[$data['name']])) {
$selected = [$_POST[$data['name']]];
}
} elseif (isset($_POST[$data])) {
$selected = [$_POST[$data]];
}
}
// Standardize selected as strings, like the option keys will be
foreach ($selected as $key => $item) {
$selected[$key] = (string) $item;
}
$extra = stringify_attributes($extra);
$multiple = (count($selected) > 1 && stripos($extra, 'multiple') === false) ? ' multiple="multiple"' : '';
$form = '<select ' . rtrim(parse_form_attributes($data, $defaults)) . $extra . $multiple . ">\n";
foreach ($options as $key => $val) {
// Keys should always be strings for strict comparison
$key = (string) $key;
if (is_array($val)) {
if (empty($val)) {
continue;
}
$form .= '<optgroup label="' . $key . "\">\n";
foreach ($val as $optgroupKey => $optgroupVal) {
// Keys should always be strings for strict comparison
$optgroupKey = (string) $optgroupKey;
$sel = in_array($optgroupKey, $selected, true) ? ' selected="selected"' : '';
$form .= '<option value="' . $optgroupKey . '"' . $sel . '>' . $optgroupVal . "</option>\n";
}
$form .= "</optgroup>\n";
} else {
$form .= '<option value="' . $key . '"'
. (in_array($key, $selected, true) ? ' selected="selected"' : '') . '>'
. $val . "</option>\n";
}
}
return $form . "</select>\n";
}

0
app/Language/.gitkeep Normal file
View File

View File

@ -0,0 +1,22 @@
<?php
return [
'title' => "Account정보",
'label' => [
'uid' => "번호",
'id' => "인증ID",
'apikey' => "인증Key",
'oldkey' => "이전인증Key",
'type' => "가입방식",
'status' => "상태",
'updated_at' => "수정일",
'created_at' => "작성일"
],
"TYPE" => [
"standard" => "standard",
"enterprise" => "enterprise"
],
"STATUS" => [
"use" => "사용",
"unuse" => "사용않함",
]
];

View File

@ -0,0 +1,47 @@
<?php
return [
'title' => "Record정보",
'label' => [
'uid' => "번호",
'zone_uid' => "도메인",
'type' => "Type",
'host' => "호스트명",
'content' => "IP정보",
'ttl' => "TTL",
'proxiable' => "proxiable",
'fixed' => "CDN잠금",
'proxied' => "CDN기능",
'locked' => "서비스",
'updated_at' => "수정일",
'created_at' => "작성일",
],
"ZONE_UID" => [],
"TYPE" => [
'A' => 'A',
'AAAA' => 'AAAA(ipv6)',
'CNAME' => 'CNAME',
'NS' => 'NS',
'MX' => 'MX',
'PTR' => 'PTR',
'SPF' => 'SPF',
'TXT' => 'TXT',
'SRV' => 'SRV',
'INFO' => 'INFO',
],
"PROXIABLE" => [
"on" => "사용",
"off" => "사용 않함",
],
"FIXED" => [
"on" => "고정 사용",
"off" => "고정 사용 않함",
],
"PROXIED" => [
"on" => "CDN 사용",
"off" => "CDN 사용 않함",
],
"LOCKED" => [
"on" => "운영중",
"off" => "잠김",
],
];

View File

@ -0,0 +1,38 @@
<?php
return [
'title' => "Zone정보",
'label' => [
'uid' => "번호",
'account_uid' => "계정",
'domain' => "도메인",
'name_servers' => "네임서버",
'original_name_servers' => "이전네임서버",
'plan' => "plan",
'development_mode' => "개발모드",
'ipv6' => "ipv6",
'security_level' => "공격방어",
'status' => "서비스",
'updated_at' => "수정일",
'created_at' => "작성일"
],
"ACCOUNT_UID" => [
],
"DEVELOPMENT_MODE" => [
"on" => "사용",
"off" => "사용않함",
],
"IPV6" => [
"on" => "사용",
"off" => "사용않함",
],
"SECURITY_LEVEL" => [
"under_attack" => "under_attack",
"medium" => "medium",
"low" => "low",
"essentially_off" => "essentially_off"
],
"STATUS" => [
"active" => "active",
"pending" => "pending",
],
];

View File

@ -0,0 +1,16 @@
<?php
return [
'title' => "URL Mapping 정보",
'label' => [
'uid' => "번호",
'oldurl' => "기존URL",
'newurl' => "신규URL",
'status' => "상태",
'updated_at' => "수정일",
'created_at' => "작성일"
],
"STATUS" => [
"use" => "사용",
"unuse" => "사용않함",
]
];

27
app/Language/en/User.php Normal file
View File

@ -0,0 +1,27 @@
<?php
return [
'title' => "계정정보",
'label' => [
'uid' => "번호",
'id' => "계정",
'passwd' => "암호",
'confirmpassword' => "암호확인",
'email' => "메일",
'role' => "권한",
'name' => "이름",
'status' => "상태",
'updated_at' => "수정일",
'created_at' => "작성일"
],
"ROLE" => [
"member" => "회원",
"manager" => "관리자",
"cloudflare" => "Cloudflare관리자",
"director" => "감독자",
"master" => "마스터"
],
"STATUS" => [
"use" => "사용",
"unuse" => "사용않함",
]
];

View File

@ -0,0 +1,4 @@
<?php
// override core en language system validation or define your own en language validation message
return [];

0
app/Libraries/.gitkeep Normal file
View File

View File

@ -0,0 +1,21 @@
<?php
namespace App\Libraries;
abstract class CommonLibrary
{
private $_attributes = [];
protected function __construct() {}
final public function __get($name)
{
if (!array_key_exists($name, $this->_attributes)) {
return null;
}
return $this->_attributes[$name];
}
final public function __set($name, $value): void
{
$this->_attributes[$name] = $value;
}
}

View File

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

View File

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

View File

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

View File

@ -0,0 +1,70 @@
<?php
namespace App\Libraries\MyCloudflare;
use Cloudflare\API\Adapter\Guzzle;
use App\Models\Cloudflare\AccountModel;
use App\Libraries\MyCloudflare\MyCloudflare;
use App\Entities\Cloudflare\AccountEntity;
class Account extends MyCloudflare
{
private $_myStorage = null;
public function __construct()
{
parent::__construct();
}
final public function getMyStorage(): AccountModel
{
if ($this->_myStorage === null) {
$this->_myStorage = new AccountModel();
}
return $this->_myStorage;
}
//Result 형태
// [
// {"id":"078e88a7735965b661715af13031ecb0",
// "name":"Cloudwin002@idcjp.jp's Auth",
// "type":"standard",
// "settings":{
// "enforce_twofactor":false,
// "api_access_enabled":null,
// "access_approval_expiry":null,
// "use_account_custom_ns_by_default":false
// },
// "legacy_flags":{"enterprise_zone_quota":{"maximum":0,"current":0,"available":0}},
// "created_on":"2017-06-26T05:44:49.470184Z"}
// ]
protected function getArrayByResult($result): array
{
$formDatas[$this->getMyStorage()->getPKField()] = $result->id;
$formDatas[$this->getMyStorage()->getTitleField()] = $result->name;
$formDatas['type'] = $result->type;
$formDatas['status'] = 'use';
$formDatas['updated_at'] = $result->created_on;
$formDatas['created_at'] = $result->created_on;
return $formDatas;
}
public function create(array $formDatas): AccountEntity
{
//Socket용
$cf = $this->getMySocket()->request($formDatas['apikey'])
->post('accounts', [
'name' => $formDatas[$this->getMyStorage()->getTitleField()],
'type' => $formDatas['type'],
]);
$cf = json_decode($cf->getBody());
if (!$cf->success) {
throw new \Exception(__FUNCTION__ . "에서 실패:\n" . var_export($cf, true));
}
//Storage용
$formDatas = $this->getArrayByResult($cf->result);
$entity = $this->getMyStorage()->create($formDatas);
log_message("notice", "Account::" . __FUNCTION__ . "=> 작업을 완료하였습니다.");
return $entity;
}
protected function reload_entity($cf): AccountEntity
{
return $this->getMyStorage()->modify(new AccountEntity, $this->getArrayByResult($cf));
}
}

View File

@ -0,0 +1,67 @@
<?php
namespace App\Libraries\MyCloudflare;
use Cloudflare\API\Adapter\Guzzle;
use App\Libraries\MySocket\CloudflareSocket;
use App\Libraries\CommonLibrary;
abstract class MyCloudflare extends CommonLibrary
{
private $_mySocket = null;
protected function __construct()
{
parent::__construct();
}
abstract protected function getArrayByResult($result): array;
abstract protected function reload_entity($cf): mixed;
abstract public function getMyStorage(): mixed;
final protected function getMySocket(): CloudflareSocket
{
if ($this->_mySocket === null) {
$this->_mySocket = new CloudflareSocket();
}
return $this->_mySocket;
}
//-----------------------필수항목-------------------//
final protected function reload_entitys(string $parent, array $cfs): array
{
$entity_uids = [];
if (count($cfs)) {
$cnt = 1;
foreach ($cfs as $cf) {
$entity = $this->reload_entity($cf);
$entity_uids[] = $entity->getPK();
log_message("debug", "{$cnt}번째: {$entity->getTitle()} 저장");
$cnt++;
}
//부모키를 기준으로 CF에 존재하지 않는 데이터 삭제용
$this->getMyStorage()->where($this->getMyStorage()::PARENT, $parent);
$this->getMyStorage()->whereNotIn($this->getMyStorage()->getPKField(), $entity_uids);
$this->getMyStorage()->delete();
}
return $entity_uids;
}
final protected function reload_cfs(Guzzle $request, $uri): array
{
$page = 1; //Page는 1부터 시작해야함
$perpage_max = getenv("cfmgr.request.perpage.max");
$cfs = [];
do {
$query = [
'page' => $page,
'per_page' => $perpage_max,
'match' => 'all',
];
$cf = $request->get($uri, $query);
$cf = json_decode($cf->getBody());
if (!$cf->success) {
throw new \Exception(__FUNCTION__ . "에서 실패:\n" . var_export($cf, true));
}
$cfs = [$cfs, ...$cf->result];
//Loop 제한 : 한페이지에서 가져온 갯수가 perpage_max보다 적다는것은 더이상 다음페이지기 없으므로 0로 종료시키기 위함
$page = count($cf->result) < $perpage_max ? 0 : $page + 1;
} while (0 < $page);
return $cfs;
}
}

View File

@ -0,0 +1,129 @@
<?php
namespace App\Libraries\MyCloudflare;
use Cloudflare\API\Adapter\Guzzle;
use App\Models\Cloudflare\API\RecordModel;
use App\Libraries\MyCloudflare\MyCloudflare;
use App\Entities\Cloudflare\ZoneEntity;
use App\Entities\Cloudflare\RecordEntity;
use App\Entities\Cloudflare\AccountEntity;
class Record extends MyCloudflare
{
private $_myStorage = null;
private $_account_entity = null;
private $_zone_entity = null;
public function __construct(AccountEntity $account_entity, ZoneEntity $zone_entity)
{
parent::__construct();
$this->_account_entity = $account_entity;
$this->_zone_entity = $zone_entity;
}
protected function getRequest(): Guzzle
{
return $this->getMySocket()->request($this->_account_entity->getAPIKey());
}
final public function getMyStorage(): RecordModel
{
if ($this->_myStorage === null) {
$this->_myStorage = new RecordModel();
}
return $this->_myStorage;
}
protected function getArrayByResult($result): array
{
$formDatas[$this->getMyStorage()->getPKField()] = $result->id;
$formDatas[$this->getMyStorage()::PARENT] = $result->zone_id;
$formDatas[$this->getMyStorage()->getTitleField()] = $result->name;
$formDatas['type'] = $result->type;
$formDatas['content'] = $result->content;
$formDatas['ttl'] = (int)$result->ttl;
$formDatas['proxiable'] = $result->proxiable ? "on" : "off";
$formDatas['proxied'] = $result->proxied ? "on" : "off";
$formDatas['locked'] = "on";
if (isset($result->locked) && $result->locked) {
$formDatas['locked'] = "off";
}
// $formDatas['updated_at'] = $cfResult->modified_on;
$formDatas['created_at'] = $result->created_on;
return $formDatas;
}
public function create(string $host, array $formDatas): RecordEntity
{
//Socket용
//도메인생성을 위해 Cloudflare에 전송
$cf = $this->getRequest()->post('zones/' . $this->_zone_entity->getPK() . '/dns_records', [
'name' => $host,
'type' => $formDatas['type'],
'content' => $formDatas['content'],
'proxied' => isset($formDatas['proxied']) && $formDatas['proxied'] === 'on' ? true : false
]);
$cf = json_decode($cf->getBody());
if (!$cf->success) {
throw new \Exception("Record:" . __FUNCTION__ . "에서 실패:\n" . var_export($cf, true));
}
//Storage용
$formDatas = $this->getArrayByResult($cf->result);
$entity = $this->$this->getMyStorage()->create($formDatas);
log_message("notice", "Record:" . __FUNCTION__ . "=> 작업을 완료하였습니다.");
return $entity;
}
public function modify(RecordEntity $entity, array $formDatas): RecordEntity
{
//TTL값은 CDN(proxied)가 사용함일때는 무조건 1, 않함일때는 120이 적용
$datas = [
'type' => isset($formDatas['type']) ? $formDatas['type'] : $entity->type,
'name' => isset($formDatas['host']) ? $formDatas['host'] : $entity->host,
'content' => isset($formDatas['content']) ? $formDatas['content'] : $entity->content,
'proxied' => $entity->proxied == 'on' ? true : false,
'ttl' => intval($entity->ttl),
];
//변경작업: 2024-08-09
if (isset($formDatas['proxied']) && $formDatas['proxied'] === 'on') {
$datas['proxied'] = true;
$datas['ttl'] = 1;
} elseif (isset($formDatas['proxied']) && $formDatas['proxied'] === 'off') {
$datas['proxied'] = false;
$datas['ttl'] = 120;
}
$cf = $this->getRequest()->put('zones/' . $this->_zone_entity->getPK() . '/dns_records', $datas);
$cf = json_decode($cf->getBody());
if (!$cf->success) {
throw new \Exception("Record:" . __FUNCTION__ . "에서 실패:\n" . var_export($cf, true));
}
log_message("notice", "Record:" . __FUNCTION__ . "=> 작업을 완료하였습니다.");
return $entity;
}
public function delete(RecordEntity $entity): void
{
$cf = $this->getRequest()->delete('zones/' . $this->_zone_entity->getPK() . '/dns_records/' . $entity->getPK());
$cf = json_decode($cf->getBody());
if (!$cf->success) {
throw new \Exception("Record:" . __FUNCTION__ . "에서 실패:\n" . var_export($cf, true));
}
log_message("notice", "Record:" . __FUNCTION__ . "=> 작업을 완료하였습니다.");
}
public function sync(RecordEntity $entity): RecordEntity
{
$cf = $this->getRequest()->get('zones/' . $this->_zone_entity->getPK() . '/dns_records/' . $entity->getPK());
$cf = json_decode($cf->getBody());
if (!$cf->success) {
throw new \Exception(__FUNCTION__ . "에서 실패:\n" . var_export($cf, true));
}
log_message("notice", "Record:" . __FUNCTION__ . "=> 작업을 완료하였습니다.");
$formDatas = $this->getArrayByResult($cf->result);
return $this->$this->getMyStorage()->create($formDatas);
}
protected function reload_entity($cf): RecordEntity
{
return $this->getMyStorage()->modify(new RecordEntity, $this->getArrayByResult($cf));
}
public function reload(): void
{
$cfs = $this->reload_cfs($this->getRequest(), 'zones/' . $this->_zone_entity->getPK() . '/dns_records');
log_message("notice", "-----{$this->_zone_entity->getTitle()} 처리[" . count($cfs) . "개] 시작-----");
$entitys = $this->reload_entitys($this->_zone_entity->getPK(), $cfs);
log_message("notice", "-----{$this->_zone_entity->getTitle()} DB 처리[" . count($entitys) . "개] 완료-----");
}
}

View File

@ -0,0 +1,157 @@
<?php
namespace App\Libraries\MyCloudflare;
use App\Models\Cloudflare\ZoneModel;
use App\Libraries\MyCloudflare\MyCloudflare;
use App\Entities\Cloudflare\ZoneEntity;
use App\Entities\Cloudflare\AccountEntity;
use Cloudflare\API\Adapter\Guzzle;
class Zone extends MyCloudflare
{
private $_myStorage = null;
private $_account_entity = null;
public function __construct(AccountEntity $account_entity)
{
parent::__construct();
$this->_account_entity = $account_entity;
}
private function getRequest(): Guzzle
{
return $this->getMySocket()->request($this->_account_entity->getAPIKey());
}
final public function getMyStorage(): ZoneModel
{
if ($this->_myStorage === null) {
$this->_myStorage = new ZoneModel();
}
return $this->_myStorage;
}
protected function getArrayByResult($result): array
{
$formDatas[$this->getMyStorage()->getPKField()] = $result->id;
$formDatas[$this->getMyStorage()::PARENT] = $result->account->id;
$formDatas[$this->getMyStorage()->getTitleField()] = $result->name;
$formDatas['status'] = $result->status;
//$formDatas['type'] = $result->type; // full 이게있는데 뭔지 잘모름
$formDatas['name_servers'] = 'none';
if (isset($result->name_servers)) {
$formDatas['name_servers'] = is_array($result->name_servers) ?
implode(
',',
$result->name_servers
) : $result->name_servers;
}
$formDatas['original_name_servers'] = 'none';
if (isset($result->original_name_servers)) {
$formDatas['original_name_servers'] = is_array($result->original_name_servers) ?
implode(
',',
$result->original_name_servers
) : $result->original_name_servers;
}
$formDatas['updated_at'] = $result->modified_on;
$formDatas['created_at'] = $result->created_on;
$formDatas['plan'] = $result->plan->name;
return $formDatas;
}
//Cfzone에서 가져온 값을 zone에 setting
final public function getCFSetting(ZoneEntity $entity): ZoneEntity
{
$cf = $this->getRequest()->patch('zones/' . $entity->getPK() . '/settings/');
$cf = json_decode($cf->getBody());
if (!$cf->success) {
throw new \Exception("Zone:" . __FUNCTION__ . "에서 실패:\n" . var_export($cf, true));
}
foreach ($cf->result as $cf) {
switch ($cf->id) {
case 'development_mode':
$entity->development_mode = $cf->value;
break;
case 'ipv6':
$entity->ipv6 = $cf->value;
break;
case 'security_level':
$entity->security_level = $cf->value;
break;
}
}
return $entity;
}
final public function setCFSetting(ZoneEntity $entity, string $field, string $value): ZoneEntity
{
$cf = $this->getRequest()->patch('zones/' . $entity->getPK() . '/settings/' . $field, array('value' => $value));
$cf = json_decode($cf->getBody());
if (!$cf->success || $cf->result->id !== $field) {
throw new \Exception("Zone:" . __FUNCTION__ . "에서 {$field}->{$value} 변경실패:\n" . var_export($cf, true));
}
//최종 결과값은 body->result->id='필드명',body->result->value='on/off'이런식으로 받음
$entity->$field = $cf->result->value;
return $entity;
}
public function create(string $domain, $jump_start = false): ZoneEntity
{
//Socket용
//도메인생성을 위해 Cloudflare에 전송
$cf = $this->getRequest()->post('zones/', [
'accountId' => $this->_account_entity->getPK(),
'name' => $domain,
'jump_start' => $jump_start,
]);
$cf = json_decode($cf->getBody());
if (!$cf->success) {
throw new \Exception("Zone:" . __FUNCTION__ . "에서 실패:\n" . var_export($cf, true));
}
//Storage용
$formDatas = $this->getArrayByResult($cf->result);
$entity = $this->$this->getMyStorage()->create($formDatas);
//아래는 추가 셋팅 ipv6 TurnOFF , //Development mode TurnOFF
$entity = $this->setCFSetting($entity, 'ipv6', 'off');
$entity = $this->setCFSetting($entity, 'development_mode', 'off');
$entity = $this->setCFSetting($entity, 'security_level', 'medium');
log_message("notice", "Zone:" . __FUNCTION__ . "=> 작업을 완료하였습니다.");
return $entity;
}
public function modify(ZoneEntity $entity, array $formDatas): ZoneEntity
{
//ipv6 , //development_mode , //security_level
foreach ($formDatas as $field => $value) {
$entity = $this->setCFSetting($entity, $field, $value);
}
log_message("notice", "Zone:" . __FUNCTION__ . "=> 작업을 완료하였습니다.");
return $entity;
}
public function delete(ZoneEntity $entity): void
{
$cf = $this->getRequest()->delete('zones/' . $entity->getPK());
$cf = json_decode($cf->getBody());
if (!$cf->success) {
throw new \Exception("Zone:" . __FUNCTION__ . "에서 실패:\n" . var_export($cf, true));
}
log_message("notice", "Zone:" . __FUNCTION__ . "=> 작업을 완료하였습니다.");
}
public function sync(ZoneEntity $entity): ZoneEntity
{
$cf = $this->getRequest()->get('zones/' . $entity->getPK());
$cf = json_decode($cf->getBody());
if (!$cf->success) {
throw new \Exception("Zone:" . __FUNCTION__ . "에서 실패:\n" . var_export($cf, true));
}
log_message("notice", "Zone:" . __FUNCTION__ . "=> 작업을 완료하였습니다.");
$formDatas = $this->getArrayByResult($cf->result);
return $this->$this->getMyStorage()->create($formDatas);
}
protected function reload_entity($cf): ZoneEntity
{
return $this->getMyStorage()->modify(new ZoneEntity, $this->getArrayByResult($cf));
}
public function reload(): void
{
$cfs = $this->reload_cfs($this->getRequest(), 'zones');
log_message("notice", "-----{$this->_account_entity->getTitle()} 처리[" . count($cfs) . "개] 시작-----");
$entitys = $this->reload_entitys($this->_account_entity->getPK(), $cfs);
log_message("notice", "-----{$this->_account_entity->getTitle()} DB 처리[" . count($entitys) . "개] 완료-----");
}
}

View File

@ -0,0 +1,120 @@
<?php
namespace App\Libraries\MyCrawler;
use Symfony\Component\DomCrawler\Crawler;
use App\Entities\Mangboard\UserEntity;
class Inven extends MyCrawler
{
public function __construct(string $host, string $board_name, UserEntity $user_entity)
{
parent::__construct($host, $board_name, $user_entity);
}
protected function getUrlByMediaType(Crawler $node, string $media_type, string $attr): null|string
{
switch ($media_type) {
case 'video':
$url = parent::getUrlByMediaType($node, $media_type, $attr);
//그래도 null이면 data-src로 추출해본다.
if ($url === null) {
$attributes = $node->extract(['data-src']);
if (count($attributes)) {
$url = $attributes[0];
}
}
break;
case 'img':
default:
$url = parent::getUrlByMediaType($node, $media_type, $attr);
break;
}
return $url;
}
//작성내용
// <div class="articleContent">
// <div id="imageCollectDiv" class="contentBody">
// <!-- ============== CONTENT ============== -->
// <div id="powerbbsContent">
// <div id="BBSImageHolderTop" style="text-align:center;">
// <img src="https://upload3.inven.co.kr/upload/2024/09/15/bbs/i1620925350.jpg?MW=800" style="max-width: 100%; width: 800px; aspect-ratio: 1080 / 1350;" loading="lazy" />
// <br><br><img src="https://upload3.inven.co.kr/upload/2024/09/15/bbs/i1587803007.jpg?MW=800" style="max-width: 100%; width: 800px; aspect-ratio: 1080 / 1350;" loading="lazy" />
// <br><br><img src="https://upload3.inven.co.kr/upload/2024/09/15/bbs/i1134295360.jpg?MW=800" style="max-width: 100%; width: 800px; aspect-ratio: 1080 / 1350;" loading="lazy" />
// <br><br><img src="https://upload3.inven.co.kr/upload/2024/09/15/bbs/i1481352611.jpg?MW=800" style="max-width: 100%; width: 800px; aspect-ratio: 1080 / 1350;" loading="lazy" />
// <br><br><img src="https://upload3.inven.co.kr/upload/2024/09/15/bbs/i1878651605.jpg?MW=800" style="max-width: 100%; width: 800px; aspect-ratio: 850 / 1063;" loading="lazy" />
// <br><br>
// </div>
// <div>^^</div>
// </div>
// <!-- ============== End CONTENT ============== -->
// </div>
protected function getDetailSelector(array $listInfo): array
{
$response = $this->getMySocket()->getContent($listInfo['detail_url']);
return array($this->getSelector($response, getenv("inven.view.content.tag")), $listInfo);
}
//리스트내용
// <div class="board-list">
// <table>
// <tr class="lgtm">
// <td class="num"><span>1589</span></td>
// <td class="tit">
// <div class="text-wrap">
// <div>
// <span class="user-icon">
// <img src="https://upload3.inven.co.kr/upload/2024/06/12/icon/i1237935053.jpg" alt="유저 아이콘" loading="lazy">
// </span>
// <a class="subject-link" href="https://www.inven.co.kr/board/party/5951/1589">
// <span class="board_name">[사진&움짤]</span>스테이씨 윤
// </a>
// </div>
// <span data-opinion-bbs-comeidx="5951" data-opinion-bbs-uid="1589" data-opinion-bbs-opi="1" class="con-comment">[1]</span>
// <span class="con-icon board-img photo">사진</span>
// </div>
// </td>
// <td class="user">
// <img src="https://static.inven.co.kr/image_2011/member/level/1202/lv32.gif" alt="레벨 아이콘">
// <span class="layerNickName" onclick="layerNickName('배수민', 'pbNickNameHandler'); ">배수민</span>
// </td>
// <td class="date">09-15</td>
// <td class="view">1,502</td>
// <td class="reco">1</td>
// </tr>
// </table>
// </div>
public function execute(): void
{
$listInfos = [];
if ($this->isDebug) {
$listInfo = [];
$listInfo['title'] = 'test_title';
$listInfo['nickname'] = 'test_name';
$listInfo['hit'] = 1;
$listInfo['date'] = date("Y-m-d H:i:s");
$listInfo['detail_url'] = getenv("inven.view.test.url.{$this->getMyStorage()->getBoardName()}");
$listInfos[] = $listInfo;
} else {
$response = $this->getMySocket()->getContent(getenv("inven.list.url.{$this->getMyStorage()->getBoardName()}"));
$this->getSelector($response, getenv("inven.list.tag.{$this->getMyStorage()->getBoardName()}"))->each(
function (Crawler $node) use (&$listInfos): void {
$nickname = $node->filter(getenv("inven.list.item.nickname.tag"))->text();
$hit = $node->filter(getenv("inven.list.item.hit.tag"))->text();
$date = date("Y") . "-" . $node->filter(getenv("inven.list.item.date.tag"))->text();
//title및 detail url
$link_node = $node->filter(getenv("inven.list.item.link.tag"));
$detail_url = $link_node->attr("href");
$title = $link_node->text();
//title에서 예외사항비교
if (strpos($title, getenv("inven.list.tag.except.{$this->getMyStorage()->getBoardName()}")) === false) {
$listInfos[] = ['title' => $title, 'nickname' => $nickname, 'detail_url' => $detail_url, 'date' => $date, 'hit' => $hit];
}
}
);
}
if (!count($listInfos)) {
throw new \Exception("Target URL이 없습니다.");
}
$this->list_process(intval(getenv("inven.list.max_limit.{$this->getMyStorage()->getBoardName()}")), $listInfos);
log_message("notice", __FUNCTION__ . " 작업이 완료되었습니다.");
}
}

View File

@ -0,0 +1,310 @@
<?php
namespace App\Libraries\MyCrawler;
use App\Libraries\MySocket\WebSocket;
use App\Libraries\MyMangboard\Storage;
use Symfony\Component\DomCrawler\Crawler;
use App\Traits\FileTrait;
use App\Models\Mangboard\BoardsModel;
use App\Models\Mangboard\BoardModel;
use App\Libraries\CommonLibrary;
use App\Entities\Mangboard\UserEntity;
use App\Entities\Mangboard\BoardsEntity;
use App\Entities\Mangboard\BoardEntity;
abstract class MyCrawler extends CommonLibrary
{
use FileTrait;
private $_host = "";
private $_board_name = "";
private $_user_entity = null;
private $_mySocket = null;
private $_myStorage = null;
private $_board_model = null;
private $_user_model = null;
private $_boards_entity = null;
protected function __construct(string $host, string $board_name, UserEntity $user_entity)
{
parent::__construct();
$this->_host = $host;
$this->_board_name = $board_name;
$this->_user_entity = $user_entity;
}
abstract protected function getDetailSelector(array $listInfo): array;
//-----------------------필수항목-------------------//
final protected function getMySocket(): WebSocket
{
if ($this->_mySocket === null) {
$this->_mySocket = new WebSocket($this->_host);
}
return $this->_mySocket;
}
final protected function getMyStorage(): Storage
{
if ($this->_myStorage === null) {
$this->_myStorage = new Storage($this->_board_name, $this->_user_entity);
}
return $this->_myStorage;
}
final protected function getBoardsEntity(): BoardsEntity
{
if ($this->_boards_entity === null) {
$boardsModel = new BoardsModel();
$this->_boards_entity = $boardsModel->getEntityByID($this->getMyStorage()->getBoardName());
if ($this->_boards_entity === null) {
throw new \Exception(__FUNCTION__ . "=> {$this->getMyStorage()->getBoardName()}에 해당 Board 정보가 존재하지 않습니다.");
}
}
return $this->_boards_entity;
}
final protected function getBoardModel(): BoardModel
{
if ($this->_board_model === null) {
$this->_board_model = new BoardModel("mb_" . $this->getMyStorage()->getBoardName());
}
return $this->_board_model;
}
final protected function getSelector(string $content, string $tag): Crawler
{
$crawler = new Crawler($content);
if ($this->isDebug) {
log_message("debug", __FUNCTION__ . "=> " . $tag);
}
$crawler->filter($tag);
if ($this->isDebug) {
log_message("debug", sprintf(
"\n------------%s HTML-------------\n%s\n-----------------------------------------------------\n",
__FUNCTION__,
$crawler->filter($tag)->html()
));
}
return $crawler->filter($tag);
}
protected function changeURLByCrawler(string $url): string
{
return preg_match('/^[^?]+/', $url, $matches) ? $matches[0] : null;
}
protected function getUrlByMediaType(Crawler $node, string $media_tag, string $attr): null|string
{
switch ($media_tag) {
case 'video':
$url = $node->attr($attr); //<video src="test.mp4"></video> 또는 <video data-src="test.mp4"></video>
if ($url === null) {
$url = $node->children()->attr("src"); //<video><source src="test.mp4"></source</video>
}
break;
case 'img':
default:
$url = $node->attr($attr);
break;
}
return $url;
}
private function getUrlsByMediaType(Crawler $selector, string $media_tag, string $attr, array $urls = []): array
{
log_message("notice", "-----------" . __FUNCTION__ . "=> {$media_tag} 작업시작--------");
$urls[$media_tag] = [];
$selector->filter($media_tag)->each(
function (Crawler $node) use (&$media_tag, &$attr, &$urls): void {
$url = $this->getUrlByMediaType($node, $media_tag, $attr);
if ($url !== null && preg_match('/^[^?]+/', $url, $matches)) {
$urls[$media_tag][] = $this->changeURLByCrawler($matches[0]);
} else {
log_message("debug", __FUNCTION__ . "-> {$media_tag}:{$attr}\n");
//Node 모든 속성은 DOMElement 변환 후 반환가능
$domNode = $node->getNode(0);
if ($domNode->hasAttributes()) {
foreach ($domNode->attributes as $attr) {
log_message("debug", "{$attr->nodeName} = {$attr->nodeValue}");
}
}
}
}
);
log_message("notice", "-----------" . __FUNCTION__ . "=> {$media_tag} 작업완료--------");
return $urls;
}
private function media_save(int $file_sequence, string $media_tag, string $file_name, string $content): mixed
{
log_message("debug", __FUNCTION__ . " 원본파일 {$file_name} 작업 시작");
$storage = clone $this->getMyStorage();
$storage->setOriginName($file_name);
$storage->setOriginContent($content);
$storage->setOriginMediaTag($media_tag);
$storage->setOriginSequence($file_sequence);
return $storage->save();
}
//ViewPage의 이미지나영상데이터가 있으면 Dodownload 한다.
private function media_download(string $media_tag, string $url): array
{
$file_names = explode('/', $url);
if (!is_array($file_names) || !count($file_names)) {
throw new \Exception("URL이 파일명 형식이 아닙니다 : " . $this->getMySocket()->getHost() . $url);
}
$file_name = array_pop($file_names);
$temps = explode(".", $file_name);
$file_ext = array_pop($temps);
if (!$this->isFileType_FileTrait($file_ext, $media_tag)) {
throw new \Exception("파일명 형식이 {$media_tag}가 아닙니다");
}
$content = $this->getMySocket()->getContent($url);
log_message("notice", "{$file_name} 파일이 다운로드되었습니다!");
return array($file_name, $content);
}
private function media_process(array $media_urls): array
{
$file_sequence = 1;
$storages = []; //CreateBoard에서 사용을 위해 DetailPage마다 초기화
foreach ($media_urls as $media_tag => $urls) {
$total = count($urls);
foreach ($urls as $url) {
log_message("notice", __FUNCTION__ . " {$file_sequence}번째/총:{$total} MediaType->{$media_tag} 작업 시작");
try {
list($file_name, $content) = $this->media_download($media_tag, $url);
$storage = $this->media_save($file_sequence, $media_tag, $file_name, $content);
log_message("debug", __FUNCTION__ . " {$file_sequence}번째/총:{$total} 결과=>" . $storage->getOriginName());
$storages[] = $storage;
} catch (\Exception $e) {
log_message("warning", sprintf(
"\n---%s MediaType->%s {$file_sequence}번째/총:{$total} 오류---\n%s\n-----------------------------------------\n",
__FUNCTION__,
$media_tag,
$e->getMessage()
));
}
log_message("notice", __FUNCTION__ . " {$file_sequence}번째/총:{$total} MediaType->{$media_tag} 작업 완료");
$file_sequence++;
}
}
return $storages;
}
//Board 등록작업
private function create_board(int $cnt, array $listInfo, array $storages, array $formDatas = ['image_path' => "", 'content' => ""]): BoardEntity
{
//Board DB 등록작업등
//미디어관련정보 entity에 넣기
$formDatas[BoardModel::TITLE] = $listInfo["title"];
$formDatas['user_pid'] = $this->getMyStorage()->getUserEntity()->getPK();
$formDatas['user_id'] = $this->getMyStorage()->getUserEntity()->getID();
$formDatas['user_name'] = $listInfo["nickname"] != "" ? $listInfo["nickname"] : $this->getMyStorage()->getUserEntity()->getTitle();
$formDatas['level'] = $this->getBoardsEntity()->getListLevel();
$formDatas['hit'] = intval($listInfo['hit']);
$formDatas['reg_date'] = date("Y-m-d H:i:s", strtotime($listInfo['date']));
$formDatas['data_type'] = "html";
$formDatas['editor_type'] = "S";
foreach ($storages as $storage) {
if ($formDatas['image_path'] == "") {
$formDatas['image_path'] = $storage->getBasePath() . DIRECTORY_SEPARATOR . $storage->getPath() . DIRECTORY_SEPARATOR . $storage->getOriginName();
}
$formDatas['content'] .= $storage->getHTMLTag();
}
//망보드 게시판에 등록
if ($formDatas['content'] == "") {
throw new \Exception(sprintf(
"%s=>%s번째 %s 내용이 없어 => %s 등록 안함 : storage->%s",
__FUNCTION__,
$cnt,
$listInfo["title"],
$this->getBoardModel()->getTable(),
count($storages)
));
}
$board_entity = $this->getBoardModel()->create($formDatas);
log_message("notice", sprintf(
"%s=>%s번째 %s => %s 등록 완료 : storage->%s",
__FUNCTION__,
$cnt,
$listInfo["title"],
$this->getBoardModel()->getTable(),
count($storages)
));
return $board_entity;
}
//File DB 등록작업, 작은이미지 생성
private function create_storages(BoardEntity $board_entity, array $storages)
{
foreach ($storages as $storage) {
try {
$storage->create($this->getBoardsEntity(), $board_entity, $this->getBoardModel()->getTable());
} catch (\Exception $e) {
log_message("notice", sprintf(
"\n---%s -> %s 게시물의 %s번째:%s 파일 등록 오류---\n%s\n--------------------------------\n",
__FUNCTION__,
$board_entity->getTitle(),
$storage->getOriginSequence(),
$storage->getOriginName(),
$e->getMessage()
));
}
}
}
private function detail_copy_process(int $cnt, array $listInfo): array
{
list($selector, $listInfo) = $this->getDetailSelector($listInfo);
$formDatas = [];
$formDatas['image_path'] = "";
$formDatas['content'] = $selector->html();
//Board 등록작업등
$this->create_board($cnt, $listInfo, [], $formDatas);
log_message("notice", __FUNCTION__ . " 작업이 완료되었습니다.");
return $listInfo;
}
private function detail_download_process(int $cnt, array $listInfo): array
{
list($selector, $listInfo) = $this->getDetailSelector($listInfo);
$media_urls = $this->getUrlsByMediaType($selector, "img", "src");
$media_urls = $this->getUrlsByMediaType($selector, "video", "src", $media_urls);
if ($this->isDebug) {
throw new \Exception(sprintf(
"\n--------------%s Debug--------------\n%s%s\n---------------------------------------\n",
__FUNCTION__,
var_export($listInfo, true),
var_export($media_urls, true)
));
} else {
// Image 나 Video 소스들의 url을 가져와서 실제 다운받는 처리
$storages = $this->media_process($media_urls);
if (!count($storages)) {
throw new \Exception("등록할 자료가 없습니다.");
}
//Board 등록작업등
$board_entity = $this->create_board($cnt, $listInfo, $storages);
//File DB 등록작업, 작은이미지 생성
$this->create_storages($board_entity, $storages);
}
log_message("notice", __FUNCTION__ . " 작업이 완료되었습니다.");
return $listInfo;
}
protected function list_process(int $max_limit, array $listInfos): void
{
//Limit가 0이면 $listInfos 갯수만큼 다하고, LIMIT 갯수 혹은 item의 갯수중 작은수만큼 한다.
$max_limit = !$max_limit || count($listInfos) <= $max_limit ? count($listInfos) : $max_limit;
$total = count($listInfos);
$i = 1;
foreach ($listInfos as $listInfo) {
if ($i <= $max_limit) {
log_message("notice", __FUNCTION__ . " 게시물 {$i}번째/총:{$total} {$listInfo["nickname"]} 작업시작");
try {
if ($this->isCopy) {
$listInfo = $this->detail_copy_process($i, $listInfo);
} else {
//listInfo는 title,작성자,작성시간등등의 정보를 가지고 있어 detail_process 처리 안에서 바뀔 수 있으므로 다시 반환 받는다.
$listInfo = $this->detail_download_process($i, $listInfo);
}
} catch (\Exception $e) {
log_message("warning", sprintf(
"\n---%s {$i}번째/총:{$total} 오류---\n%s\n-----------------------------------------\n",
__FUNCTION__,
$e->getMessage()
));
}
log_message("notice", __FUNCTION__ . " 게시물 {$i}번째/총:{$total} {$listInfo["nickname"]} 작업완료.");
$i++;
}
}
log_message("notice", __FUNCTION__ . " 작업이 완료되었습니다.");
}
}

View File

@ -0,0 +1,123 @@
<?php
namespace App\Libraries\MyCrawler;
use Symfony\Component\DomCrawler\Crawler;
use DateTime;
use App\Entities\Mangboard\UserEntity;
class Sir extends MyCrawler
{
public function __construct(string $host, string $board_name, UserEntity $user_entity)
{
parent::__construct($host, $board_name, $user_entity);
}
protected function changeURLByCrawler(string $url): string
{
return str_replace("/sir.kr/", "", parent::changeURLByCrawler($url));
}
//작성내용
// <article class="sir_vbo ">
// <header class="vbo_head">
// <h2 class="head_h2">할아버지의 마술 정보</h2>
// <strong id="head_title">
// 할아버지의 마술 </strong>
// <ul id="head_info">
// <li id="info_name"><span class="sv_wrap">
// <a href="//sir.kr/bbs/profile.php?mb_id=hadirector" class="sv_member" title="감독님 자기소개" target="_blank" rel="nofollow" onclick="return false;"><span class="sir_mb_icon"></span> <span class="member">감독님</span></a>
// <span class="sv">
// <a href="//sir.kr/bbs/profile.php?mb_id=hadirector" onclick="win_profile(this.href); return false;"><i class="fa fa-user" aria-hidden="true"></i> 자기소개</a>
// <a href="//sir.kr/cm_humor?sca=&amp;sfl=mb_id,1&amp;stx=hadirector"><i class="fa fa-search" aria-hidden="true"></i> 아이디로 검색</a>
// <a href="//sir.kr/main/member/?mb_id=hadirector"><i class="fa fa-file-text-o" aria-hidden="true"></i> 회원게시물</a>
// </span>
// <noscript class="sv_nojs"><span class="sv">
// <a href="//sir.kr/bbs/profile.php?mb_id=hadirector" onclick="win_profile(this.href); return false;"><i class="fa fa-user" aria-hidden="true"></i> 자기소개</a>
// <a href="//sir.kr/cm_humor?sca=&amp;sfl=mb_id,1&amp;stx=hadirector"><i class="fa fa-search" aria-hidden="true"></i> 아이디로 검색</a>
// <a href="//sir.kr/main/member/?mb_id=hadirector"><i class="fa fa-file-text-o" aria-hidden="true"></i> 회원게시물</a>
// </span>
// </noscript></span>&nbsp;(210.♡.♡.13)</li>
// <li id="info_date"><time datetime='2024-09-13T00:24:04+09:00'>2024.09.13 00:24:04</time></li>
// <li id="info_hit"> 조회 <span>245</span>
// </li>
// <li id="info_cmt">
// <a href="#vcmt_anchor" class="comment">댓글 <span>3</span></a>
// </li>
// </ul>
// <div id="head_img"><span class='sir_mb_img' title='회원정보에 사진을 올려주세요.'></span></div>
// </header>
// <script>
// $(".vcmt-btn").click(function() {
// $('html, body').animate({
// scrollTop: $("#vcmt_anchor").offset().top - 100
// }, 300);
// });
// </script>
// <ul class="sir_vbo_cmd link">
// <li><a href="javascript:void(0)" class="sir_b01 sir_prev"><span class="sound_only">이전 게시글</span><i class="fa fa-angle-left"></i></a></li>
// <li><a href="//sir.kr/cm_humor/191445" class="sir_b01 sir_next"><span class="sound_only">다음 게시글</span><i class="fa fa-angle-right"></i></a></li>
// </ul>
// <ul class="sir_vbo_com" >
// <li><a href="//sir.kr/cm_humor" class="sir_b01">목록</a></li>
// </ul>
// <section id="vbo_con">
// <h2 class="con_h2">본문</h2>
// <div class="con_inner">
// <div id="con_pix">
// <video autoplay="autoplay" loop="loop" preload="auto" playsinline webkit-playsinline muted>
// <source src="//sir.kr/data/file/cm_humor/3535243533_CiH6Iv9O_ee170eeec15e748d9bfcc895836c71d9829c07fb.mp4" type="video/mp4" />
// </video>
// </div>
//
protected function getDetailSelector(array $listInfo): array
{
$response = $this->getMySocket()->getContent($listInfo['detail_url']);
//작성시간
$selector = $this->getSelector($response, getenv("sir.view.date.tag"));
//Date Format이 맞지않아 변경해주기위함 : 2024.09.13 00:24:04 -> 2024-09-13 00:24:04
$listInfo['date'] = trim($selector->text());
$listInfo['date'] = DateTime::createFromFormat('Y.m.d H:i:s', $listInfo['date']);
$listInfo['date'] = $listInfo['date']->format('Y-m-d H:i:s');
return array($this->getSelector($response, tag: getenv("sir.view.content.tag")), $listInfo);
}
//리스트 내용
// <td class="listvisited mobile-td subject-view">
// <a href="board-read.asp?fullboardname=yamoonfreeboard&mtablename=humor&num=89372&ref=85575&page=1" class="ya-tooltip mobile-bold mobile-height" title="<p><br><br><video autoplay=&quot;autoplay&quot; loop=&quot;loop&quot; muted=&quot;&quot; controls=&quot;controls&quot; width=&quot;560&quot;&quot; height=&quot; &quot;> <source src=&quot; https://files.bepick.net/bbs/2024/09/c2a20ab5771cbb934940551859fce1c8_769966583.mp4 &quot;> </video><br><br><br></p">
// 졸고 있는 여군</a>
// <i class="fa fa-commenting-o" aria-hidden="true"></i> <span class="color-red small">6</span>
// <span class="visible-xs visible-sm small"><i class="fa fa-user-o" aria-hidden="true"></i> yeeyuu | <i class="fa fa-thumbs-o-up" aria-hidden="true"></i> 6 | <i class="fa fa-eye" aria-hidden="true"></i> 369 | No 89372 | 2024-09-13</span>
// </td>
public function execute(): void
{
$listInfos = [];
if ($this->isDebug) {
$listInfo = [];
$listInfo['title'] = 'test_title';
$listInfo['nickname'] = 'test_name';
$listInfo['hit'] = 1;
$listInfo['date'] = date("Y-m-d H:i:s");
$listInfo['detail_url'] = getenv("sir.view.test.url.{$this->getMyStorage()->getBoardName()}");
$listInfos[] = $listInfo;
} else {
$response = $this->getMySocket()->getContent(getenv("sir.list.url.{$this->getMyStorage()->getBoardName()}"));
$this->getSelector($response, getenv("sir.list.tag.{$this->getMyStorage()->getBoardName()}"))->each(
function (Crawler $node) use (&$listInfos): void {
$nickname = $node->filter(getenv("sir.list.item.nickname.tag"))->text();
$hit = $node->filter(getenv("sir.list.item.hit.tag"))->text();
// 작성시간은 detail에서 정의
// $date = $node->filter(getenv("sir.list.item.date.tag"))->text();
//title및 detail url
$link_node = $node->filter(getenv("sir.list.item.link.tag"));
// href url의 맨 앞이 /sir.kr가 빼기
$detail_url = $this->changeURLByCrawler($link_node->attr("href"));
$title = $link_node->text();
$listInfos[] = ['title' => $title, 'nickname' => $nickname, 'detail_url' => $detail_url, 'date' => "", 'hit' => $hit];
}
);
}
if (!count($listInfos)) {
throw new \Exception("Target URL이 없습니다.");
}
$this->list_process(intval(getenv("sir.list.max_limit.{$this->getMyStorage()->getBoardName()}")), $listInfos);
log_message("notice", __FUNCTION__ . " 작업이 완료되었습니다.");
}
}

View File

@ -0,0 +1,85 @@
<?php
namespace App\Libraries\MyCrawler;
use App\Entities\Mangboard\UserEntity;
use Symfony\Component\DomCrawler\Crawler;
class Yamap extends MyCrawler
{
public function __construct(string $host, string $board_name, UserEntity $user_entity)
{
parent::__construct($host, $board_name, $user_entity);
}
protected function getDetailSelector(array $listInfo): array
{
$response = $this->getMySocket()->getContent($listInfo['detail_url']);
return array($this->getSelector($response, getenv("yamap.view.content.tag")), $listInfo);
}
//리스트내용
// <div class="panel panel-default">
// <div class="text-center panel-heading-local-title text-bold">요즘 패션</div>
// <div style="margin:5px 10px;">
// <span class="pull-left dropdown">
// 괴강고귀
// </span>
// <span class="pull-right">
// | 추천 (14) | 조회 (432)
// </span>
// <div class="clearfix"></div>
// <hr class="hr-xs-xs">
// <span>
// <a href="javascript:void(0);" id="incfont"><i class="fa fa-plus fa-fw" aria-hidden="true"></i></a><a href="javascript:void(0);" id="decfont"><i class="fa fa-minus fa-fw margin-left-5" aria-hidden="true"></i></a>
// </span>
// <span class="pull-right">2024-09-14 01:53:45
// </span>
// <div class="clearfix"></div>
// <hr class="margin-top-5 margin-bottom-20">
// <div class="fr-view margin-bottom-30" id="read-content" style="word-break:break-all;">
// <p><img title="" class="cloudzoom" data-cloudzoom="zoomImage:'/newboard/yamoonfreeboard/uploads/humor/mceu_86177012011726246415487.jpg'" class="fr-fic fr-dii" src="/newboard/yamoonfreeboard/uploads/humor/mceu_86177012011726246415487.jpg" alt=""></p>
// <p>&nbsp;</p>
// </div>
// </div>
// <div class="margin-10">
// <a href="javascript:void(0)" onclick="javascript:window.open('https://twitter.com/intent/tweet?text='+encodeURIComponent(document.title)+'%20-%20'+encodeURIComponent(document.URL), 'twittersharedialog', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600');return false;" target="_blank"> <i class="fa fa-twitter-square fa-lg ya-tooltip" title="트위터 공유하기"></i></a>
// <a href="javascript:void(0)" onclick="javascript:window.open('https://www.facebook.com/sharer/sharer.php?u='+encodeURIComponent(document.URL)+'&t='+encodeURIComponent(document.title), 'facebooksharedialog', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600');return false;" target="_blank"> <i class="fa fa-facebook-square fa-lg ya-tooltip" title="페이스북 공유하기"></i></a>
// </div>
// <div id="freesubframe"></div>
// </div>
final public function execute(): void
{
$listInfos = [];
if ($this->isDebug) {
$listInfo = [];
$listInfo['title'] = 'test_title';
$listInfo['nickname'] = 'test_name';
$listInfo['hit'] = 1;
$listInfo['date'] = date("Y-m-d H:i:s");
$listInfo['detail_url'] = getenv("yamap.view.test.url.{$this->getMyStorage()->getBoardName()}");
$listInfos[] = $listInfo;
} else {
$response = $this->getMySocket()->getContent(getenv("yamap.list.url.{$this->getMyStorage()->getBoardName()}"));
$this->getSelector($response, getenv("yamap.list.tag.{$this->getMyStorage()->getBoardName()}"))->each(
function (Crawler $node) use (&$listInfos): void {
$nickname = $node->filter(getenv("yamap.list.item.nickname.tag"))->text();
$hit = $node->filter(getenv("yamap.list.item.hit.tag"))->text();
$date = $node->filter(getenv("yamap.list.item.date.tag"))->text();
//title및 detail url
$link_node = $node->filter(getenv("yamap.list.item.link.tag"));
$detail_url = $link_node->attr("href");
$title = $link_node->children()->last()->text();
//title에서 예외사항비교
if (strpos($title, getenv("yamap.list.tag.except.{$this->getMyStorage()->getBoardName()}")) === false) {
$listInfos[] = ['title' => $title, 'nickname' => $nickname, 'detail_url' => $detail_url, 'date' => $date, 'hit' => $hit];
}
}
);
}
if (!count($listInfos)) {
throw new \Exception("Target URL이 없습니다.");
}
$this->list_process(intval(getenv("yamap.list.max_limit.{$this->getMyStorage()->getBoardName()}")), $listInfos);
log_message("notice", __FUNCTION__ . " 작업이 완료되었습니다.");
}
}

View File

@ -0,0 +1,89 @@
<?php
namespace App\Libraries\MyCrawler;
use Symfony\Component\DomCrawler\Crawler;
use App\Entities\Mangboard\UserEntity;
class Yamoon extends MyCrawler
{
public function __construct(string $host, string $board_name, UserEntity $user_entity)
{
parent::__construct($host, $board_name, $user_entity);
}
//작성내용
// <div class="panel panel-default">
// <div class="text-center panel-heading-local-title text-bold">요즘 화제라는 명품 목걸이</div>
// <div style="margin:5px 10px;">
// <span class="pull-left dropdown">CAT7478</span>
// <span class="pull-right">| 추천 (8) | 조회 (268)</span>
// <div class="clearfix"></div>
// <hr class="hr-xs-xs">
// <span>
// <a href="javascript:void(0);" id="incfont"><i class="fa fa-plus fa-fw" aria-hidden="true"></i></a><a href="javascript:void(0);" id="decfont"><i class="fa fa-minus fa-fw margin-left-5" aria-hidden="true"></i></a>
// </span>
// <span class="pull-right">2024-09-16 09:52:39</span>
// <div class="clearfix"></div>
// <hr class="margin-top-5 margin-bottom-20">
// <div class="fr-view margin-bottom-30" id="read-content" style="word-break:break-all;">
// <p><img title="" class="cloudzoom" data-cloudzoom="zoomImage:'/newboard/yamoonfreeboard/uploads/humor/mceu_18297097311726447898684.webp'" class="fr-fic fr-dii" src="/newboard/yamoonfreeboard/uploads/humor/mceu_18297097311726447898684.webp" alt=""></p>
// <p><img title="" class="cloudzoom" data-cloudzoom="zoomImage:'/newboard/yamoonfreeboard/uploads/humor/mceu_41105156321726447902977.png'" class="fr-fic fr-dii" src="/newboard/yamoonfreeboard/uploads/humor/mceu_41105156321726447902977.png" alt=""></p>
// <p>&nbsp;</p>
// <p>&nbsp;</p>
// <p>전화기선 짤라서 목걸이 만들어도 위화감이 전혀 없을것같은</p>
// <p>&nbsp;</p>
// <p>디자인이군요</p>
// <p>&nbsp;</p>
// </div>
// </div>
// <div class="margin-10">
// <a href="javascript:void(0)" onclick="javascript:window.open('https://twitter.com/intent/tweet?text='+encodeURIComponent(document.title)+'%20-%20'+encodeURIComponent(document.URL), 'twittersharedialog', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600');return false;" target="_blank"> <i class="fa fa-twitter-square fa-lg ya-tooltip" title="트위터 공유하기"></i></a>
// <a href="javascript:void(0)" onclick="javascript:window.open('https://www.facebook.com/sharer/sharer.php?u='+encodeURIComponent(document.URL)+'&t='+encodeURIComponent(document.title), 'facebooksharedialog', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600');return false;" target="_blank"> <i class="fa fa-facebook-square fa-lg ya-tooltip" title="페이스북 공유하기"></i></a>
// </div>
// <div id="freesubframe"></div>
// </div>
protected function getDetailSelector(array $listInfo): array
{
$response = $this->getMySocket()->getContent("/newboard/yamoonboard/" . $listInfo['detail_url']);
return array($this->getSelector($response, getenv("yamoon.view.content.tag")), $listInfo);
}
//리스트 내용
// <td class="listvisited mobile-td subject-view">
// <a href="board-read.asp?fullboardname=yamoonfreeboard&mtablename=humor&num=89372&ref=85575&page=1" class="ya-tooltip mobile-bold mobile-height" title="<p><br><br><video autoplay=&quot;autoplay&quot; loop=&quot;loop&quot; muted=&quot;&quot; controls=&quot;controls&quot; width=&quot;560&quot;&quot; height=&quot; &quot;> <source src=&quot; https://files.bepick.net/bbs/2024/09/c2a20ab5771cbb934940551859fce1c8_769966583.mp4 &quot;> </video><br><br><br></p">
// 졸고 있는 여군</a>
// <i class="fa fa-commenting-o" aria-hidden="true"></i> <span class="color-red small">6</span>
// <span class="visible-xs visible-sm small"><i class="fa fa-user-o" aria-hidden="true"></i> yeeyuu | <i class="fa fa-thumbs-o-up" aria-hidden="true"></i> 6 | <i class="fa fa-eye" aria-hidden="true"></i> 369 | No 89372 | 2024-09-13</span>
// </td>
public function execute(): void
{
$listInfos = [];
if ($this->isDebug) {
$listInfo = [];
$listInfo['title'] = 'test_title';
$listInfo['nickname'] = 'test_name';
$listInfo['hit'] = 1;
$listInfo['date'] = date("Y-m-d H:i:s");
$listInfo['detail_url'] = getenv("yamoon.view.test.url.{$this->getMyStorage()->getBoardName()}");
$listInfos[] = $listInfo;
} else {
$response = $this->getMySocket()->getContent(getenv("yamoon.list.url.{$this->getMyStorage()->getBoardName()}"));
$this->getSelector($response, getenv("yamoon.list.tag.{$this->getMyStorage()->getBoardName()}"))->each(
function (Crawler $node) use (&$listInfos): void {
//title및 detail url
$link_node = $node->filter(getenv("yamoon.list.item.link.tag"));
$detail_url = $link_node->attr("href");
$title = $link_node->text();
//기타정보기 |로 구분되어 있어 작업
$info_node = $node->filter(getenv("yamoon.list.item.info.tag"));
$infos = explode("|", $info_node->text());
$listInfos[] = ['title' => $title, 'detail_url' => $detail_url, 'nickname' => trim($infos[0]), 'hit' => trim($infos[2]), 'date' => trim($infos[4])];
}
);
}
if (!count($listInfos)) {
throw new \Exception("Target URL이 없습니다.");
}
$this->list_process(intval(getenv("yamoon.list.max_limit.{$this->getMyStorage()->getBoardName()}")), $listInfos);
log_message("notice", __FUNCTION__ . " 작업이 완료되었습니다.");
}
}

View File

@ -0,0 +1,155 @@
<?php
namespace App\Libraries\MyMangboard;
use App\Entities\Mangboard\BoardEntity;
use App\Entities\Mangboard\BoardsEntity;
use App\Entities\Mangboard\FileEntity;
use App\Entities\Mangboard\UserEntity;
use App\Libraries\MyStorage\FileStorage;
use App\Models\Mangboard\FileModel;
use App\Traits\ImageTrait;
class Storage extends FileStorage
{
use ImageTrait;
private $_board_name = "";
private $_user_entity = null;
private $_fileModel = null;
public function __construct(string $board_name, UserEntity $user_entity)
{
parent::__construct($board_name);
$this->_board_name = $board_name;
$this->_user_entity = $user_entity;
}
final public function getBoardName(): string
{
if ($this->_board_name === "") {
throw new \Exception("BoardName이 정의되지 않았습니다.");
}
return $this->_board_name;
}
final public function getUserEntity(): UserEntity
{
if ($this->_user_entity === null) {
throw new \Exception("UserEntity가 정의되지 않았습니다.");
}
return $this->_user_entity;
}
final protected function getFileModel(): FileModel
{
if ($this->_fileModel === null) {
$this->_fileModel = new FileModel();
}
return $this->_fileModel;
}
final public function getBasePath(): string
{
return getenv("mangboard.uploads.path");
}
final public function getUploadPath(): string
{
return parent::getUploadPath() . DIRECTORY_SEPARATOR . $this->getBasePath();
}
final public function getUploadURL(): string
{
return sprintf("/wp-content/%s/%s/%s", parent::getUploadURL(), $this->getBasePath(), $this->getBasePath());
}
final public function getHTMLTag(string $content = ""): string
{
//Board 게시판 image_path , content용 데이터 배열에 추가 후 modifyBoard에서 처리
switch ($this->getOriginMediaTag()) {
case "img":
$content = sprintf(
"<img src=\"%s/%s/%s\" alt=\"%s\">",
$this->getUploadURL(),
$this->getPath(),
$this->getOriginName(),
$this->getOriginName()
);
break;
case "video":
$content = sprintf(
"<video alt=\"%s\" controls autoplay>
<source src=\"%s/%s/%s\" type=\"%s\">
Your browser does not support the video tag.
</video>",
$this->getOriginName(),
$this->getUploadURL(),
$this->getPath(),
$this->getOriginName(),
$this->getMimeType(),
);
break;
}
log_message("debug", sprintf(
"\n--------%s--------\n%s\n--------------------\n",
__FUNCTION__,
$content
));
return $content;
}
private function create_file(BoardsEntity $boards_entity, BoardEntity $board_entity, string $board_table): FileEntity
{
$formDatas['board_pid'] = $board_entity->getPk();
$formDatas['user_pid'] = $this->_user_entity->getPK();
$formDatas['user_name'] = $this->_user_entity->getTitle();
$formDatas['board_name'] = $boards_entity->getTitle();
$formDatas['table_name'] = $board_table;
$formDatas['file_path'] = $this->getBasePath() . DIRECTORY_SEPARATOR . $this->getPath() . DIRECTORY_SEPARATOR . $this->getOriginName();
$formDatas[FileModel::TITLE] = $this->getOriginName();
$formDatas['file_type'] = $this->getMimeType();
$formDatas['file_caption'] = $this->getOriginName();
$formDatas['file_alt'] = $this->getOriginName();
$formDatas['file_description'] = "Filedata";
$formDatas['file_size'] = $this->getFileSize();
$formDatas['file_sequence'] = $this->getOriginSequence();
$formDatas['reg_date'] = date("Y-m-d H:i:s");
$entity = $this->getFileModel()->create($formDatas);
log_message("notice", sprintf(
"%s -> %s 게시물의 %s번째:%s 파일 등록 완료",
__FUNCTION__,
$board_entity->getTitle(),
$this->getOriginSequence(),
$entity->getTitle()
));
return $entity;
}
private function create_small_image(BoardEntity $board_entity, $target_name = "small", int $width = 480, int $height = 319): void
{
$fileInfo = pathinfo($this->getFullPath() . DIRECTORY_SEPARATOR . $this->getOriginName(), PATHINFO_ALL);
$target_file_name = sprintf("%s_%s.%s", $fileInfo['filename'], $target_name, $fileInfo['extension']);
if (!$this->isFileType_FileTrait($fileInfo['extension'])) {
throw new \Exception("{$this->getOriginName()} Image 형식파일이 아닙니다.");
}
// 이미지 파일 로드
$this->load_ImageTrait($this->getFullPath() . DIRECTORY_SEPARATOR . $this->getOriginName());
// 200x200으로 이미지 크기 조정
$this->resize_ImageTrait($width, $height);
// 파일 저장
$this->save_ImageTrait($this->getFullPath() . DIRECTORY_SEPARATOR . $target_file_name);
// 메모리 해제
$this->destroy_ImageTrait();
log_message("notice", sprintf(
"%s -> %s 게시물의 %s번째:%s->%s 작은이미지(W:%s,H:%s) 생성 완료",
__FUNCTION__,
$board_entity->getTitle(),
$this->getOriginSequence(),
$this->getOriginName(),
$target_file_name,
$width,
$height
));
}
final public function create(BoardsEntity $boards_entity, BoardEntity $board_entity, string $board_table): void
{
//File DB에 넣기
$this->create_file($boards_entity, $board_entity, $board_table);
//작은이미지 만들기
$this->create_small_image($board_entity);
}
}

Some files were not shown because too many files have changed in this diff Show More