Import alt-mysql plugin
This commit is contained in:
@@ -0,0 +1,333 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
final class AppContext
|
||||
{
|
||||
public DirectAdminUser $daUser;
|
||||
public Settings $settings;
|
||||
public MySQLService $mysql;
|
||||
|
||||
private CsrfGuard $csrf;
|
||||
private Lang $lang;
|
||||
|
||||
public function __construct(DirectAdminUser $daUser, Settings $settings, MySQLService $mysql, CsrfGuard $csrf, Lang $lang)
|
||||
{
|
||||
$this->daUser = $daUser;
|
||||
$this->settings = $settings;
|
||||
$this->mysql = $mysql;
|
||||
$this->csrf = $csrf;
|
||||
$this->lang = $lang;
|
||||
}
|
||||
|
||||
public function action(): string
|
||||
{
|
||||
return (string)PLUGIN_ACTION;
|
||||
}
|
||||
|
||||
public function baseUrl(): string
|
||||
{
|
||||
return '/CMD_PLUGINS/alt-mysql';
|
||||
}
|
||||
|
||||
public function url(string $page, array $query = []): string
|
||||
{
|
||||
$path = $this->baseUrl() . '/' . ltrim($page, '/');
|
||||
if (!empty($query)) {
|
||||
$path .= '?' . http_build_query($query);
|
||||
}
|
||||
return $path;
|
||||
}
|
||||
|
||||
public function isPost(): bool
|
||||
{
|
||||
return Http::isPost();
|
||||
}
|
||||
|
||||
public function postString(string $key, string $default = ''): string
|
||||
{
|
||||
return Http::getString($_POST, $key, $default);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int,string>
|
||||
*/
|
||||
public function postArray(string $key): array
|
||||
{
|
||||
$raw = Http::getArray($_POST, $key);
|
||||
$out = [];
|
||||
foreach ($raw as $item) {
|
||||
if (is_array($item)) {
|
||||
continue;
|
||||
}
|
||||
$out[] = trim((string)$item);
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
public function queryString(string $key, string $default = ''): string
|
||||
{
|
||||
return Http::getString($_GET, $key, $default);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,string|int|float> $vars
|
||||
*/
|
||||
public function t(string $key, array $vars = []): string
|
||||
{
|
||||
return $this->lang->t($key, $vars);
|
||||
}
|
||||
|
||||
public function formatException(Throwable $e): string
|
||||
{
|
||||
if ($e instanceof LocalizedException) {
|
||||
return $this->t($e->key(), $e->vars());
|
||||
}
|
||||
return $this->t($e->getMessage());
|
||||
}
|
||||
|
||||
public function csrfField(string $intent): string
|
||||
{
|
||||
$issued = $this->csrf->issue($intent);
|
||||
$ts = (string)$issued['ts'];
|
||||
$sid = htmlspecialchars((string)($issued['sid'] ?? ''), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
|
||||
$token = htmlspecialchars($issued['token'], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
|
||||
|
||||
return '<input type="hidden" name="csrf_ts" value="' . $ts . '">' .
|
||||
'<input type="hidden" name="csrf_sid" value="' . $sid . '">' .
|
||||
'<input type="hidden" name="csrf_token" value="' . $token . '">';
|
||||
}
|
||||
|
||||
public function requireCsrf(string $intent): void
|
||||
{
|
||||
$ts = $this->postString('csrf_ts');
|
||||
$sid = $this->postString('csrf_sid');
|
||||
$token = $this->postString('csrf_token');
|
||||
if (!$this->csrf->validate($intent, $ts, $token, 3600, $sid)) {
|
||||
$debug = sprintf(
|
||||
'[%s] CSRF_FAIL intent=%s action=%s method=%s ts=%s sid=%s token_prefix=%s post_keys=%s',
|
||||
date('c'),
|
||||
$intent,
|
||||
$this->action(),
|
||||
Http::method(),
|
||||
$ts,
|
||||
$sid,
|
||||
substr($token, 0, 12),
|
||||
implode(',', array_keys($_POST))
|
||||
);
|
||||
@error_log($debug . "\n", 3, PLUGIN_ROOT . '/error.log');
|
||||
throw new RuntimeException('Nieprawidłowy lub wygasły token CSRF.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string[] $okMessages
|
||||
* @param string[] $errorMessages
|
||||
*/
|
||||
public function renderPage(string $title, string $body, array $okMessages = [], array $errorMessages = [], string $logs = ''): void
|
||||
{
|
||||
$alerts = '';
|
||||
foreach ($okMessages as $msg) {
|
||||
$alerts .= '<div class="alert alert-ok">' . self::e($msg) . '</div>';
|
||||
}
|
||||
foreach ($errorMessages as $msg) {
|
||||
$alerts .= '<div class="alert alert-err">' . self::e($msg) . '</div>';
|
||||
}
|
||||
|
||||
$alerts = $this->lang->translateHtml($alerts);
|
||||
$body = $this->lang->translateHtml($body);
|
||||
$logs = $this->lang->translateHtml($logs);
|
||||
|
||||
$safeTitle = self::e($this->t($title));
|
||||
$topActions = $this->renderTopActions();
|
||||
$langCode = $this->daUser->language();
|
||||
|
||||
header('Content-Type: text/html; charset=UTF-8');
|
||||
echo '<!doctype html><html lang="' . self::e($langCode) . '"><head><meta charset="utf-8">';
|
||||
echo '<meta name="viewport" content="width=device-width, initial-scale=1">';
|
||||
echo '<title>' . $safeTitle . '</title>';
|
||||
echo '<style>' . $this->styles() . '</style>';
|
||||
echo '</head><body>';
|
||||
echo '<div class="wrap">';
|
||||
echo '<div class="breadcrumbs">' . self::e($this->t('Pulpit')) . ' <span>></span> ' . self::e($this->t('Bazy danych')) . '</div>';
|
||||
$headerClass = in_array($this->action(), ['index', 'upload_backup'], true) ? ' class="header-center"' : '';
|
||||
echo '<header' . $headerClass . '><h1>' . $safeTitle . '</h1></header>';
|
||||
echo '<div class="top-actions">' . $topActions . '</div>';
|
||||
echo '<section class="main-section">' . $alerts . $body . '</section>';
|
||||
echo '<section class="logs-section">' . $logs . '</section>';
|
||||
echo '</div>';
|
||||
$jsConfig = 'window.DA_MYSQL_BASE_URL=' . json_encode($this->baseUrl(), JSON_UNESCAPED_SLASHES) . ';';
|
||||
$jsConfig .= 'window.DA_MYSQL_INDEX_URL=' . json_encode($this->url('index.html'), JSON_UNESCAPED_SLASHES) . ';';
|
||||
$jsConfig .= 'window.DA_MYSQL_USER_URL=' . json_encode($this->url('user/index.html'), JSON_UNESCAPED_SLASHES) . ';';
|
||||
$jsConfig .= 'window.DA_MYSQL_UPLOAD_RAW_URL=' . json_encode($this->url('upload_backup.raw'), JSON_UNESCAPED_SLASHES) . ';';
|
||||
$jsConfig .= 'window.DA_MYSQL_I18N=' . json_encode($this->jsI18n(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ';';
|
||||
echo '<script>' . $jsConfig . '</script>';
|
||||
echo '<script>' . $this->scripts() . '</script>';
|
||||
echo '</body></html>';
|
||||
}
|
||||
|
||||
public function renderFatal(string $message, int $code = 400): void
|
||||
{
|
||||
http_response_code($code);
|
||||
$body = '<p>' . self::e($this->t($message)) . '</p>';
|
||||
$body .= '<p><a href="' . self::e($this->url('index.html')) . '">' . self::e($this->t('Powrót')) . '</a></p>';
|
||||
$this->renderPage('Błąd', $body, [], []);
|
||||
}
|
||||
|
||||
public static function e(string $value): string
|
||||
{
|
||||
return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
|
||||
}
|
||||
|
||||
private function renderTopActions(): string
|
||||
{
|
||||
$links = [];
|
||||
|
||||
$links[] = '<a class="btn amber' . ($this->action() === 'index' ? ' active' : '') . '" href="' . self::e($this->url('index.html')) . '">' . self::e($this->t('BAZY DANYCH')) . '</a>';
|
||||
$links[] = '<a class="btn amber' . ($this->action() === 'change_password' ? ' active' : '') . '" href="' . self::e($this->url('change_password.html')) . '">' . self::e($this->t('UŻYTKOWNICY BAZ DANYCH')) . '</a>';
|
||||
if ($this->settings->enableUploadBackup()) {
|
||||
$links[] = '<a class="btn amber' . ($this->action() === 'upload_backup' ? ' active' : '') . '" href="' . self::e($this->url('upload_backup.html')) . '">' . self::e($this->t('BACKUPY BAZ DANYCH')) . '</a>';
|
||||
}
|
||||
if ($this->settings->enableAdminer()) {
|
||||
$links[] = '<form method="post" target="_top" action="' . self::e($this->url('open_phpmyadmin.raw')) . '" style="display:inline-flex;align-items:center;">' .
|
||||
$this->csrfField('open_phpmyadmin_submit') .
|
||||
'<button class="btn amber' . ($this->action() === 'open_phpmyadmin' ? ' active' : '') . '" type="submit">' . self::e($this->t('PHPMYADMIN')) . '</button>' .
|
||||
'</form>';
|
||||
}
|
||||
|
||||
return implode('', $links);
|
||||
}
|
||||
|
||||
private function styles(): string
|
||||
{
|
||||
$skin = $this->daUser->skin();
|
||||
$path = PLUGIN_ROOT . '/user/' . $skin . '.css';
|
||||
if (!is_file($path)) {
|
||||
$path = PLUGIN_ROOT . '/user/enhanced.css';
|
||||
}
|
||||
$css = is_file($path) ? file_get_contents($path) : '';
|
||||
if ($css === false) {
|
||||
return '';
|
||||
}
|
||||
return $css;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string,string>
|
||||
*/
|
||||
private function jsI18n(): array
|
||||
{
|
||||
$keys = [
|
||||
'Pobieranie...',
|
||||
'Nieudana odpowiedź serwera ({code})',
|
||||
'Nieudana odpowiedź serwera (HTML zamiast pliku, URL: {url})',
|
||||
'Serwer zwrócił pusty plik.',
|
||||
'Nie można pobrać pliku backupu.',
|
||||
'Pobierz plik backupu',
|
||||
'Brak plików .sql/.gz',
|
||||
'Brak katalogów',
|
||||
'Nie udało się wczytać katalogów.',
|
||||
'Podaj nazwę katalogu.',
|
||||
'Nie udało się utworzyć katalogu.',
|
||||
'Wysyłanie pliku...',
|
||||
'Nie udało się wysłać pliku backupu.',
|
||||
'Wybierz plik .sql/.gz/.sql.gz lub wskaż ścieżkę pliku na serwerze.',
|
||||
'Wskaż ścieżkę do pliku SQL lub SQL.GZ.',
|
||||
'Wybierz plik .sql/.gz/.sql.gz do przywrócenia.',
|
||||
];
|
||||
|
||||
$out = [];
|
||||
foreach ($keys as $key) {
|
||||
$out[$key] = $this->t($key);
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
private function scripts(): string
|
||||
{
|
||||
$js = <<<'JS'
|
||||
(function () {
|
||||
var __i18n = (typeof window.DA_MYSQL_I18N === 'object' && window.DA_MYSQL_I18N) ? window.DA_MYSQL_I18N : {};
|
||||
function tr(key) {
|
||||
return (__i18n && Object.prototype.hasOwnProperty.call(__i18n, key)) ? __i18n[key] : key;
|
||||
}
|
||||
function trf(key, vars) {
|
||||
var out = tr(key);
|
||||
if (!vars) {
|
||||
return out;
|
||||
}
|
||||
for (var k in vars) {
|
||||
if (!Object.prototype.hasOwnProperty.call(vars, k)) {
|
||||
continue;
|
||||
}
|
||||
out = out.replace(new RegExp('\\{' + k + '\\}', 'g'), String(vars[k]));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function generatePassword(len) {
|
||||
var size = len || 20;
|
||||
var alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%^&*_-+=';
|
||||
var bytes = new Uint32Array(size);
|
||||
if (window.crypto && window.crypto.getRandomValues) {
|
||||
window.crypto.getRandomValues(bytes);
|
||||
} else {
|
||||
for (var i = 0; i < size; i += 1) {
|
||||
bytes[i] = Math.floor(Math.random() * 0xffffffff);
|
||||
}
|
||||
}
|
||||
var out = '';
|
||||
for (var j = 0; j < size; j += 1) {
|
||||
out += alphabet.charAt(bytes[j] % alphabet.length);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function bindPasswordHelpers() {
|
||||
document.querySelectorAll('[data-generate-target]').forEach(function (btn) {
|
||||
btn.addEventListener('click', function () {
|
||||
var input = document.getElementById(btn.getAttribute('data-generate-target'));
|
||||
if (!input) { return; }
|
||||
input.value = generatePassword(20);
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
});
|
||||
});
|
||||
|
||||
document.querySelectorAll('[data-toggle-target]').forEach(function (btn) {
|
||||
btn.addEventListener('click', function () {
|
||||
var input = document.getElementById(btn.getAttribute('data-toggle-target'));
|
||||
if (!input) { return; }
|
||||
input.type = input.type === 'password' ? 'text' : 'password';
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function bindDownloadForms() {
|
||||
document.querySelectorAll('form[data-backup-download]').forEach(function (form) {
|
||||
form.addEventListener('submit', function (ev) {
|
||||
var btn = form.querySelector('button[type="submit"],input[type="submit"]');
|
||||
if (btn) {
|
||||
btn.disabled = true;
|
||||
btn.dataset.originalText = btn.textContent;
|
||||
btn.textContent = tr('Pobieranie...');
|
||||
}
|
||||
window.setTimeout(function () {
|
||||
if (btn) {
|
||||
btn.disabled = false;
|
||||
if (btn.dataset.originalText) {
|
||||
btn.textContent = btn.dataset.originalText;
|
||||
}
|
||||
}
|
||||
}, 4000);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
window.daMysqlI18n = { tr: tr, trf: trf };
|
||||
bindPasswordHelpers();
|
||||
bindDownloadForms();
|
||||
}());
|
||||
JS;
|
||||
|
||||
return FilePicker::scripts() . "\n" . $js;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
final class CsrfGuard
|
||||
{
|
||||
private string $secret;
|
||||
private string $username;
|
||||
private string $sessionId;
|
||||
|
||||
public function __construct(string $secret, string $username, string $sessionId)
|
||||
{
|
||||
$this->secret = $secret;
|
||||
$this->username = $username;
|
||||
$this->sessionId = $sessionId !== '' ? $sessionId : 'no_session';
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{ts:int,token:string}
|
||||
*/
|
||||
public function issue(string $intent): array
|
||||
{
|
||||
$ts = time();
|
||||
$sid = $this->sessionId;
|
||||
return [
|
||||
'ts' => $ts,
|
||||
'sid' => $sid,
|
||||
'token' => $this->buildToken($intent, $ts, $sid),
|
||||
];
|
||||
}
|
||||
|
||||
public function validate(string $intent, string $timestamp, string $token, int $ttl = 3600, string $sessionHint = ''): bool
|
||||
{
|
||||
if (!preg_match('/^[0-9]{1,20}$/', $timestamp)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$ts = (int)$timestamp;
|
||||
$now = time();
|
||||
if ($ts <= 0 || $ts > ($now + 30) || ($now - $ts) > $ttl) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$token = trim($token);
|
||||
$sids = [];
|
||||
|
||||
$hint = trim($sessionHint);
|
||||
if ($hint !== '') {
|
||||
$sids[] = $hint;
|
||||
}
|
||||
$sids[] = $this->sessionId;
|
||||
$sids[] = 'no_session';
|
||||
$sids[] = '';
|
||||
$sids = array_values(array_unique($sids));
|
||||
|
||||
foreach ($sids as $sid) {
|
||||
$expected = $this->buildToken($intent, $ts, $sid);
|
||||
if (hash_equals($expected, $token)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private function buildToken(string $intent, int $timestamp, string $sid): string
|
||||
{
|
||||
$payload = implode('|', [$this->username, $sid !== '' ? $sid : 'no_session', $intent, (string)$timestamp]);
|
||||
return hash_hmac('sha256', $payload, $this->secret);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
final class DirectAdminUser
|
||||
{
|
||||
private string $username;
|
||||
private string $prefix;
|
||||
|
||||
/** @var array<string,string> */
|
||||
private array $userConf;
|
||||
|
||||
/** @var array<string,string> */
|
||||
private array $packageConf;
|
||||
|
||||
private Settings $settings;
|
||||
|
||||
private function __construct(string $username, array $userConf, array $packageConf, Settings $settings)
|
||||
{
|
||||
$this->username = $username;
|
||||
$this->prefix = $username . '_';
|
||||
$this->userConf = $userConf;
|
||||
$this->packageConf = $packageConf;
|
||||
$this->settings = $settings;
|
||||
}
|
||||
|
||||
public static function fromEnvironment(Settings $settings): self
|
||||
{
|
||||
$username = Http::server('USER');
|
||||
if ($username === '') {
|
||||
$username = Http::server('USERNAME');
|
||||
}
|
||||
|
||||
if ($username === '' || !preg_match('/^[A-Za-z0-9._-]+$/', $username)) {
|
||||
throw new RuntimeException('Nie można ustalić użytkownika DirectAdmin.');
|
||||
}
|
||||
|
||||
$userConfPath = '/usr/local/directadmin/data/users/' . $username . '/user.conf';
|
||||
$userConf = self::loadSimpleConf($userConfPath);
|
||||
$packageConf = self::loadPackageConf($username, $userConf);
|
||||
|
||||
return new self($username, $userConf, $packageConf, $settings);
|
||||
}
|
||||
|
||||
public function username(): string
|
||||
{
|
||||
return $this->username;
|
||||
}
|
||||
|
||||
public function prefix(): string
|
||||
{
|
||||
return $this->prefix;
|
||||
}
|
||||
|
||||
public function language(): string
|
||||
{
|
||||
$lang = strtolower(trim((string)($this->userConf['language'] ?? $this->userConf['lang'] ?? 'en')));
|
||||
if ($lang === '' || strpos($lang, 'en') === 0) {
|
||||
return 'en';
|
||||
}
|
||||
if (strpos($lang, 'pl') === 0) {
|
||||
return 'pl';
|
||||
}
|
||||
return 'en';
|
||||
}
|
||||
|
||||
public function skin(): string
|
||||
{
|
||||
$skin = strtolower(trim((string)($this->userConf['skin'] ?? 'enhanced')));
|
||||
if (strpos($skin, 'evolution') !== false) {
|
||||
return 'evolution';
|
||||
}
|
||||
if (strpos($skin, 'enhanced') !== false) {
|
||||
return 'enhanced';
|
||||
}
|
||||
return 'enhanced';
|
||||
}
|
||||
|
||||
public function hasPluginAccess(): bool
|
||||
{
|
||||
if ($this->settings->alwaysEnabled()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return $this->isPluginEnabledByCustomItem() && $this->isDatabaseQuotaEnabled() && $this->isPluginAllowedByPluginRules();
|
||||
}
|
||||
|
||||
public function pluginAccessErrorMessage(): string
|
||||
{
|
||||
if (!$this->isPluginEnabledByCustomItem()) {
|
||||
return 'Plugin MySQL jest wyłączony dla tego konta lub pakietu.';
|
||||
}
|
||||
|
||||
if (!$this->isDatabaseQuotaEnabled()) {
|
||||
return 'Plugin MySQL jest wyłączony: limit baz danych MySQL ustawiono na 0 i nie zaznaczono opcji Bez Ograniczeń.';
|
||||
}
|
||||
|
||||
if (!$this->isPluginAllowedByPluginRules()) {
|
||||
return 'Plugin MySQL jest zablokowany przez reguły plugins_allow/plugins_deny.';
|
||||
}
|
||||
|
||||
return 'Brak dostępu do pluginu MySQL.';
|
||||
}
|
||||
|
||||
public function maxDatabases(): int
|
||||
{
|
||||
if ($this->settings->alwaysEnabled()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if ($this->isUnlimitedDatabasesByCustomItem()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$rawValue = $this->rawDatabasesLimitValue();
|
||||
if ($rawValue === null || trim($rawValue) === '') {
|
||||
$default = $this->settings->defaultDatabasesLimit();
|
||||
return $default < 0 ? 0 : $default;
|
||||
}
|
||||
|
||||
$normalized = strtolower(trim($rawValue));
|
||||
if ($normalized === 'unlimited') {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (!preg_match('/^[0-9]+$/', $normalized)) {
|
||||
$default = $this->settings->defaultDatabasesLimit();
|
||||
return $default < 0 ? 0 : $default;
|
||||
}
|
||||
|
||||
$limit = (int)$normalized;
|
||||
return $limit < 0 ? 0 : $limit;
|
||||
}
|
||||
|
||||
private function isPluginEnabledByCustomItem(): bool
|
||||
{
|
||||
$raw = $this->readScopedValue('mysql_enabled');
|
||||
if ($raw === null) {
|
||||
$raw = $this->readScopedValue('da_mysql_enabled');
|
||||
}
|
||||
if ($raw === null) {
|
||||
return false;
|
||||
}
|
||||
return Settings::toBool($raw, false);
|
||||
}
|
||||
|
||||
private function isUnlimitedDatabasesByCustomItem(): bool
|
||||
{
|
||||
$unlimitedFlags = [
|
||||
$this->readScopedValue('umysql'),
|
||||
$this->readScopedValue('umysql_max_databases'),
|
||||
$this->readScopedValue('mysql_unlimited'),
|
||||
];
|
||||
|
||||
foreach ($unlimitedFlags as $raw) {
|
||||
if ($raw !== null && Settings::toBool($raw, false)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
$rawLimit = $this->rawDatabasesLimitValue();
|
||||
return $rawLimit !== null && strtolower(trim($rawLimit)) === 'unlimited';
|
||||
}
|
||||
|
||||
private function isDatabaseQuotaEnabled(): bool
|
||||
{
|
||||
if ($this->isUnlimitedDatabasesByCustomItem()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return $this->maxDatabases() > 0;
|
||||
}
|
||||
|
||||
private function rawDatabasesLimitValue(): ?string
|
||||
{
|
||||
$raw = $this->readScopedValue('mysql_max_databases');
|
||||
if ($raw === null || trim($raw) === '') {
|
||||
$raw = $this->readScopedValue('mysql');
|
||||
}
|
||||
return $raw;
|
||||
}
|
||||
|
||||
private function isPluginAllowedByPluginRules(): bool
|
||||
{
|
||||
$pluginId = 'alt-mysql';
|
||||
|
||||
foreach ([$this->packageConf, $this->userConf] as $conf) {
|
||||
if (!empty($conf['plugins_allow'])) {
|
||||
$allow = self::parsePluginsList($conf['plugins_allow']);
|
||||
return in_array($pluginId, $allow, true);
|
||||
}
|
||||
}
|
||||
|
||||
foreach ([$this->packageConf, $this->userConf] as $conf) {
|
||||
if (!empty($conf['plugins_deny'])) {
|
||||
$deny = self::parsePluginsList($conf['plugins_deny']);
|
||||
return !in_array($pluginId, $deny, true);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private function readScopedValue(string $key): ?string
|
||||
{
|
||||
if (array_key_exists($key, $this->userConf)) {
|
||||
return $this->userConf[$key];
|
||||
}
|
||||
if (array_key_exists($key, $this->packageConf)) {
|
||||
return $this->packageConf[$key];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string,string>
|
||||
*/
|
||||
private static function loadSimpleConf(string $path): array
|
||||
{
|
||||
$data = [];
|
||||
if (!is_readable($path)) {
|
||||
return $data;
|
||||
}
|
||||
|
||||
$lines = file($path, FILE_IGNORE_NEW_LINES);
|
||||
if ($lines === false) {
|
||||
return $data;
|
||||
}
|
||||
|
||||
foreach ($lines as $line) {
|
||||
$line = trim($line);
|
||||
if ($line === '' || $line[0] === '#') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!preg_match('/^([A-Za-z0-9_]+)=(.*)$/', $line, $m)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$data[strtolower($m[1])] = trim((string)$m[2]);
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,string> $userConf
|
||||
* @return array<string,string>
|
||||
*/
|
||||
private static function loadPackageConf(string $username, array $userConf): array
|
||||
{
|
||||
$package = trim((string)($userConf['package'] ?? $userConf['user_package'] ?? ''));
|
||||
if ($package === '' || !preg_match('/^[A-Za-z0-9._-]+$/', $package)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$candidates = [];
|
||||
$owners = [];
|
||||
foreach (['creator', 'owner', 'reseller', 'username'] as $key) {
|
||||
if (!empty($userConf[$key]) && preg_match('/^[A-Za-z0-9._-]+$/', $userConf[$key])) {
|
||||
$owners[] = $userConf[$key];
|
||||
}
|
||||
}
|
||||
$owners[] = $username;
|
||||
$owners[] = 'admin';
|
||||
$owners = array_values(array_unique($owners));
|
||||
|
||||
foreach ($owners as $owner) {
|
||||
$candidates[] = '/usr/local/directadmin/data/users/' . $owner . '/packages/' . $package;
|
||||
$candidates[] = '/usr/local/directadmin/data/users/' . $owner . '/packages/' . $package . '.conf';
|
||||
}
|
||||
|
||||
foreach ($candidates as $path) {
|
||||
$conf = self::loadSimpleConf($path);
|
||||
if (!empty($conf)) {
|
||||
return $conf;
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string[]
|
||||
*/
|
||||
private static function parsePluginsList(string $value): array
|
||||
{
|
||||
$value = trim($value);
|
||||
if ($value === '') {
|
||||
return [];
|
||||
}
|
||||
|
||||
$items = [];
|
||||
foreach (explode(':', strtolower($value)) as $item) {
|
||||
$item = trim($item);
|
||||
if ($item !== '') {
|
||||
$items[] = $item;
|
||||
}
|
||||
}
|
||||
|
||||
return array_values(array_unique($items));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,536 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
final class FilePicker
|
||||
{
|
||||
public static function styles(): string
|
||||
{
|
||||
return <<<'CSS'
|
||||
.br-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(15, 23, 42, 0.6);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 9999;
|
||||
}
|
||||
.br-modal {
|
||||
width: min(560px, 92vw);
|
||||
background: #ffffff;
|
||||
border-radius: 12px;
|
||||
padding: 16px;
|
||||
border: 2px solid #d8dde6;
|
||||
box-shadow: 0 20px 40px rgba(15, 23, 42, 0.25);
|
||||
}
|
||||
.br-modal-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
.br-modal-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.br-modal-title {
|
||||
font-weight: 700;
|
||||
font-size: 16px;
|
||||
}
|
||||
.br-modal-body {
|
||||
max-height: 60vh;
|
||||
overflow: auto;
|
||||
}
|
||||
.br-muted { color: #64748b; }
|
||||
.br-alert {
|
||||
border-radius: 8px;
|
||||
padding: 10px 12px;
|
||||
margin: 8px 0;
|
||||
border: 1px solid transparent;
|
||||
}
|
||||
.br-alert-error { background: #fff1f2; border-color: #fecdd3; color: #9f1239; }
|
||||
.br-picker-path {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.br-picker-list {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
border: 1px solid #d8dde6;
|
||||
border-radius: 10px;
|
||||
max-height: 45vh;
|
||||
overflow: auto;
|
||||
}
|
||||
.br-picker-create {
|
||||
margin-top: 10px;
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
.br-picker-create input {
|
||||
flex: 1;
|
||||
padding: 6px 8px;
|
||||
border: 1px solid #d8dde6;
|
||||
border-radius: 8px;
|
||||
}
|
||||
.br-picker-list li {
|
||||
padding: 8px 12px;
|
||||
cursor: pointer;
|
||||
border-bottom: 1px solid #d8dde6;
|
||||
}
|
||||
.br-picker-list li:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
.br-picker-list li:hover {
|
||||
background: #f8fafc;
|
||||
}
|
||||
.br-picker-list li.active {
|
||||
background: #e0f2fe;
|
||||
}
|
||||
.br-btn {
|
||||
background: #b77200;
|
||||
color: #fff;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
padding: 8px 14px;
|
||||
cursor: pointer;
|
||||
font-weight: 600;
|
||||
}
|
||||
.br-btn:hover { background: #9a6200; }
|
||||
.br-btn-ghost {
|
||||
background: transparent;
|
||||
color: #1f2d3d;
|
||||
border: 1px solid #d8dde6;
|
||||
}
|
||||
.br-btn-ghost:hover { background: #eef2f7; }
|
||||
.br-btn-small {
|
||||
padding: 6px 10px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.br-icon-btn {
|
||||
border: 1px solid #d8dde6;
|
||||
background: #fff;
|
||||
border-radius: 8px;
|
||||
padding: 4px 8px;
|
||||
cursor: pointer;
|
||||
font-size: 16px;
|
||||
line-height: 1;
|
||||
}
|
||||
.br-icon-btn:hover {
|
||||
background: #f8fafc;
|
||||
}
|
||||
CSS;
|
||||
}
|
||||
|
||||
public static function scripts(): string
|
||||
{
|
||||
return <<<'JS'
|
||||
var pickerTarget = null;
|
||||
var pickerPath = '';
|
||||
var pickerBase = '';
|
||||
var pickerMode = 'dir';
|
||||
var pickerSelected = '';
|
||||
var pickerUrl = '';
|
||||
var pickerRoot = '';
|
||||
|
||||
function openPicker(inputId, mode) {
|
||||
var modal = document.getElementById('br-picker');
|
||||
if (!modal) { return; }
|
||||
var target = document.getElementById(inputId);
|
||||
if (!target) { return; }
|
||||
pickerTarget = target;
|
||||
pickerMode = mode === 'file' ? 'file' : 'dir';
|
||||
pickerSelected = '';
|
||||
pickerUrl = modal.getAttribute('data-picker-url') || window.location.href;
|
||||
pickerRoot = modal.getAttribute('data-picker-root') || '';
|
||||
|
||||
var initial = (target.value || '').trim();
|
||||
if (initial === '') {
|
||||
initial = pickerRoot || '';
|
||||
}
|
||||
var createRow = document.getElementById('br-picker-create');
|
||||
if (createRow) {
|
||||
createRow.style.display = (pickerMode === 'dir') ? 'flex' : 'none';
|
||||
}
|
||||
loadPicker(initial);
|
||||
modal.style.display = 'flex';
|
||||
}
|
||||
|
||||
function closePicker() {
|
||||
var modal = document.getElementById('br-picker');
|
||||
if (modal) { modal.style.display = 'none'; }
|
||||
}
|
||||
|
||||
function pickerSetError(msg) {
|
||||
var el = document.getElementById('br-picker-error');
|
||||
if (!el) { return; }
|
||||
if (msg) {
|
||||
el.textContent = msg;
|
||||
el.style.display = 'block';
|
||||
} else {
|
||||
el.textContent = '';
|
||||
el.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
function renderPickerList(items) {
|
||||
var list = document.getElementById('br-picker-list');
|
||||
if (!list) { return; }
|
||||
list.innerHTML = '';
|
||||
if (!items || !items.length) {
|
||||
var empty = document.createElement('li');
|
||||
empty.textContent = pickerMode === 'file' ? tr('Brak plików .sql/.gz') : tr('Brak katalogów');
|
||||
empty.className = 'br-muted';
|
||||
list.appendChild(empty);
|
||||
return;
|
||||
}
|
||||
items.forEach(function (entry) {
|
||||
var li = document.createElement('li');
|
||||
if (entry.type === 'dir') {
|
||||
li.textContent = '📁 ' + entry.name + '/';
|
||||
li.addEventListener('click', function () {
|
||||
pickerSelected = '';
|
||||
loadPicker(pickerPath.replace(/\/+$/, '') + '/' + entry.name);
|
||||
});
|
||||
} else {
|
||||
var full = pickerPath.replace(/\/+$/, '') + '/' + entry.name;
|
||||
li.textContent = '📄 ' + entry.name;
|
||||
li.addEventListener('click', function () {
|
||||
pickerSelected = full;
|
||||
var active = list.querySelectorAll('li.active');
|
||||
for (var i = 0; i < active.length; i += 1) {
|
||||
active[i].classList.remove('active');
|
||||
}
|
||||
li.classList.add('active');
|
||||
});
|
||||
if (pickerSelected === full) {
|
||||
li.classList.add('active');
|
||||
}
|
||||
}
|
||||
list.appendChild(li);
|
||||
});
|
||||
}
|
||||
|
||||
function extractPickerJson(text) {
|
||||
var marker = '__DA_MYSQL_PICKER_JSON__';
|
||||
var start = text.indexOf(marker);
|
||||
if (start === -1) { return null; }
|
||||
start += marker.length;
|
||||
var end = text.indexOf(marker, start);
|
||||
if (end === -1) { return null; }
|
||||
var jsonText = text.substring(start, end).trim();
|
||||
try { return JSON.parse(jsonText); } catch (e) { return null; }
|
||||
}
|
||||
|
||||
function loadPicker(path) {
|
||||
pickerSetError('');
|
||||
var url = pickerUrl + '?action=dir_list&mode=' + encodeURIComponent(pickerMode) + '&path=' + encodeURIComponent(path || '');
|
||||
fetch(url, { credentials: 'same-origin' })
|
||||
.then(function (r) { return r.text(); })
|
||||
.then(function (text) {
|
||||
var data = extractPickerJson(text || '');
|
||||
if (!data || !data.ok) {
|
||||
pickerSetError(tr('Nie udało się wczytać katalogów.'));
|
||||
return;
|
||||
}
|
||||
pickerPath = data.path || '';
|
||||
pickerBase = data.base || '';
|
||||
if (data.selected) {
|
||||
pickerSelected = data.selected;
|
||||
}
|
||||
var current = document.getElementById('br-picker-current');
|
||||
if (current) { current.textContent = pickerPath; }
|
||||
renderPickerList(data.items || []);
|
||||
})
|
||||
.catch(function () {
|
||||
pickerSetError(tr('Nie udało się wczytać katalogów.'));
|
||||
});
|
||||
}
|
||||
|
||||
function pickerGoUp() {
|
||||
if (!pickerPath) { return; }
|
||||
if (pickerBase && pickerPath === pickerBase) { return; }
|
||||
var up = pickerPath.replace(/\/+$/, '');
|
||||
up = up.substring(0, up.lastIndexOf('/')) || '/';
|
||||
loadPicker(up);
|
||||
}
|
||||
|
||||
function createPickerDir() {
|
||||
var input = document.getElementById('br-picker-new');
|
||||
if (!input) { return; }
|
||||
var name = (input.value || '').trim();
|
||||
if (name === '') {
|
||||
pickerSetError(tr('Podaj nazwę katalogu.'));
|
||||
return;
|
||||
}
|
||||
pickerSetError('');
|
||||
var url = pickerUrl + '?action=dir_create&path=' + encodeURIComponent(pickerPath || '') + '&name=' + encodeURIComponent(name);
|
||||
fetch(url, { credentials: 'same-origin' })
|
||||
.then(function (r) { return r.text(); })
|
||||
.then(function (text) {
|
||||
var data = extractPickerJson(text || '');
|
||||
if (!data || !data.ok) {
|
||||
pickerSetError(tr('Nie udało się utworzyć katalogu.'));
|
||||
return;
|
||||
}
|
||||
input.value = '';
|
||||
loadPicker(pickerPath);
|
||||
})
|
||||
.catch(function () {
|
||||
pickerSetError(tr('Nie udało się utworzyć katalogu.'));
|
||||
});
|
||||
}
|
||||
|
||||
function selectPickerPath() {
|
||||
if (!pickerTarget) { closePicker(); return; }
|
||||
if (pickerMode === 'file' && pickerSelected) {
|
||||
pickerTarget.value = pickerSelected || '';
|
||||
} else if (pickerMode === 'dir') {
|
||||
pickerTarget.value = pickerPath || '';
|
||||
}
|
||||
try {
|
||||
pickerTarget.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
pickerTarget.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
} catch (e) {
|
||||
// ignore dispatch errors on older browsers
|
||||
}
|
||||
if (typeof window.__restoreFileSync === 'function') {
|
||||
window.__restoreFileSync();
|
||||
}
|
||||
closePicker();
|
||||
}
|
||||
|
||||
function bindFilePicker() {
|
||||
window.openPicker = openPicker;
|
||||
window.closePicker = closePicker;
|
||||
window.pickerGoUp = pickerGoUp;
|
||||
window.createPickerDir = createPickerDir;
|
||||
window.selectPickerPath = selectPickerPath;
|
||||
}
|
||||
JS;
|
||||
}
|
||||
|
||||
public static function renderOverlay(AppContext $ctx, string $overlayId, string $rootPath, string $listUrl, string $inputId = 'source-file-path'): string
|
||||
{
|
||||
$safeRoot = AppContext::e($rootPath);
|
||||
$safeUrl = AppContext::e($listUrl);
|
||||
|
||||
$title = $ctx->t('Wybierz plik');
|
||||
$close = $ctx->t('Zamknij');
|
||||
$up = $ctx->t('W górę');
|
||||
$newDir = $ctx->t('Nowy katalog');
|
||||
$create = $ctx->t('Utwórz');
|
||||
$cancel = $ctx->t('Anuluj');
|
||||
$choose = $ctx->t('Wybierz');
|
||||
|
||||
$html = '';
|
||||
$html .= '<div id="br-picker" class="br-overlay" style="display:none;" data-picker-url="' . $safeUrl . '" data-picker-root="' . $safeRoot . '">';
|
||||
$html .= '<div class="br-modal">';
|
||||
$html .= '<div class="br-modal-header"><div class="br-modal-title">' . AppContext::e($title) . '</div><button class="br-btn br-btn-ghost br-btn-small" type="button" onclick="closePicker();">' . AppContext::e($close) . '</button></div>';
|
||||
$html .= '<div class="br-modal-body">';
|
||||
$html .= '<div class="br-picker-path"><button class="br-btn br-btn-ghost br-btn-small" type="button" onclick="pickerGoUp();">⟵ ' . AppContext::e($up) . '</button><span id="br-picker-current" class="br-muted"></span></div>';
|
||||
$html .= '<div id="br-picker-error" class="br-alert br-alert-error" style="display:none;"></div>';
|
||||
$html .= '<ul id="br-picker-list" class="br-picker-list"></ul>';
|
||||
$html .= '<div id="br-picker-create" class="br-picker-create" style="display:none;">';
|
||||
$html .= '<input id="br-picker-new" type="text" placeholder="' . AppContext::e($newDir) . '" />';
|
||||
$html .= '<button class="br-btn br-btn-ghost br-btn-small" type="button" onclick="createPickerDir();">' . AppContext::e($create) . '</button>';
|
||||
$html .= '</div>';
|
||||
$html .= '</div>';
|
||||
$html .= '<div class="br-modal-actions">';
|
||||
$html .= '<button class="br-btn br-btn-ghost" type="button" onclick="closePicker();">' . AppContext::e($cancel) . '</button>';
|
||||
$html .= '<button class="br-btn" type="button" onclick="selectPickerPath();">' . AppContext::e($choose) . '</button>';
|
||||
$html .= '</div>';
|
||||
$html .= '</div></div>';
|
||||
|
||||
return $html;
|
||||
}
|
||||
|
||||
public static function handleDirList(AppContext $ctx, BackupQueueService $queue, string $rootPath): bool
|
||||
{
|
||||
$action = strtolower($ctx->queryString('action'));
|
||||
if ($action !== 'dir_list') {
|
||||
return false;
|
||||
}
|
||||
|
||||
while (ob_get_level() > 0) {
|
||||
@ob_end_clean();
|
||||
}
|
||||
|
||||
$base = self::normalizeBase($rootPath);
|
||||
$mode = strtolower($ctx->queryString('mode', 'dir')) === 'file' ? 'file' : 'dir';
|
||||
$requested = trim($ctx->queryString('path', $base));
|
||||
if ($requested === '') {
|
||||
$requested = $base;
|
||||
}
|
||||
if ($requested !== '' && $requested[0] !== '/') {
|
||||
$requested = '/' . $requested;
|
||||
}
|
||||
|
||||
$selected = '';
|
||||
if ($mode === 'file' && $requested !== '') {
|
||||
$realReq = @realpath($requested);
|
||||
if ($realReq !== false && is_file($realReq)) {
|
||||
$selected = $realReq;
|
||||
$requested = dirname($realReq);
|
||||
}
|
||||
}
|
||||
|
||||
[$resolved, $base, $ok] = self::resolvePickerPath($requested, $base);
|
||||
if (!$ok) {
|
||||
self::pickerOutput(['ok' => false, 'error' => 'Nieprawidłowa ścieżka.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
if ($base !== '/' && $selected !== '') {
|
||||
if (strpos($selected, $base . '/') !== 0 && $selected !== $base) {
|
||||
$selected = '';
|
||||
}
|
||||
}
|
||||
|
||||
$dirItems = [];
|
||||
$fileItems = [];
|
||||
$entries = @scandir($resolved);
|
||||
if (is_array($entries)) {
|
||||
foreach ($entries as $entry) {
|
||||
if ($entry === '.' || $entry === '..') {
|
||||
continue;
|
||||
}
|
||||
$full = $resolved . '/' . $entry;
|
||||
if (is_dir($full)) {
|
||||
$dirItems[] = $entry;
|
||||
} elseif ($mode === 'file' && is_file($full) && $queue->isAllowedSqlFile($full)) {
|
||||
$fileItems[] = $entry;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
natcasesort($dirItems);
|
||||
natcasesort($fileItems);
|
||||
$items = [];
|
||||
foreach ($dirItems as $name) {
|
||||
$items[] = ['name' => $name, 'type' => 'dir'];
|
||||
}
|
||||
foreach ($fileItems as $name) {
|
||||
$items[] = ['name' => $name, 'type' => 'file'];
|
||||
}
|
||||
|
||||
self::pickerOutput([
|
||||
'ok' => true,
|
||||
'path' => $resolved,
|
||||
'base' => $base,
|
||||
'items' => $items,
|
||||
'selected' => $selected,
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
|
||||
public static function handleDirCreate(AppContext $ctx, string $rootPath, string $daUser): bool
|
||||
{
|
||||
$action = strtolower($ctx->queryString('action'));
|
||||
if ($action !== 'dir_create') {
|
||||
return false;
|
||||
}
|
||||
|
||||
while (ob_get_level() > 0) {
|
||||
@ob_end_clean();
|
||||
}
|
||||
|
||||
$base = self::normalizeBase($rootPath);
|
||||
$parentReq = trim($ctx->queryString('path', $base));
|
||||
if ($parentReq !== '' && $parentReq[0] !== '/') {
|
||||
$parentReq = '/' . $parentReq;
|
||||
}
|
||||
[$parent, $base, $ok] = self::resolvePickerPath($parentReq, $base);
|
||||
$name = trim($ctx->queryString('name'));
|
||||
if ($name === '' || $name === '.' || $name === '..' || strpos($name, '/') !== false || strpos($name, '\\') !== false) {
|
||||
self::pickerOutput(['ok' => false, 'error' => 'invalid_name']);
|
||||
exit;
|
||||
}
|
||||
if (!$ok || !is_dir($parent)) {
|
||||
self::pickerOutput(['ok' => false, 'error' => 'invalid_parent']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$newPath = rtrim($parent, '/') . '/' . $name;
|
||||
if ($base !== '/' && strpos($newPath, $base . '/') !== 0 && $newPath !== $base) {
|
||||
self::pickerOutput(['ok' => false, 'error' => 'outside_base']);
|
||||
exit;
|
||||
}
|
||||
if (file_exists($newPath)) {
|
||||
self::pickerOutput(['ok' => false, 'error' => 'exists']);
|
||||
exit;
|
||||
}
|
||||
if (!@mkdir($newPath, 0700, true)) {
|
||||
self::pickerOutput(['ok' => false, 'error' => 'mkdir_failed']);
|
||||
exit;
|
||||
}
|
||||
@chown($newPath, $daUser);
|
||||
@chgrp($newPath, $daUser);
|
||||
self::pickerOutput(['ok' => true, 'path' => $parent, 'base' => $base, 'created' => $newPath]);
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $payload
|
||||
*/
|
||||
private static function pickerOutput(array $payload): void
|
||||
{
|
||||
$json = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE);
|
||||
if ($json === false) {
|
||||
$json = json_encode(['ok' => false, 'error' => 'json_encode_failed'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
}
|
||||
$marker = '__DA_MYSQL_PICKER_JSON__';
|
||||
header('Content-Type: text/plain; charset=UTF-8');
|
||||
echo $marker . "\n" . $json . "\n" . $marker;
|
||||
}
|
||||
|
||||
private static function normalizeBase(string $base): string
|
||||
{
|
||||
$base = trim($base);
|
||||
if ($base === '') {
|
||||
return '/';
|
||||
}
|
||||
if ($base[0] !== '/') {
|
||||
$base = '/' . $base;
|
||||
}
|
||||
if ($base !== '/' && substr($base, -1) === '/') {
|
||||
$base = rtrim($base, '/');
|
||||
}
|
||||
return $base === '' ? '/' : $base;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0:string,1:string,2:bool}
|
||||
*/
|
||||
private static function resolvePickerPath(string $requested, string $base): array
|
||||
{
|
||||
$base = self::normalizeBase($base);
|
||||
$candidate = trim($requested);
|
||||
if ($candidate === '') {
|
||||
$candidate = $base;
|
||||
}
|
||||
if ($candidate[0] !== '/') {
|
||||
$candidate = '/' . $candidate;
|
||||
}
|
||||
$resolved = @realpath($candidate);
|
||||
if ($resolved === false || !is_dir($resolved)) {
|
||||
$resolved = @realpath($base);
|
||||
}
|
||||
if ($resolved === false || !is_dir($resolved)) {
|
||||
return [$base, $base, false];
|
||||
}
|
||||
if ($base !== '/' && strpos($resolved, $base . '/') !== 0 && $resolved !== $base) {
|
||||
$resolved = @realpath($base);
|
||||
}
|
||||
if ($resolved === false || !is_dir($resolved)) {
|
||||
return [$base, $base, false];
|
||||
}
|
||||
return [$resolved, $base, true];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
final class Http
|
||||
{
|
||||
public static function bootstrapGlobals(): void
|
||||
{
|
||||
if (PHP_SAPI !== 'cli') {
|
||||
return;
|
||||
}
|
||||
|
||||
$query = getenv('QUERY_STRING') ?: '';
|
||||
$method = strtoupper((string)(getenv('REQUEST_METHOD') ?: 'GET'));
|
||||
|
||||
$_GET = [];
|
||||
if ($query !== '') {
|
||||
parse_str($query, $_GET);
|
||||
}
|
||||
$queryAction = strtolower(trim((string)($_GET['action'] ?? '')));
|
||||
|
||||
$_POST = [];
|
||||
if ($method === 'POST') {
|
||||
$rawPost = (string)(getenv('POST') ?: '');
|
||||
if ($rawPost === '') {
|
||||
$rawPost = (string)(getenv('HTTP_POST') ?: '');
|
||||
}
|
||||
|
||||
$contentType = strtolower((string)(getenv('CONTENT_TYPE') ?: ''));
|
||||
$isUrlEncoded = ($contentType === '' || str_contains($contentType, 'application/x-www-form-urlencoded'));
|
||||
if ($rawPost === '' && $isUrlEncoded) {
|
||||
if ($queryAction !== 'upload_blob') {
|
||||
$stdin = @file_get_contents('php://stdin');
|
||||
if (is_string($stdin) && $stdin !== '') {
|
||||
$rawPost = $stdin;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($rawPost !== '') {
|
||||
parse_str($rawPost, $_POST);
|
||||
}
|
||||
}
|
||||
|
||||
$_REQUEST = array_merge($_GET, $_POST);
|
||||
$_SERVER['REQUEST_METHOD'] = $method;
|
||||
$_SERVER['QUERY_STRING'] = $query;
|
||||
|
||||
$knownServerVars = [
|
||||
'USER',
|
||||
'USERNAME',
|
||||
'HOME',
|
||||
'LANGUAGE',
|
||||
'SESSION_ID',
|
||||
'REQUEST_URI',
|
||||
'HTTP_HOST',
|
||||
'HTTPS',
|
||||
'HTTP_USER_AGENT',
|
||||
'HTTP_X_FORWARDED_PROTO',
|
||||
'HTTP_FRONT_END_HTTPS',
|
||||
'REQUEST_SCHEME',
|
||||
'SERVER_NAME',
|
||||
'SERVER_PORT',
|
||||
'REMOTE_ADDR',
|
||||
];
|
||||
foreach ($knownServerVars as $key) {
|
||||
if (!isset($_SERVER[$key])) {
|
||||
$value = getenv($key);
|
||||
if ($value !== false) {
|
||||
$_SERVER[$key] = $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static function method(): string
|
||||
{
|
||||
return strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET'));
|
||||
}
|
||||
|
||||
public static function isPost(): bool
|
||||
{
|
||||
return self::method() === 'POST';
|
||||
}
|
||||
|
||||
public static function getString(array $source, string $key, string $default = ''): string
|
||||
{
|
||||
if (!isset($source[$key])) {
|
||||
return $default;
|
||||
}
|
||||
|
||||
$value = $source[$key];
|
||||
if (is_array($value)) {
|
||||
return $default;
|
||||
}
|
||||
|
||||
return trim((string)$value);
|
||||
}
|
||||
|
||||
public static function getArray(array $source, string $key): array
|
||||
{
|
||||
if (!isset($source[$key])) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$value = $source[$key];
|
||||
if (!is_array($value)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
public static function server(string $key, string $default = ''): string
|
||||
{
|
||||
$value = $_SERVER[$key] ?? null;
|
||||
if ($value === null) {
|
||||
return $default;
|
||||
}
|
||||
|
||||
return trim((string)$value);
|
||||
}
|
||||
|
||||
public static function redirect(string $url): void
|
||||
{
|
||||
header('Location: ' . $url, true, 302);
|
||||
exit;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
final class Lang
|
||||
{
|
||||
/** @var array<string,string> */
|
||||
private array $map;
|
||||
|
||||
/**
|
||||
* @param array<string,string> $map
|
||||
*/
|
||||
private function __construct(array $map)
|
||||
{
|
||||
$this->map = $map;
|
||||
}
|
||||
|
||||
public static function load(string $code): self
|
||||
{
|
||||
$code = strtolower(trim($code));
|
||||
if ($code !== 'pl' && $code !== 'en') {
|
||||
$code = 'en';
|
||||
}
|
||||
|
||||
$path = PLUGIN_ROOT . '/lang/' . $code . '.php';
|
||||
if (!is_file($path)) {
|
||||
$path = PLUGIN_ROOT . '/lang/en.php';
|
||||
}
|
||||
|
||||
$map = [];
|
||||
if (is_file($path)) {
|
||||
$data = require $path;
|
||||
if (is_array($data)) {
|
||||
$map = $data;
|
||||
}
|
||||
}
|
||||
|
||||
return new self($map);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,string|int|float> $vars
|
||||
*/
|
||||
public function t(string $key, array $vars = []): string
|
||||
{
|
||||
$text = $this->map[$key] ?? $key;
|
||||
foreach ($vars as $var => $value) {
|
||||
$text = str_replace('{' . $var . '}', (string)$value, $text);
|
||||
}
|
||||
return $text;
|
||||
}
|
||||
|
||||
public function translateHtml(string $html): string
|
||||
{
|
||||
if ($html === '' || empty($this->map)) {
|
||||
return $html;
|
||||
}
|
||||
|
||||
$keys = array_keys($this->map);
|
||||
usort($keys, static function (string $a, string $b): int {
|
||||
return strlen($b) <=> strlen($a);
|
||||
});
|
||||
|
||||
$values = [];
|
||||
foreach ($keys as $key) {
|
||||
$values[] = $this->map[$key];
|
||||
}
|
||||
|
||||
return str_replace($keys, $values, $html);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string[]
|
||||
*/
|
||||
public function keys(): array
|
||||
{
|
||||
return array_keys($this->map);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
final class LocalizedException extends RuntimeException
|
||||
{
|
||||
/** @var array<string,string|int|float> */
|
||||
private array $vars;
|
||||
|
||||
/**
|
||||
* @param array<string,string|int|float> $vars
|
||||
*/
|
||||
public function __construct(string $key, array $vars = [], int $code = 0, ?Throwable $previous = null)
|
||||
{
|
||||
parent::__construct($key, $code, $previous);
|
||||
$this->vars = $vars;
|
||||
}
|
||||
|
||||
public function key(): string
|
||||
{
|
||||
return $this->getMessage();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string,string|int|float>
|
||||
*/
|
||||
public function vars(): array
|
||||
{
|
||||
return $this->vars;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,182 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
final class NamePolicy
|
||||
{
|
||||
public const MAX_IDENTIFIER_LEN = 64;
|
||||
public const MAX_HOST_COMMENT_LEN = 180;
|
||||
|
||||
/**
|
||||
* @var array<string,string>
|
||||
*/
|
||||
public const PRIVILEGE_LABELS = [
|
||||
'ALL' => 'Wszystkie uprawnienia',
|
||||
'SELECT' => 'SELECT',
|
||||
'INSERT' => 'INSERT',
|
||||
'UPDATE' => 'UPDATE',
|
||||
'DELETE' => 'DELETE',
|
||||
'CREATE' => 'CREATE',
|
||||
'ALTER' => 'ALTER',
|
||||
'DROP' => 'DROP',
|
||||
'INDEX' => 'INDEX',
|
||||
'REFERENCES' => 'REFERENCES',
|
||||
'CREATE_VIEW' => 'CREATE VIEW',
|
||||
'SHOW_VIEW' => 'SHOW VIEW',
|
||||
'TRIGGER' => 'TRIGGER',
|
||||
'EXECUTE' => 'EXECUTE',
|
||||
'EVENT' => 'EVENT',
|
||||
'LOCK_TABLES' => 'LOCK TABLES',
|
||||
];
|
||||
|
||||
public static function defaultPrivileges(): array
|
||||
{
|
||||
return ['ALL'];
|
||||
}
|
||||
|
||||
public static function normalizeDatabaseName(string $input, string $prefix): string
|
||||
{
|
||||
return self::normalizeIdentifier($input, $prefix, 'Nazwa bazy');
|
||||
}
|
||||
|
||||
public static function normalizeRoleName(string $input, string $prefix): string
|
||||
{
|
||||
return self::normalizeIdentifier($input, $prefix, 'Nazwa użytkownika');
|
||||
}
|
||||
|
||||
public static function assertBelongsToUser(string $name, string $prefix, string $entityLabel = 'Obiekt'): void
|
||||
{
|
||||
if (strpos($name, $prefix) !== 0) {
|
||||
throw new InvalidArgumentException($entityLabel . ' musi zaczynać się od prefiksu: ' . $prefix);
|
||||
}
|
||||
}
|
||||
|
||||
public static function normalizeIdentifier(string $input, string $prefix, string $label): string
|
||||
{
|
||||
$value = strtolower(trim($input));
|
||||
if ($value === '') {
|
||||
throw new InvalidArgumentException($label . ' jest wymagana.');
|
||||
}
|
||||
|
||||
if (!preg_match('/^[a-z0-9_]+$/', $value)) {
|
||||
throw new InvalidArgumentException($label . ' może zawierać wyłącznie znaki a-z, 0-9 oraz _.');
|
||||
}
|
||||
|
||||
if (strpos($value, $prefix) !== 0) {
|
||||
$value = $prefix . $value;
|
||||
}
|
||||
|
||||
if (strlen($value) > self::MAX_IDENTIFIER_LEN) {
|
||||
throw new InvalidArgumentException($label . ' przekracza limit 64 znaków MySQL.');
|
||||
}
|
||||
|
||||
if ($value === $prefix) {
|
||||
throw new InvalidArgumentException($label . ' nie może być równa samemu prefiksowi.');
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string[]
|
||||
*/
|
||||
public static function parseHosts(string $raw): array
|
||||
{
|
||||
$raw = str_replace(["\r\n", "\r", ';'], ["\n", "\n", "\n"], $raw);
|
||||
$raw = str_replace(',', "\n", $raw);
|
||||
$parts = explode("\n", $raw);
|
||||
|
||||
$hosts = [];
|
||||
foreach ($parts as $part) {
|
||||
$part = trim($part);
|
||||
if ($part === '') {
|
||||
continue;
|
||||
}
|
||||
$hosts[] = $part;
|
||||
}
|
||||
|
||||
return array_values(array_unique($hosts));
|
||||
}
|
||||
|
||||
public static function normalizeHost(string $input, bool $allowWildcard): string
|
||||
{
|
||||
$host = strtolower(trim($input));
|
||||
if ($host === '') {
|
||||
throw new InvalidArgumentException('Pusty host.');
|
||||
}
|
||||
|
||||
if (in_array($host, ['localhost', '127.0.0.1', '::1', '%'], true)) {
|
||||
return $host;
|
||||
}
|
||||
|
||||
if (self::isStrictIpv4($host)) {
|
||||
return $host;
|
||||
}
|
||||
|
||||
if ($allowWildcard && preg_match('/^[A-Za-z0-9._%-]+$/', $host)) {
|
||||
return $host;
|
||||
}
|
||||
|
||||
throw new InvalidArgumentException('Nieobsługiwany format hosta: ' . $input);
|
||||
}
|
||||
|
||||
public static function normalizeRemoteIpv4Host(string $input): string
|
||||
{
|
||||
$host = trim($input);
|
||||
if ($host === '') {
|
||||
throw new InvalidArgumentException('Adres IPv4 jest wymagany.');
|
||||
}
|
||||
|
||||
if (!self::isStrictIpv4($host)) {
|
||||
throw new InvalidArgumentException('Dozwolone są tylko pojedyncze adresy IPv4, np. 203.0.113.10.');
|
||||
}
|
||||
|
||||
return $host;
|
||||
}
|
||||
|
||||
public static function normalizeHostComment(string $input): string
|
||||
{
|
||||
$comment = trim(preg_replace('/[\r\n\t]+/', ' ', $input) ?? '');
|
||||
$comment = preg_replace('/\s+/', ' ', $comment) ?? '';
|
||||
$comment = trim($comment);
|
||||
|
||||
if (strlen($comment) > self::MAX_HOST_COMMENT_LEN) {
|
||||
throw new InvalidArgumentException('Komentarz hosta przekracza limit ' . self::MAX_HOST_COMMENT_LEN . ' znaków.');
|
||||
}
|
||||
|
||||
return $comment;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int,string> $input
|
||||
* @return string[]
|
||||
*/
|
||||
public static function sanitizePrivileges(array $input): array
|
||||
{
|
||||
$allowed = array_keys(self::PRIVILEGE_LABELS);
|
||||
$result = [];
|
||||
|
||||
foreach ($input as $priv) {
|
||||
$priv = strtoupper(trim((string)$priv));
|
||||
if ($priv === '' || !in_array($priv, $allowed, true)) {
|
||||
continue;
|
||||
}
|
||||
$result[] = $priv;
|
||||
}
|
||||
|
||||
$result = array_values(array_unique($result));
|
||||
if (in_array('ALL', $result, true)) {
|
||||
return ['ALL'];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
private static function isStrictIpv4(string $value): bool
|
||||
{
|
||||
if (!preg_match('/^(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?:\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}$/', $value)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
final class PhpMyAdminRuntimeConfig
|
||||
{
|
||||
private const FILE_NAME = 'config.json';
|
||||
|
||||
public static function sync(Settings $settings, string $pluginErrorLog = ''): void
|
||||
{
|
||||
$runtimeDir = rtrim($settings->adminerSsoDir(), '/');
|
||||
if ($runtimeDir === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!is_dir($runtimeDir) && !@mkdir($runtimeDir, 0755, true) && !is_dir($runtimeDir)) {
|
||||
self::log($pluginErrorLog, 'Cannot create phpMyAdmin runtime dir: ' . $runtimeDir);
|
||||
return;
|
||||
}
|
||||
|
||||
$payload = [
|
||||
'version' => 1,
|
||||
'phpmyadmin_url_path' => $settings->adminerUrlPath(),
|
||||
'phpmyadmin_public_base_url' => $settings->adminerPublicBaseUrl(),
|
||||
'ticket_dir' => $runtimeDir . '/tickets',
|
||||
'host' => 'dynamic:' . basename($settings->mysqlCredentialsFile()),
|
||||
'credentials_file' => $settings->mysqlCredentialsFile(),
|
||||
'client_bin_dir' => $settings->mysqlClientBinDir(),
|
||||
'updated_at' => time(),
|
||||
];
|
||||
|
||||
$encoded = json_encode($payload, JSON_UNESCAPED_SLASHES);
|
||||
if (!is_string($encoded) || $encoded === '') {
|
||||
self::log($pluginErrorLog, 'Failed to encode phpMyAdmin runtime config JSON.');
|
||||
return;
|
||||
}
|
||||
|
||||
$targetPath = $runtimeDir . '/' . self::FILE_NAME;
|
||||
if (@file_put_contents($targetPath, $encoded) === false) {
|
||||
self::log($pluginErrorLog, 'Failed to write phpMyAdmin runtime config: ' . $targetPath);
|
||||
return;
|
||||
}
|
||||
|
||||
@chmod($targetPath, 0644);
|
||||
}
|
||||
|
||||
private static function log(string $pluginErrorLog, string $message): void
|
||||
{
|
||||
if ($pluginErrorLog === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
$line = sprintf("[%s] PHPMYADMIN_RUNTIME_CONFIG %s\n", date('c'), $message);
|
||||
@error_log($line, 3, $pluginErrorLog);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
final class PhpMyAdminSso
|
||||
{
|
||||
private Settings $settings;
|
||||
private DirectAdminUser $daUser;
|
||||
private MySQLService $db;
|
||||
|
||||
public function __construct(Settings $settings, DirectAdminUser $daUser, MySQLService $db)
|
||||
{
|
||||
$this->settings = $settings;
|
||||
$this->daUser = $daUser;
|
||||
$this->db = $db;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{target:string,auth:array<string,string|int>}
|
||||
*/
|
||||
public function issueLoginPayload(?string $requestedDatabase = null): array
|
||||
{
|
||||
if (!$this->settings->enableAdminer()) {
|
||||
throw new RuntimeException('Integracja phpMyAdmin jest wyłączona.');
|
||||
}
|
||||
|
||||
$this->db->cleanupExpiredAdminerRoles();
|
||||
|
||||
$databaseRows = $this->db->listDatabasesForUser($this->daUser->username(), false);
|
||||
if (empty($databaseRows)) {
|
||||
throw new RuntimeException('Użytkownik nie ma żadnej bazy MySQL do otwarcia w phpMyAdmin.');
|
||||
}
|
||||
|
||||
$databaseNames = [];
|
||||
foreach ($databaseRows as $row) {
|
||||
$name = (string)($row['name'] ?? '');
|
||||
if ($name !== '') {
|
||||
$databaseNames[] = $name;
|
||||
}
|
||||
}
|
||||
$databaseNames = array_values(array_unique($databaseNames));
|
||||
|
||||
$targetDatabase = '';
|
||||
if ($requestedDatabase !== null) {
|
||||
$requestedDatabase = trim($requestedDatabase);
|
||||
if ($requestedDatabase !== '') {
|
||||
if (!in_array($requestedDatabase, $databaseNames, true)) {
|
||||
throw new RuntimeException('Wskazana baza danych nie należy do zalogowanego użytkownika.');
|
||||
}
|
||||
$targetDatabase = $requestedDatabase;
|
||||
}
|
||||
}
|
||||
if ($targetDatabase === '') {
|
||||
$targetDatabase = $databaseNames[0];
|
||||
}
|
||||
|
||||
$roleTtl = max($this->settings->adminerRoleTtl(), $this->settings->adminerSessionTtl() + 120);
|
||||
$role = $this->generateTemporaryRoleName();
|
||||
$password = $this->generateSecret(32);
|
||||
$expiresAt = time() + $roleTtl;
|
||||
|
||||
$this->db->createTemporaryRole($role, $password, $expiresAt);
|
||||
try {
|
||||
foreach ($databaseNames as $dbName) {
|
||||
$this->db->grantTemporaryAdminerAccess($dbName, $role);
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
try {
|
||||
$this->db->dropTemporaryRole($role);
|
||||
} catch (Throwable $ignored) {
|
||||
}
|
||||
throw new RuntimeException('Nie udało się przygotować sesji phpMyAdmin: ' . $e->getMessage(), 0, $e);
|
||||
}
|
||||
|
||||
$auth = [
|
||||
'user' => $role,
|
||||
'password' => $password,
|
||||
'host' => $this->db->connectionEndpoint()['host'],
|
||||
'port' => $this->db->connectionEndpoint()['port'],
|
||||
'db' => $targetDatabase,
|
||||
];
|
||||
$ticket = $this->writeLoginTicket($auth, $targetDatabase);
|
||||
|
||||
return [
|
||||
'target' => $this->buildPhpMyAdminLoginUrl($targetDatabase, $ticket),
|
||||
'auth' => $auth,
|
||||
];
|
||||
}
|
||||
|
||||
private function buildPhpMyAdminLoginUrl(string $database, string $ticket): string
|
||||
{
|
||||
$query = http_build_query([
|
||||
'ticket' => $ticket,
|
||||
'route' => '/database/structure',
|
||||
'db' => $database,
|
||||
]);
|
||||
|
||||
return $this->phpMyAdminBaseUrl() . '/da_login.php?' . $query;
|
||||
}
|
||||
|
||||
private function phpMyAdminBaseUrl(): string
|
||||
{
|
||||
$path = $this->settings->adminerUrlPath();
|
||||
$customBase = $this->settings->adminerPublicBaseUrl();
|
||||
if ($customBase !== '') {
|
||||
return $customBase . $path;
|
||||
}
|
||||
|
||||
$scheme = 'http';
|
||||
$https = strtolower(Http::server('HTTPS'));
|
||||
if ($https !== '' && $https !== 'off' && $https !== '0') {
|
||||
$scheme = 'https';
|
||||
} elseif (strtolower(Http::server('HTTP_X_FORWARDED_PROTO')) === 'https') {
|
||||
$scheme = 'https';
|
||||
} elseif (strtolower(Http::server('REQUEST_SCHEME')) === 'https') {
|
||||
$scheme = 'https';
|
||||
}
|
||||
|
||||
$host = Http::server('HTTP_HOST');
|
||||
if ($host === '') {
|
||||
$host = Http::server('SERVER_NAME', 'localhost');
|
||||
}
|
||||
$host = preg_replace('/:\d+$/', '', $host) ?? $host;
|
||||
|
||||
return $scheme . '://' . $host . $path;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,string|int> $auth
|
||||
*/
|
||||
private function writeLoginTicket(array $auth, string $database): string
|
||||
{
|
||||
$ticketDir = rtrim($this->settings->adminerSsoDir(), '/') . '/tickets';
|
||||
if (!is_dir($ticketDir) && !@mkdir($ticketDir, 0755, true) && !is_dir($ticketDir)) {
|
||||
throw new RuntimeException('Nie można utworzyć katalogu ticketów phpMyAdmin: ' . $ticketDir);
|
||||
}
|
||||
|
||||
$this->cleanupExpiredTickets($ticketDir);
|
||||
|
||||
$token = bin2hex(random_bytes(32));
|
||||
$payload = [
|
||||
'version' => 1,
|
||||
'created_at' => time(),
|
||||
'expires_at' => time() + $this->settings->adminerTicketTtl(),
|
||||
'auth' => $auth,
|
||||
'route' => '/database/structure',
|
||||
'db' => $database,
|
||||
];
|
||||
$encoded = json_encode($payload, JSON_UNESCAPED_SLASHES);
|
||||
if (!is_string($encoded) || $encoded === '') {
|
||||
throw new RuntimeException('Nie udało się zakodować ticketu phpMyAdmin.');
|
||||
}
|
||||
|
||||
$path = $ticketDir . '/' . $token . '.json';
|
||||
$tmpPath = $path . '.tmp.' . bin2hex(random_bytes(4));
|
||||
if (@file_put_contents($tmpPath, $encoded, LOCK_EX) === false) {
|
||||
throw new RuntimeException('Nie udało się zapisać ticketu phpMyAdmin.');
|
||||
}
|
||||
@chmod($tmpPath, 0644);
|
||||
if (!@rename($tmpPath, $path)) {
|
||||
@unlink($tmpPath);
|
||||
throw new RuntimeException('Nie udało się aktywować ticketu phpMyAdmin.');
|
||||
}
|
||||
|
||||
return $token;
|
||||
}
|
||||
|
||||
private function cleanupExpiredTickets(string $ticketDir): void
|
||||
{
|
||||
foreach (glob($ticketDir . '/*.json') ?: [] as $path) {
|
||||
if (!is_file($path)) {
|
||||
continue;
|
||||
}
|
||||
$raw = @file_get_contents($path);
|
||||
$decoded = is_string($raw) ? json_decode($raw, true) : null;
|
||||
$expiresAt = is_array($decoded) ? (int)($decoded['expires_at'] ?? 0) : 0;
|
||||
if ($expiresAt > 0 && $expiresAt >= time()) {
|
||||
continue;
|
||||
}
|
||||
@unlink($path);
|
||||
}
|
||||
}
|
||||
|
||||
private function generateTemporaryRoleName(): string
|
||||
{
|
||||
$base = strtolower($this->daUser->username());
|
||||
$base = preg_replace('/[^a-z0-9_]+/', '_', $base) ?? 'user';
|
||||
$base = trim($base, '_');
|
||||
if ($base === '') {
|
||||
$base = 'user';
|
||||
}
|
||||
|
||||
for ($i = 0; $i < 5; $i++) {
|
||||
$suffix = bin2hex(random_bytes(6));
|
||||
$maxBaseLen = NamePolicy::MAX_IDENTIFIER_LEN - strlen('da_tmp_phpmyadmin_') - 1 - strlen($suffix);
|
||||
if ($maxBaseLen < 1) {
|
||||
$maxBaseLen = 1;
|
||||
}
|
||||
$safeBase = substr($base, 0, $maxBaseLen);
|
||||
$role = 'da_tmp_phpmyadmin_' . $safeBase . '_' . $suffix;
|
||||
if (!$this->db->roleExists($role)) {
|
||||
return $role;
|
||||
}
|
||||
}
|
||||
|
||||
throw new RuntimeException('Nie udało się wygenerować unikalnego tymczasowego użytkownika dla phpMyAdmin.');
|
||||
}
|
||||
|
||||
private function generateSecret(int $len): string
|
||||
{
|
||||
$value = rtrim(strtr(base64_encode(random_bytes(48)), '+/', 'AZ'), '=');
|
||||
if (strlen($value) >= $len) {
|
||||
return substr($value, 0, $len);
|
||||
}
|
||||
return str_pad($value, $len, 'x');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,472 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
final class Settings
|
||||
{
|
||||
/** @var array<string,string> */
|
||||
private array $values;
|
||||
|
||||
private function __construct(array $values)
|
||||
{
|
||||
$this->values = $values;
|
||||
}
|
||||
|
||||
public static function load(string $path): self
|
||||
{
|
||||
$values = [];
|
||||
if (is_readable($path)) {
|
||||
$lines = file($path, FILE_IGNORE_NEW_LINES);
|
||||
if ($lines !== false) {
|
||||
foreach ($lines as $line) {
|
||||
$line = trim($line);
|
||||
if ($line === '' || $line[0] === '#') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!preg_match('/^([A-Za-z0-9_]+)=(.*)$/', $line, $m)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$values[$m[1]] = self::parseShValue((string)$m[2]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new self($values);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{host:string,port:int,database:string,user:string,password:string,socket:string}
|
||||
*/
|
||||
public static function loadMysqlCredentials(string $path): array
|
||||
{
|
||||
if (!is_readable($path)) {
|
||||
throw new RuntimeException('Brak pliku z danymi MySQL: ' . $path);
|
||||
}
|
||||
|
||||
$lines = file($path, FILE_IGNORE_NEW_LINES);
|
||||
if ($lines === false) {
|
||||
throw new RuntimeException('Nie można odczytać pliku: ' . $path);
|
||||
}
|
||||
|
||||
$kv = [];
|
||||
foreach ($lines as $line) {
|
||||
$line = trim($line);
|
||||
if ($line === '' || $line[0] === '#') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (strpos($line, '=') !== false) {
|
||||
[$k, $v] = array_map('trim', explode('=', $line, 2));
|
||||
if ($k !== '') {
|
||||
$kv[strtoupper($k)] = self::parseShValue($v);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
$parts = explode(':', $line);
|
||||
if (count($parts) >= 5) {
|
||||
return [
|
||||
'host' => trim($parts[0]) !== '' ? trim($parts[0]) : 'localhost',
|
||||
'port' => (int)(trim($parts[1]) !== '' ? trim($parts[1]) : '3306'),
|
||||
'database' => trim($parts[2]) !== '' ? trim($parts[2]) : 'mysql',
|
||||
'user' => trim($parts[3]) !== '' ? trim($parts[3]) : 'root',
|
||||
'password' => trim(implode(':', array_slice($parts, 4))),
|
||||
'socket' => '',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
$host = trim((string)($kv['HOST'] ?? $kv['MYSQL_HOST'] ?? ''));
|
||||
if ($host === '') {
|
||||
$host = 'localhost';
|
||||
}
|
||||
|
||||
$portRaw = trim((string)($kv['PORT'] ?? $kv['MYSQL_PORT'] ?? '3306'));
|
||||
$port = preg_match('/^[0-9]+$/', $portRaw) ? (int)$portRaw : 3306;
|
||||
if ($port < 1 || $port > 65535) {
|
||||
$port = 3306;
|
||||
}
|
||||
|
||||
$database = trim((string)($kv['DATABASE'] ?? $kv['MYSQL_DATABASE'] ?? $kv['DB'] ?? 'mysql'));
|
||||
if ($database === '' || $database === '*') {
|
||||
$database = 'mysql';
|
||||
}
|
||||
|
||||
$user = trim((string)($kv['USER'] ?? $kv['MYSQL_USER'] ?? 'root'));
|
||||
$password = trim((string)($kv['PASSWORD'] ?? $kv['PASSWD'] ?? $kv['MYSQL_PASSWORD'] ?? ''));
|
||||
$socket = trim((string)($kv['SOCKET'] ?? $kv['MYSQL_SOCKET'] ?? ''));
|
||||
|
||||
if ($user === '') {
|
||||
throw new RuntimeException('Brak użytkownika MySQL w pliku: ' . $path);
|
||||
}
|
||||
|
||||
return [
|
||||
'host' => $host,
|
||||
'port' => $port,
|
||||
'database' => $database,
|
||||
'user' => $user,
|
||||
'password' => $password,
|
||||
'socket' => $socket,
|
||||
];
|
||||
}
|
||||
|
||||
public function mysqlCredentialsFile(): string
|
||||
{
|
||||
$path = trim($this->getString('MYSQL_PLUGIN_CREDENTIALS_FILE', '/usr/local/directadmin/conf/alt-mysql.conf'));
|
||||
return $path !== '' ? $path : '/usr/local/directadmin/conf/alt-mysql.conf';
|
||||
}
|
||||
|
||||
public function mysqlClientBinDir(): string
|
||||
{
|
||||
return rtrim(trim($this->getString('MYSQL_PLUGIN_CLIENT_BIN_DIR', '')), '/');
|
||||
}
|
||||
|
||||
public function getString(string $key, string $default = ''): string
|
||||
{
|
||||
return isset($this->values[$key]) ? trim($this->values[$key]) : $default;
|
||||
}
|
||||
|
||||
public function getInt(string $key, int $default = 0): int
|
||||
{
|
||||
if (!isset($this->values[$key])) {
|
||||
return $default;
|
||||
}
|
||||
|
||||
$value = trim($this->values[$key]);
|
||||
if ($value === '' || !preg_match('/^-?[0-9]+$/', $value)) {
|
||||
return $default;
|
||||
}
|
||||
|
||||
return (int)$value;
|
||||
}
|
||||
|
||||
public function getBool(string $key, bool $default = false): bool
|
||||
{
|
||||
if (!isset($this->values[$key])) {
|
||||
return $default;
|
||||
}
|
||||
|
||||
return self::toBool($this->values[$key], $default);
|
||||
}
|
||||
|
||||
public function defaultDatabasesLimit(): int
|
||||
{
|
||||
$limit = $this->getInt('MYSQL_PLUGIN_DEFAULT_DB_LIMIT', 5);
|
||||
return $limit < 0 ? 0 : $limit;
|
||||
}
|
||||
|
||||
public function alwaysEnabled(): bool
|
||||
{
|
||||
return $this->getBool('always_enabled', true);
|
||||
}
|
||||
|
||||
public function maxHostsPerUser(): int
|
||||
{
|
||||
$limit = $this->getInt('MYSQL_PLUGIN_MAX_HOSTS_PER_USER', 30);
|
||||
return $limit < 1 ? 1 : $limit;
|
||||
}
|
||||
|
||||
public function allowRemoteHosts(): bool
|
||||
{
|
||||
if (array_key_exists('allow_remote_hosts', $this->values)) {
|
||||
return self::toBool($this->values['allow_remote_hosts'], false);
|
||||
}
|
||||
|
||||
if (array_key_exists('MYSQL_PLUGIN_ALLOW_REMOTE_HOSTS', $this->values)) {
|
||||
return self::toBool($this->values['MYSQL_PLUGIN_ALLOW_REMOTE_HOSTS'], false);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function modifyServerConfiguration(): bool
|
||||
{
|
||||
if ($this->allowRemoteHosts()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (array_key_exists('modify_server_configuration', $this->values)) {
|
||||
return self::toBool($this->values['modify_server_configuration'], false);
|
||||
}
|
||||
|
||||
if (array_key_exists('MYSQL_PLUGIN_MODIFY_SERVER_CONFIGURATION', $this->values)) {
|
||||
return self::toBool($this->values['MYSQL_PLUGIN_MODIFY_SERVER_CONFIGURATION'], false);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function hostSyncScript(): string
|
||||
{
|
||||
$default = '/usr/local/directadmin/plugins/alt-mysql/scripts/setup/mysql_host_sync.sh';
|
||||
$path = $this->getString('MYSQL_PLUGIN_SUDO_SYNC_HOSTS', $default);
|
||||
return $path !== '' ? $path : $default;
|
||||
}
|
||||
|
||||
public function enableBackup(): bool
|
||||
{
|
||||
return $this->getBool('ENABLE_BACKUP', true);
|
||||
}
|
||||
|
||||
public function enableUploadBackup(): bool
|
||||
{
|
||||
return $this->getBool('ENABLE_UPLOAD_BACKUP', true);
|
||||
}
|
||||
|
||||
public function enableAdminer(): bool
|
||||
{
|
||||
if (!$this->getBool('ENABLE_PHPMYADMIN', $this->getBool('ENABLE_ADMINER', true))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->isPhpMyAdminInstalled();
|
||||
}
|
||||
|
||||
public function phpMyAdminInstallDir(): string
|
||||
{
|
||||
$path = trim($this->getString('PHPMYADMIN_INSTALL_DIR', '/var/www/html/alt-mysql-phpmyadmin'));
|
||||
return $path !== '' ? rtrim($path, '/') : '/var/www/html/alt-mysql-phpmyadmin';
|
||||
}
|
||||
|
||||
public function adminerUrlPath(): string
|
||||
{
|
||||
$path = trim($this->getString('PHPMYADMIN_URL_PATH', $this->getString('ADMINER_URL_PATH', '/alt-mysql-phpmyadmin')));
|
||||
if ($path === '') {
|
||||
return '/alt-mysql-phpmyadmin';
|
||||
}
|
||||
|
||||
if ($path[0] !== '/') {
|
||||
$path = '/' . $path;
|
||||
}
|
||||
|
||||
$path = rtrim($path, '/');
|
||||
return $path !== '' ? $path : '/alt-mysql-phpmyadmin';
|
||||
}
|
||||
|
||||
public function adminerPublicBaseUrl(): string
|
||||
{
|
||||
$url = trim($this->getString('PHPMYADMIN_PUBLIC_BASE_URL', $this->getString('ADMINER_PUBLIC_BASE_URL', '')));
|
||||
if ($url === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
$url = rtrim($url, '/');
|
||||
if (!preg_match('#^https?://#i', $url)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return $url;
|
||||
}
|
||||
|
||||
public function adminerPublic(): bool
|
||||
{
|
||||
return $this->getBool('PHPMYADMIN_PUBLIC', $this->getBool('ADMINER_PUBLIC', false));
|
||||
}
|
||||
|
||||
public function adminerSsoDir(): string
|
||||
{
|
||||
$path = trim($this->getString('PHPMYADMIN_SSO_DIR', $this->getString('ADMINER_SSO_DIR', $this->phpMyAdminInstallDir() . '/runtime')));
|
||||
if ($path === '') {
|
||||
$path = $this->phpMyAdminInstallDir() . '/runtime';
|
||||
}
|
||||
return rtrim($path, '/');
|
||||
}
|
||||
|
||||
public function adminerTicketTtl(): int
|
||||
{
|
||||
$ttl = $this->getInt('PHPMYADMIN_TICKET_TTL', $this->getInt('ADMINER_TICKET_TTL', 120));
|
||||
if ($ttl < 10) {
|
||||
return 10;
|
||||
}
|
||||
if ($ttl > 300) {
|
||||
return 300;
|
||||
}
|
||||
return $ttl;
|
||||
}
|
||||
|
||||
public function adminerSessionTtl(): int
|
||||
{
|
||||
$ttl = $this->getInt('PHPMYADMIN_SESSION_TTL', $this->getInt('ADMINER_SESSION_TTL', 900));
|
||||
if ($ttl < 60) {
|
||||
return 60;
|
||||
}
|
||||
if ($ttl > 3600) {
|
||||
return 3600;
|
||||
}
|
||||
return $ttl;
|
||||
}
|
||||
|
||||
public function adminerRoleTtl(): int
|
||||
{
|
||||
$ttl = $this->getInt('PHPMYADMIN_ROLE_TTL', $this->getInt('ADMINER_ROLE_TTL', 1200));
|
||||
if ($ttl < 120) {
|
||||
return 120;
|
||||
}
|
||||
if ($ttl > 7200) {
|
||||
return 7200;
|
||||
}
|
||||
return $ttl;
|
||||
}
|
||||
|
||||
public function phpMyAdminIntegrationWarning(): string
|
||||
{
|
||||
if (!$this->getBool('ENABLE_PHPMYADMIN', $this->getBool('ENABLE_ADMINER', true))) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$dir = $this->phpMyAdminInstallDir();
|
||||
if (!is_dir($dir)) {
|
||||
return 'Prywatna kopia phpMyAdmin dla pluginu nie jest zainstalowana. Uruchom scripts/setup/phpmyadmin_private_install.sh jako root.';
|
||||
}
|
||||
|
||||
$config = $dir . '/config.inc.php';
|
||||
$signon = $dir . '/da_signon.php';
|
||||
$signonUrl = $dir . '/da_login.php';
|
||||
|
||||
if (!is_readable($config)) {
|
||||
return 'Prywatny phpMyAdmin pluginu jest zainstalowany, ale nie można odczytać config.inc.php.';
|
||||
}
|
||||
|
||||
if (!is_readable($signon)) {
|
||||
return 'Prywatny phpMyAdmin pluginu jest zainstalowany, ale brakuje da_signon.php. Uruchom scripts/setup/phpmyadmin_repair.sh jako root.';
|
||||
}
|
||||
if (!is_readable($signonUrl)) {
|
||||
return 'Prywatny phpMyAdmin pluginu jest zainstalowany, ale brakuje da_login.php. Uruchom scripts/setup/phpmyadmin_repair.sh jako root.';
|
||||
}
|
||||
|
||||
$contents = file_get_contents($config);
|
||||
if (!is_string($contents) || strpos($contents, 'DA_MYSQL_PMA_DEFAULT_CONF') === false) {
|
||||
return 'Prywatny phpMyAdmin pluginu nie ma konfiguracji alt-mysql. Uruchom scripts/setup/phpmyadmin_repair.sh jako root.';
|
||||
}
|
||||
if (strpos($contents, "SignonURL'] = da_mysql_phpmyadmin_signon_url") === false) {
|
||||
return 'Prywatny phpMyAdmin pluginu nie ma wymaganej konfiguracji SignonURL. Uruchom scripts/setup/phpmyadmin_repair.sh jako root.';
|
||||
}
|
||||
$signonUrlContents = file_get_contents($signonUrl);
|
||||
if (!is_string($signonUrlContents) || strpos($signonUrlContents, 'da_mysql_login_consume_ticket') === false) {
|
||||
return 'Prywatny phpMyAdmin pluginu nie obsługuje jednorazowych ticketów SSO. Uruchom scripts/setup/phpmyadmin_repair.sh jako root.';
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
public function allowRestoreToOtherDatabase(): bool
|
||||
{
|
||||
return $this->getBool('ALLOW_RESTORE_TO_OTHER_DATABASE', true);
|
||||
}
|
||||
|
||||
public function enableTableCount(): bool
|
||||
{
|
||||
return $this->getBool('ENABLE_TABLE_COUNT', true);
|
||||
}
|
||||
|
||||
public function countDatabaseSize(): bool
|
||||
{
|
||||
return $this->getBool('COUNT_DATABASE_SIZE', true);
|
||||
}
|
||||
|
||||
public function compressBackup(): bool
|
||||
{
|
||||
return $this->getBool('COMPRESS_BACKUP', true);
|
||||
}
|
||||
|
||||
public function hitmeBackupLocation(string $daUser = ''): string
|
||||
{
|
||||
$path = $this->getString('HITME_BACKUP_LOCATION', '/home/admin/mysql_backup');
|
||||
if ($path === '') {
|
||||
$path = '/home/admin/mysql_backup';
|
||||
}
|
||||
|
||||
if ($daUser !== '') {
|
||||
$path = str_replace(['DA_USER', 'da_user'], $daUser, $path);
|
||||
}
|
||||
|
||||
return rtrim($path, '/');
|
||||
}
|
||||
|
||||
public function userBaseBackupDir(string $daUser = ''): string
|
||||
{
|
||||
$path = $this->getString('USER_BASE_BACKUP_DIR', '/home/DA_USER/mysql_backup');
|
||||
if ($path === '') {
|
||||
$path = '/home/DA_USER/mysql_backup';
|
||||
}
|
||||
|
||||
if ($daUser !== '') {
|
||||
$path = str_replace(['DA_USER', 'da_user'], $daUser, $path);
|
||||
}
|
||||
|
||||
return rtrim($path, '/');
|
||||
}
|
||||
|
||||
public function userBackupDateFormat(): string
|
||||
{
|
||||
$format = $this->getString('USER_BACKUP_DATE_FORMAT', 'd.m.Y-H.i');
|
||||
return $format !== '' ? $format : 'd.m.Y-H.i';
|
||||
}
|
||||
|
||||
public function loadOrCreateSecret(string $path): string
|
||||
{
|
||||
if (is_readable($path)) {
|
||||
$value = trim((string)file_get_contents($path));
|
||||
if ($value !== '') {
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
|
||||
$secret = bin2hex(random_bytes(32));
|
||||
$dir = dirname($path);
|
||||
if (!is_dir($dir)) {
|
||||
@mkdir($dir, 0700, true);
|
||||
}
|
||||
|
||||
if (@file_put_contents($path, $secret) !== false) {
|
||||
@chmod($path, 0600);
|
||||
return $secret;
|
||||
}
|
||||
|
||||
return hash('sha256', __FILE__ . '|' . php_uname('n') . '|' . $path . '|alt-mysql');
|
||||
}
|
||||
|
||||
public static function toBool(string $value, bool $default = false): bool
|
||||
{
|
||||
$v = strtolower(trim($value));
|
||||
if ($v === '') {
|
||||
return $default;
|
||||
}
|
||||
|
||||
if (in_array($v, ['1', 'true', 'yes', 'y', 'on', 'checked'], true)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (in_array($v, ['0', 'false', 'no', 'n', 'off', 'unchecked'], true)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $default;
|
||||
}
|
||||
|
||||
private function isPhpMyAdminInstalled(): bool
|
||||
{
|
||||
$dir = $this->phpMyAdminInstallDir();
|
||||
return is_dir($dir) && is_readable($dir . '/index.php') && is_readable($dir . '/config.inc.php');
|
||||
}
|
||||
|
||||
private static function parseShValue(string $value): string
|
||||
{
|
||||
$value = trim($value);
|
||||
if ($value === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
if ($value[0] === '\'' && substr($value, -1) === '\'') {
|
||||
return substr($value, 1, -1);
|
||||
}
|
||||
|
||||
if ($value[0] === '"' && substr($value, -1) === '"') {
|
||||
return stripcslashes(substr($value, 1, -1));
|
||||
}
|
||||
|
||||
$value = preg_replace('/\s+#.*$/', '', $value);
|
||||
return trim((string)$value);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user