many updates

This commit is contained in:
Paul Spenke
2023-07-10 21:27:43 +08:00
parent 249f6b06b5
commit cd9dc85420
29 changed files with 3164 additions and 962 deletions
+27 -23
View File
@@ -4,9 +4,9 @@ namespace Plugi\Core;
use Exception;
use PDO;
use PDOException;
use Plugi\Extensions;
use Plugi\Repositories\SettingRepository;
use Plugi\Setting;
/**
* Class DB
@@ -20,22 +20,21 @@ class DB
/**
* @var PDO $pdo
*/
protected $pdo;
protected PDO $pdo;
/**
* DB constructor.
*
* @param array $config
*/
public function __construct(array $config)
public function __construct()
{
$this->pdo = new PDO(
$config['driver'] . ':host=' . $config['host'] . ';dbname=' . $config['database'] . ";options='--client_encoding=" . $config['charset'] . "'",
$config['username'],
$config['password'],
$_ENV['DATABASE_DRIVER'] . ':host=' . $_ENV['DATABASE_HOST'] . ';dbname=' . $_ENV['DATABASE_DATABASE'] . ";options='--client_encoding=" . $_ENV['DATABASE_CHARSET'] . "'",
$_ENV['DATABASE_USERNAME'],
$_ENV['DATABASE_PASSWORD'],
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
$this->pdo->exec("set names " . $config['charset']);
$this->pdo->exec("set names " . $_ENV['DATABASE_CHARSET']);
}
/**
@@ -43,7 +42,7 @@ class DB
*
* @return string
*/
public function lastInsertId()
public function lastInsertId(): string
{
return $this->pdo->lastInsertId();
}
@@ -55,7 +54,7 @@ class DB
* @param string $table
* @return array
*/
public function all(string $table, $columns = '*')
public function all(string $table, array|string $columns = '*'): array
{
try {
if (is_array($columns)) {
@@ -63,13 +62,13 @@ class DB
$column = preg_replace('/[^a-zA-Z_]*/', '', $column);
}
$columns = implode(',', $columns);
$stmt = $this->pdo->prepare("SELECT {$columns} FROM {$table}");
$stmt = $this->pdo->prepare("SELECT $columns FROM $table");
} else {
$stmt = $this->pdo->prepare("SELECT * FROM {$table}");
$stmt = $this->pdo->prepare("SELECT * FROM $table");
}
$stmt->execute();
return $stmt->fetchAll();
} catch (\PDOException $e) {
} catch (PDOException $e) {
$_SESSION["phpb_flash"] = [
'message-type' => 'error',
'message' => phpb_trans('website-manager.check-database')
@@ -119,20 +118,23 @@ class DB
return $stmt->execute($parameters);
}
function tableExists($table) {
function tableExists(string $table): bool
{
$tableName = $_ENV['DATABASE_PREFIX'] . phpb_remove_non_alpha_numeric($table);
try {
$this->pdo->query("SELECT 1 FROM {$table} LIMIT 1");
$this->pdo->query("SELECT 1 FROM {$tableName} LIMIT 1");
return true;
} catch (Exception $e) {
return false;
}
}
public function columnExists(string $table, string $column)
public function columnExists(string $table, string $column): bool
{
$tableName = $_ENV['DATABASE_PREFIX'] . phpb_remove_non_alpha_numeric($table);
// check if table with the name $table exists. if not, execute $query.'
try {
$rs = $this->pdo->query("SELECT * FROM {$table} LIMIT 0");
$rs = $this->pdo->query("SELECT * FROM {$tableName} LIMIT 0");
for ($i = 0; $i < $rs->columnCount(); $i++) {
$col = $rs->getColumnMeta($i);
$columns[] = $col['name'];
@@ -146,11 +148,12 @@ class DB
public function uniqueKeyExists(string $table, string $key)
{
$tableName = $_ENV['DATABASE_PREFIX'] . phpb_remove_non_alpha_numeric($table);
// check if table with the name $table exists. if not, execute $query.'
try {
$keys = $this->select(
"SELECT CONSTRAINT_NAME FROM information_schema.TABLE_CONSTRAINTS WHERE CONSTRAINT_NAME = ? AND TABLE_SCHEMA = 'plugi' AND TABLE_NAME = ? AND CONSTRAINT_TYPE = 'UNIQUE'",
[$key, $table]
[$key, $tableName]
);
if (count($keys) === 1) return true;
return false;
@@ -202,16 +205,17 @@ class DB
public function resolveDiffDB() {
$diff = $this->diffDB();
foreach ($diff as $table => $tableDiff) {
$tableName = $_ENV['DATABASE_PREFIX'] . phpb_remove_non_alpha_numeric($table);
if($tableDiff === false){
$this->query("CREATE TABLE {$table} (`id` int NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3");
$this->query("ALTER TABLE {$table} ADD PRIMARY KEY (`id`)");
$this->query("ALTER TABLE {$table} MODIFY `id` int NOT NULL AUTO_INCREMENT");
$this->query("CREATE TABLE {$tableName} (`id` int NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3");
$this->query("ALTER TABLE {$tableName} ADD PRIMARY KEY (`id`)");
$this->query("ALTER TABLE {$tableName} MODIFY `id` int NOT NULL AUTO_INCREMENT");
} elseif (is_array($tableDiff)) {
foreach ($tableDiff['columns'] as $column => $columnDefinition) {
$this->query("ALTER TABLE {$table} ADD {$column} {$columnDefinition}");
$this->query("ALTER TABLE {$tableName} ADD {$column} {$columnDefinition}");
}
foreach ($tableDiff['uniqueKeys'] as $key => $keyDefinition) {
$this->query("ALTER TABLE {$table} ADD UNIQUE KEY {$key} ($keyDefinition)");
$this->query("ALTER TABLE {$tableName} ADD UNIQUE KEY {$key} ($keyDefinition)");
}
}
}
+47
View File
@@ -0,0 +1,47 @@
<?php
namespace Plugi\Core;
class EnvLoader
{
/**
* The directory where the .env file can be located.
*
* @var string
*/
protected string $path;
public function __construct(string $path = '.env')
{
if(!file_exists($path)) {
throw new \InvalidArgumentException(sprintf('%s does not exist', $path));
}
$this->path = $path;
}
public function load() :void
{
if (!is_readable($this->path)) {
throw new \RuntimeException(sprintf('%s file is not readable', $this->path));
}
$lines = file($this->path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
if (strpos(trim($line), '#') === 0) {
continue;
}
list($name, $value) = explode('=', $line, 2);
$name = trim($name);
$value = trim($value);
if (!array_key_exists($name, $_SERVER) && !array_key_exists($name, $_ENV)) {
putenv(sprintf('%s=%s', $name, $value));
$_ENV[$name] = $value;
$_SERVER[$name] = $value;
}
}
}
}
+37 -17
View File
@@ -110,10 +110,14 @@ if (! function_exists('phpb_config')) {
* @param string $key
* @return mixed
*/
function phpb_config(string $key): mixed
function phpb_config(?string $key = null): mixed
{
global $phpb_config;
if (!isset($key)) {
return $phpb_config;
}
// if no dot notation is used, return first dimension value or empty string
if (!str_contains($key, '.')) {
return $phpb_config[$key] ?? '';
@@ -203,7 +207,7 @@ if (! function_exists('phpb_full_url')) {
return $urlRelativeToBaseUrl;
}
$baseUrl = phpb_config('general.base_url');
$baseUrl = $_ENV['BASE_URL'];
return rtrim($baseUrl, '/') . $urlRelativeToBaseUrl;
}
}
@@ -259,7 +263,7 @@ if (! function_exists('phpb_current_relative_url')) {
*/
function phpb_current_relative_url(): string
{
$baseUrl = phpb_config('general.base_url');
$baseUrl = $_ENV['BASE_URL'];
$baseUrl = rtrim($baseUrl, '/'. DIRECTORY_SEPARATOR);
$currentFullUrl = phpb_current_full_url();
@@ -523,6 +527,16 @@ if (! function_exists('phpb_slug')) {
}
}
if (! function_exists('phpb_remove_non_alpha_numeric')) {
/**
* Create a slug (safe URL or path) of the given string.
*/
function phpb_remove_non_alpha_numeric(string $string): array|string|null
{
return preg_replace('/\W*/', '', $string);
}
}
if (! function_exists('phpb_autoload')) {
/**
* Autoload classes from the Plugi package.
@@ -580,26 +594,32 @@ if (! function_exists('phpb_registered_assets')) {
}
}
if (! function_exists('array_merge_recursive_ex')) {
if (! function_exists('phpb_array_merge_deep_array')) {
/**
* Deep merging
*/
function array_merge_recursive_ex(array $array1, array $array2): array
{
$merged = $array1;
function phpb_array_merge_deep_array($arrays) {
$result = array();
foreach ($arrays as $array) {
foreach ($array as $key => $value) {
foreach ($array2 as $key => $value) {
if (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) {
$merged[$key] = array_merge_recursive_ex($merged[$key], $value);
} else if (is_numeric($key)) {
if (!in_array($value, $merged)) {
$merged[] = $value;
// Renumber integer keys as array_merge_recursive() does. Note that PHP
// automatically converts array keys that are integer strings (e.g., '1')
// to integers.
if (is_integer($key)) {
$result[] = $value;
}
elseif (isset($result[$key]) && is_array($result[$key]) && is_array($value)) {
$result[$key] = phpb_array_merge_deep_array(array(
$result[$key],
$value,
));
}
else {
$result[$key] = $value;
}
} else {
$merged[$key] = $value;
}
}
return $merged;
return $result;
}
}
@@ -1,5 +1,8 @@
import Alpine from "alpinejs"
import './sass/app.scss'
import './js/app.js'
import slugify from "slugify";
window.slugify = slugify
Alpine.start()
@@ -55,16 +55,16 @@ $pageTranslations = $page ? $page->getTranslations() : [];
$firstLang = true;
foreach (phpb_active_languages() as $languageCode => $languageTranslation):
?>
<details class="collapse collapse-plus bg-base-200 mt-6" <?= phpb_e($firstLang ? 'open' : '') ?>>
<details class="collapse collapse-plus bg-white mt-6" <?= phpb_e($firstLang ? 'open' : '') ?>>
<summary class="collapse-title text-xl font-medium"><?= phpb_trans('languages.' . $languageCode) ?></summary>
<div class="collapse-content">
<div class="">
<div x-data="{route: '<?= phpb_e($pageTranslations[$languageCode]['route'] ?? '') ?>', empty: true, locale: '<?= $firstLang ? '' : '/'.phpb_e($languageCode) ?>'}" x-init="empty = route.length === 0">
<div class="form-control w-full mb-2">
<label class="label" for="<?= phpb_e($languageCode) ?>-page-title">
<span class="label-text"><?= phpb_trans('website-manager.page-title') ?></span>
<span class="label-text-alt"><?= phpb_trans('website-manager.required') ?></span>
</label>
<input type="text" class="input input-bordered w-full" id="<?= phpb_e($languageCode) ?>-page-title" name="title[<?= phpb_e($languageCode) ?>]" value="<?= phpb_e($pageTranslations[$languageCode]['title'] ?? '') ?>" required />
<input type="text" class="input input-bordered w-full" id="<?= phpb_e($languageCode) ?>-page-title" name="title[<?= phpb_e($languageCode) ?>]" value="<?= phpb_e($pageTranslations[$languageCode]['title'] ?? '') ?>" @input="if(empty){route=`${locale}/${slugify($event.target.value)}`}" required />
</div>
<div class="form-control w-full mb-2">
@@ -86,7 +86,13 @@ $pageTranslations = $page ? $page->getTranslations() : [];
<span class="label-text"><?= phpb_trans('website-manager.route') ?></span>
<span class="label-text-alt"><?= phpb_trans('website-manager.required') ?></span>
</label>
<input type="text" class="input input-bordered w-full" id="<?= phpb_e($languageCode) ?>-page-route" name="route[<?= phpb_e($languageCode) ?>]" value="<?= phpb_e($pageTranslations[$languageCode]['route'] ?? '') ?>" required />
<div class="join" x-data="{disabled: true}">
<input type="text" class="input input-bordered join-item w-full" id="<?= phpb_e($languageCode) ?>-page-route" name="route[<?= phpb_e($languageCode) ?>]" :value="route" :disabled="disabled" required />
<button class="btn join-item btn-outline text-2xl" @click.stop.prevent="disabled=!disabled" type="button" >
<i class="ph ph-pencil" x-show="disabled"></i>
<i class="ph ph-pencil-slash" x-show="!disabled"></i>
</button>
</div>
</div>
</div>
@@ -82,6 +82,31 @@ use Plugi\Setting;
</ul>
</td>
</tr>
<tr>
<th class="align-top">Config</th>
<td x-data="{show: false}">
<div>
<button @click="show = !show" class="btn btn-xs btn-outline" x-text="show ? 'hide' : 'show'"></button>
</div>
<pre class="mt-4" x-show="show"><?php
print_r(phpb_config());
?></pre>
</td>
</tr>
<tr>
<th class="align-top">Environment</th>
<td x-data="{show: false}">
<div class="">
<button @click="show = !show" class="btn btn-xs btn-outline" x-text="show ? 'hide' : 'show'"></button>
</div>
<pre class="mt-4" x-show="show"><?php
print_r([
'STAGE'=>$_ENV['STAGE'],
'BASE_URL'=>$_ENV['BASE_URL']
]);
?></pre>
</td>
</tr>
</tbody>
</table>
</div>
+5 -6
View File
@@ -45,7 +45,7 @@ class Plugi
/**
* Plugi constructor.
*
* @param array|null $config configuration in the format defined in config/config.example.php
* @param array|null $config configuration in the format defined in config
*/
public function __construct($config = [])
{
@@ -72,7 +72,7 @@ class Plugi
// create database connection, if enabled
if (phpb_config('storage.use_database')) {
$this->setDatabaseConnection(phpb_config('storage.database'));
$this->setDatabaseConnection();
$this->checkDatabaseDefinition();
$this->hydrateConfig();
}
@@ -132,7 +132,7 @@ class Plugi
$extLanguageFile = $extConfig['dir'] . '/lang/en.php';
}
if (file_exists($extLanguageFile)) {
$phpb_translations = array_merge_recursive_ex($phpb_translations, require $extLanguageFile);
$phpb_translations = phpb_array_merge_deep_array([$phpb_translations, require $extLanguageFile]);
}
}
@@ -194,13 +194,12 @@ class Plugi
/**
* Set the Plugi database connection using the given array.
*
* @param array $config
*/
public function setDatabaseConnection(array $config)
public function setDatabaseConnection()
{
global $phpb_db;
global $phpb_config;
$phpb_db = new DB($config);
$phpb_db = new DB();
$theme = Setting::get('selected_theme');
if ($theme) $phpb_config['theme']['active_theme'] = $theme;
$language = Setting::get('admin_language');
@@ -42,7 +42,7 @@ class BaseRepository
$this->db = $phpb_db;
// apply the configured prefix to the table set in the superclass and remove non-alphanumeric characters
$this->table = phpb_config('storage.database.prefix') . $this->removeNonAlphaNumeric($this->table);
$this->table = $_ENV['DATABASE_PREFIX'] . $this->removeNonAlphaNumeric($this->table);
}
/**
@@ -48,9 +48,11 @@ class MenuRepository extends BaseRepository implements MenuRepositoryContract
$langMenuPage = [
'id' => $id,
'title' => phpb_trans('languages.'.$pageTranslation->locale),
'lang' => $pageTranslation->locale,
'route' => $pageTranslation->route
'locale' => $pageTranslation->locale,
'route' => $pageTranslation->route,
'selected' => false,
];
if (phpb_current_language() === $pageTranslation->locale) $langMenuPage['selected'] = true;
$menu[] = $langMenuPage;
}
return $menu;