Compare commits

...

54 Commits

Author SHA1 Message Date
84b366908c fix add theme 2025-01-24 14:43:08 +03:00
4cbcc594b6 fix add theme 2025-01-24 14:36:22 +03:00
530908568c kernel update to v0.1.5 2025-01-24 11:33:08 +03:00
4d7a2fbdec some fix 2025-01-23 16:55:02 +03:00
29e0ff327f get all dependencies 2025-01-23 13:33:41 +03:00
0cc1e0773d rout 2025-01-21 17:10:19 +03:00
67b3f62728 merge 2025-01-21 17:10:03 +03:00
74b8f2e719 kernel to v0.1.4 update 2025-01-21 16:56:10 +03:00
2664f7fd78 kernel v0.1.4 2025-01-21 16:51:29 +03:00
dc84874d16 resources update 2025-01-21 14:59:39 +03:00
b733a49738 some fix 2025-01-19 21:22:27 +03:00
a943b960ad themes add and some fix 2025-01-19 20:50:25 +03:00
219ca30608 admin theme to ms 2024-12-23 14:16:00 +03:00
483fe35561 button fix, kernel update 2024-12-19 12:55:33 +03:00
e75d21bd1b button fix, kernel update 2024-12-19 12:53:55 +03:00
4ff9fa9ad3 kernel update 2024-12-18 12:46:57 +03:00
653e0bc983 Merge branch 'master' of https://git.itguild.info/ItGuild/igfs 2024-12-16 14:38:13 +03:00
9fa3daf767 test delete 2024-12-16 14:37:11 +03:00
2ae128ff79 merge 2024-12-16 14:35:12 +03:00
f5ad07c04a kernel update 2024-12-16 14:26:13 +03:00
49399e456a update full 2024-12-04 13:11:12 +03:00
fd9439c9e2 kernel update 2024-11-20 12:56:15 +03:00
589cf81e49 Merge branch 'master' of https://git.itguild.info/ItGuild/igfs 2024-11-19 16:35:40 +03:00
1ea3eca919 test 2 CI/CD 2024-11-19 16:33:30 +03:00
4dbfe12376 Merge branch 'master' of https://git.itguild.info/ItGuild/igfs 2024-11-19 16:28:37 +03:00
4077405296 some fix 2024-11-19 16:28:22 +03:00
0055370c7e test CI/CD 2024-11-19 16:10:43 +03:00
47f29f16a5 merge 2024-11-19 13:43:13 +03:00
16cec04f6f kernel update 2024-11-19 12:31:48 +03:00
2af9ea876d kernel update 2024-11-18 16:04:57 +03:00
10605e17e7 install module to client 2024-11-14 01:56:07 +03:00
d84f23c756 fix module shop service 2024-11-08 15:33:27 +03:00
41671c2cd1 Merge branch 'master' of https://git.itguild.info/ItGuild/igfs 2024-11-08 14:58:57 +03:00
bff1cb798f action install to ms 2024-11-08 14:48:52 +03:00
c6a92f19c8 Merge branch 'master' of https://git.itguild.info/ItGuild/igfs 2024-11-05 13:32:35 +03:00
b9e1a5382b some fix 2024-11-05 13:24:04 +03:00
e4c3655d92 kernel update 2024-10-28 11:03:30 +03:00
f7838ea665 api ms group by slug, views, ins 2024-10-25 15:47:11 +03:00
45d51c7119 kernel update 2024-10-24 11:53:17 +03:00
3846da3f94 some fix 2024-10-23 17:06:10 +03:00
2470c5dba8 new kernel, ms bearer 2024-10-23 16:16:47 +03:00
5285acae12 some fix 2024-10-17 11:35:56 +03:00
9af44ca95f module shop, flash message 2024-10-16 17:54:33 +03:00
209b1e3f29 module shop crud 2024-10-16 16:06:25 +03:00
b7ac923261 first 2024-10-15 17:32:33 +03:00
c3c377a4e2 some fix 2024-10-15 16:15:46 +03:00
d3d5e3a8e5 kernel pack, update and some fix 2024-10-14 15:52:52 +03:00
7cf3708e4d session errors 2024-10-11 17:02:35 +03:00
5b9386f970 module set and unset, dependencies 2024-10-11 15:44:15 +03:00
d9c4cecd48 module fix 2024-10-10 22:40:09 +03:00
94496910d7 merge 2024-10-10 16:51:19 +03:00
fb96676bb2 gitignore tmp 2024-10-10 16:50:10 +03:00
0a3b523e00 remove tmp from git 2024-10-10 16:49:16 +03:00
2711c0258d dependences 2024-10-10 16:45:53 +03:00
904 changed files with 30690 additions and 27873 deletions

View File

@ -1,11 +1,23 @@
APP_NAME="It Guild Micro Framework"
DB_HOST=localhost
DB_USER=root
DB_USER={db_user}
DB_DRIVER=mysql
DB_PASSWORD=123edsaqw
DB_NAME=mfw
DB_CHARSET=utf8
DB_COLLATION=utf8_unicode_ci
DB_PASSWORD={db_password}
DB_NAME={db_name}
DB_CHARSET=utf8mb4
DB_COLLATION=utf8mb4_unicode_ci
DB_PREFIX=''
VIEWS_PATH=/views
VIEWS_CACHE_PATH=/views_cache
VIEWS_CACHE_PATH=/views_cache
MAIL_SMTP_HOST=smtp.mail.ru
MAIL_SMTP_PORT=587
MAIL_SMTP_USERNAME=username@mail.ru
MAIL_SMTP_PASSWORD=somepassword
MODULE_SHOP_URL='http://igfs.loc'
MODULE_SHOP_TOKEN='your token'
SECRET_KEY=''

4
.gitignore vendored
View File

@ -2,4 +2,6 @@
vendor
.env
views_cache
resources/upload
resources/upload
resources/tmp
composer.lock

View File

@ -1,14 +1,13 @@
<?php
namespace app\modules\tag;
namespace app\modules\module_shop;
use kernel\Module;
use kernel\modules\menu\service\MenuService;
use kernel\services\MigrationService;
class TagModule extends Module
class ModuleShopModule extends Module
{
public MenuService $menuService;
public MigrationService $migrationService;
public function __construct()
@ -22,17 +21,22 @@ class TagModule extends Module
*/
public function init(): void
{
$this->migrationService->runAtPath("{KERNEL_APP_MODULES}/tag/migrations");
$this->migrationService->runAtPath("{APP}/modules/module_shop/migrations");
$this->menuService->createItem([
"label" => "Тэги",
"url" => "/admin/tag",
"slug" => "tag",
"label" => "Магазин модулей",
"url" => "/admin/module_shop",
"slug" => "module_shop",
]);
}
/**
* @throws \Exception
*/
public function deactivate(): void
{
$this->menuService->removeItemBySlug("tag");
$this->menuService->removeItemBySlug("module_shop");
$this->migrationService->rollbackAtPath("{APP}/modules/module_shop/migrations");
}
}

View File

@ -0,0 +1,84 @@
<?php
namespace app\modules\module_shop\controllers;
use app\modules\module_shop\models\forms\CreateAdminThemeShopForm;
use app\modules\module_shop\services\ModuleShopService;
use JetBrains\PhpStorm\NoReturn;
use kernel\AdminController;
use kernel\FileUpload;
use kernel\Flash;
use kernel\helpers\Debug;
use kernel\helpers\Files;
use ZipArchive;
class AdminThemeShopController extends AdminController
{
protected ModuleShopService $moduleShopService;
protected Files $files;
protected function init(): void
{
parent::init();
$this->cgView->viewPath = APP_DIR . "/modules/module_shop/views/admin_theme/";
$this->moduleShopService = new ModuleShopService();
$this->files = new Files();
}
public function actionCreate(): void
{
$this->cgView->render("form.php");
}
/**
* @throws \Exception
*/
#[NoReturn] public function actionAdd(): void
{
$adminThemeShopForm = new CreateAdminThemeShopForm();
$adminThemeShopForm->load($_REQUEST);
if (isset($_FILES['path_to_archive']) && $_FILES['path_to_archive']['error'] === UPLOAD_ERR_OK) {
$file = new FileUpload($_FILES['path_to_archive'], ['zip', 'rar', 'igt']);
$file->upload();
$adminThemeShopForm->setItem('path_to_archive', $file->getUploadFile());
}
$tmpThemeDir = md5(time());
$zip = new ZipArchive;
$res = $zip->open(ROOT_DIR . $adminThemeShopForm->getItem('path_to_archive'));
if ($res === TRUE) {
if (!is_dir(RESOURCES_DIR . '/tmp/ms/')) {
$oldMask = umask(0);
mkdir(RESOURCES_DIR . '/tmp/ms/', 0775, true);
umask($oldMask);
}
$tmpModuleShopDirFull = RESOURCES_DIR . '/tmp/ms/' . $tmpThemeDir . "/";
$zip->extractTo($tmpModuleShopDirFull);
$zip->close();
if (file_exists($tmpModuleShopDirFull . "meta/manifest.json")){
$themeInfo = $this->moduleShopService->getModuleInfo($tmpModuleShopDirFull . "meta");
$adminThemeShopForm->load($themeInfo);
}
else {
throw new \Exception("Manifest.json file not found");
}
$this->files->recursiveRemoveDir($tmpModuleShopDirFull);
}
else {
throw new \Exception("zip not found");
}
if ($adminThemeShopForm->validate()) {
$theme = $this->moduleShopService->create($adminThemeShopForm);
if ($theme) {
Flash::setMessage("success", "Тема админ-панели добавлена.");
$this->redirect("/admin/module_shop/view/" . $theme->id);
}
}
Flash::setMessage("error", "Ошибка добавления темы админ-панели: <br>" . $adminThemeShopForm->getErrorsStr());
$this->redirect("/admin/module_shop/admin_theme/create");
}
}

View File

@ -0,0 +1,82 @@
<?php
namespace app\modules\module_shop\controllers;
use app\modules\module_shop\models\forms\CreateKernelShopForm;
use app\modules\module_shop\services\ModuleShopService;
use JetBrains\PhpStorm\NoReturn;
use kernel\AdminController;
use kernel\FileUpload;
use kernel\Flash;
use kernel\helpers\Debug;
use kernel\helpers\Files;
use ZipArchive;
class KernelShopController extends AdminController
{
protected ModuleShopService $moduleShopService;
protected Files $files;
protected function init(): void
{
parent::init();
$this->cgView->viewPath = APP_DIR . "/modules/module_shop/views/kernel/";
$this->moduleShopService = new ModuleShopService();
$this->files = new Files();
}
public function actionCreate(): void
{
$this->cgView->render("form.php");
}
/**
* @throws \Exception
*/
#[NoReturn] public function actionAdd(): void
{
$kernelShopForm = new CreateKernelShopForm();
$kernelShopForm->load($_REQUEST);
if (isset($_FILES['path_to_archive']) && $_FILES['path_to_archive']['error'] === UPLOAD_ERR_OK) {
$file = new FileUpload($_FILES['path_to_archive'], ['zip', 'rar', 'igk']);
$file->upload();
$kernelShopForm->setItem('path_to_archive', $file->getUploadFile());
}
$tmpKernelDir = md5(time());
$zip = new ZipArchive;
$res = $zip->open(ROOT_DIR . $kernelShopForm->getItem('path_to_archive'));
if ($res === TRUE) {
if (!is_dir(RESOURCES_DIR . '/tmp/ms/')) {
mkdir(RESOURCES_DIR . '/tmp/ms/');
}
$tmpModuleShopDirFull = RESOURCES_DIR . '/tmp/ms/' . $tmpKernelDir . "/";
$zip->extractTo($tmpModuleShopDirFull);
$zip->close();
if (file_exists($tmpModuleShopDirFull . "kernel/manifest.json")){
$kernelInfo = $this->moduleShopService->getModuleInfo($tmpModuleShopDirFull . "kernel");
$kernelShopForm->load($kernelInfo);
}
else {
throw new \Exception("Manifest.json file not found");
}
$this->files->recursiveRemoveDir($tmpModuleShopDirFull);
}
else {
throw new \Exception("zip not found");
}
if ($kernelShopForm->validate()) {
$kernel = $this->moduleShopService->create($kernelShopForm);
if ($kernel) {
Flash::setMessage("success", "Ядро добавлено.");
$this->redirect("/admin/module_shop/view/" . $kernel->id);
}
}
Flash::setMessage("error", "Ошибка добавления ядра: <br>" . $kernelShopForm->getErrorsStr());
$this->redirect("/admin/module_shop/kernel/create");
}
}

View File

@ -0,0 +1,27 @@
<?php
namespace app\modules\module_shop\controllers;
use app\modules\module_shop\models\ModuleShop;
use JetBrains\PhpStorm\NoReturn;
use kernel\helpers\Debug;
use kernel\Request;
use kernel\RestController;
class KernelShopRestController extends RestController
{
public function __construct()
{
$this->model = new ModuleShop();
}
#[NoReturn] public function actionUpdate($id): void
{
$model = $this->model->where("id", $id)->first();
$model->installations++;
$model->save();
$this->renderApi($model->toArray());
}
}

View File

@ -0,0 +1,124 @@
<?php
namespace app\modules\module_shop\controllers;
use app\modules\module_shop\models\forms\CreateModuleShopForm;
use app\modules\module_shop\models\ModuleShop;
use app\modules\module_shop\services\ModuleShopService;
use JetBrains\PhpStorm\NoReturn;
use kernel\AdminController;
use kernel\FileUpload;
use kernel\Flash;
use kernel\helpers\Debug;
use kernel\helpers\Files;
use ZipArchive;
class ModuleShopController extends AdminController
{
protected ModuleShopService $moduleShopService;
protected Files $files;
protected function init(): void
{
parent::init();
$this->cgView->viewPath = APP_DIR . "/modules/module_shop/views/";
$this->moduleShopService = new ModuleShopService();
$this->files = new Files();
}
public function actionCreate(): void
{
$this->cgView->render("form.php");
}
/**
* @throws \Exception
*/
#[NoReturn] public function actionAdd(): void
{
$moduleShopForm = new CreateModuleShopForm();
$moduleShopForm->load($_REQUEST);
if (isset($_FILES['path_to_archive']) && $_FILES['path_to_archive']['error'] === UPLOAD_ERR_OK) {
$file = new FileUpload($_FILES['path_to_archive'], ['zip', 'rar', 'igm']);
$file->upload();
$moduleShopForm->setItem('path_to_archive', $file->getUploadFile());
}
$tmpModuleDir = md5(time());
$zip = new ZipArchive;
$res = $zip->open(ROOT_DIR . $moduleShopForm->getItem('path_to_archive'));
if ($res === TRUE) {
if (!is_dir(RESOURCES_DIR . '/tmp/ms/')) {
mkdir(RESOURCES_DIR . '/tmp/ms/');
}
$tmpModuleShopDirFull = RESOURCES_DIR . '/tmp/ms/' . $tmpModuleDir . "/";
$zip->extractTo($tmpModuleShopDirFull);
$zip->close();
if (file_exists($tmpModuleShopDirFull . "app/manifest.json")){
$moduleInfo = $this->moduleShopService->getModuleInfo($tmpModuleShopDirFull . "app");
$moduleShopForm->load($moduleInfo);
}
else {
throw new \Exception("Manifest.json file not found");
}
$this->files->recursiveRemoveDir($tmpModuleShopDirFull);
}
else {
throw new \Exception("zip not found");
}
if ($moduleShopForm->validate()) {
$module = $this->moduleShopService->create($moduleShopForm);
if ($module) {
Flash::setMessage("success", "Модуль " . $moduleShopForm->getItem("name") . " добавлен.");
$this->redirect("/admin/module_shop/view/" . $module->id);
}
}
Flash::setMessage("error", "Ошибка добавления модуля: <br>" . $moduleShopForm->getErrorsStr());
$this->redirect("/admin/module_shop/module/create");
}
public function actionIndex(int $page_number = 1): void
{
$this->cgView->render("index.php", ['page_number' => $page_number]);
}
public function actionView(int $id): void
{
$module = ModuleShop::find($id);
if (!$module) {
throw new \Exception("The module not found");
}
$this->cgView->render("view.php", ['module' => $module]);
}
public function actionDelete(int $id): void
{
$module = ModuleShop::find($id);
if (!$module) {
throw new \Exception("The module not found");
}
$name = $module->name;
$dir = $module->path_to_archive;
$this->files->recursiveRemoveDir(ROOT_DIR . dirname($dir, 2));
$module->delete();
Flash::setMessage("success", "Модуль " . $name . " удален.");
$this->redirect("/admin/module_shop");
}
public function actionPack(int $id): void
{
$module = ModuleShop::find($id);
if (!$module) {
throw new \Exception("The module not found");
}
$this->moduleShopService->packModule($module);
}
}

View File

@ -0,0 +1,114 @@
<?php
namespace app\modules\module_shop\controllers;
use app\modules\module_shop\models\ModuleShop;
use app\modules\module_shop\services\ModuleShopService;
use JetBrains\PhpStorm\NoReturn;
use kernel\helpers\Debug;
use kernel\Request;
use kernel\RestController;
class ModuleShopRestController extends RestController
{
public function __construct()
{
$this->model = new ModuleShop();
}
#[NoReturn] public function actionIndex(): void
{
$request = new Request();
$page = $request->get('page') ?? 1;
$perPage = $request->get('per_page') ?? 10;
$query = $this->model->query();
$query->orderBy('created_at', 'DESC');
if ($page > 1) {
$query->skip(($page - 1) * $perPage)->take($perPage);
} else {
$query->take($perPage);
}
$expand = $this->expand();
$expandParams = explode( ",", $request->get('expand') ?? "");
$finalExpand = array_intersect($expandParams, $expand);
if ($finalExpand) {
$res = $query->get()->load($finalExpand)->toArray();
} else {
$res = $query->get()->toArray();
}
$this->renderApi($res);
}
#[NoReturn] public function actionIndexGroupBySlug(): void
{
$request = new Request();
$page = $request->get('page') ?? 1;
$perPage = $request->get('per_page') ?? 10;
$query = $this->model->query();
$query->select('ms1.*')
->from('module_shop as ms1')
->leftJoin('module_shop as ms2', function ($join) {
$join->on('ms1.slug', '=', 'ms2.slug')
->on('ms1.id', '<', 'ms2.id');
})
->where('ms2.slug', '=', null);
if ($page > 1) {
$query->skip(($page - 1) * $perPage)->take($perPage);
} else {
$query->take($perPage);
}
$expand = $this->expand();
$expandParams = explode( ",", $request->get('expand') ?? "");
$finalExpand = array_intersect($expandParams, $expand);
if ($finalExpand) {
$res = $query->get()->load($finalExpand)->toArray();
} else {
$res = $query->get()->toArray();
}
$this->renderApi($res);
}
#[NoReturn] public function actionView($id): void
{
$expand = $this->expand();
$request = new Request();
$expandParams = explode( ",", $request->get('expand') ?? "");
$model = $this->model->where("id", $id)->first();
$model->views++;
$finalExpand = array_intersect($expandParams, $expand);
if ($finalExpand){
$model->load($finalExpand);
}
$res = [];
if ($model){
$res = $model->toArray();
}
$model->save();
$this->renderApi($res);
}
#[NoReturn] public function actionInstall($id): void
{
$model = $this->model->where("id", $id)->first();
$model->installations++;
$model->save();
$this->renderApi($model->toArray());
}
public function actionGetDependenciesBySlug(string $slug)
{
$this->renderApi(ModuleShopService::getAllDependencies($slug));
}
}

View File

@ -0,0 +1,85 @@
<?php
namespace app\modules\module_shop\controllers;
use app\modules\module_shop\models\forms\CreateAdminThemeShopForm;
use app\modules\module_shop\models\forms\CreateThemeShopForm;
use app\modules\module_shop\services\ModuleShopService;
use JetBrains\PhpStorm\NoReturn;
use kernel\AdminController;
use kernel\FileUpload;
use kernel\Flash;
use kernel\helpers\Debug;
use kernel\helpers\Files;
use ZipArchive;
class ThemeShopController extends AdminController
{
protected ModuleShopService $moduleShopService;
protected Files $files;
protected function init(): void
{
parent::init();
$this->cgView->viewPath = APP_DIR . "/modules/module_shop/views/theme/";
$this->moduleShopService = new ModuleShopService();
$this->files = new Files();
}
public function actionCreate(): void
{
$this->cgView->render("form.php");
}
/**
* @throws \Exception
*/
#[NoReturn] public function actionAdd(): void
{
$themeShopForm = new CreateThemeShopForm();
$themeShopForm->load($_REQUEST);
if (isset($_FILES['path_to_archive']) && $_FILES['path_to_archive']['error'] === UPLOAD_ERR_OK) {
$file = new FileUpload($_FILES['path_to_archive'], ['zip', 'rar', 'igt']);
$file->upload();
$themeShopForm->setItem('path_to_archive', $file->getUploadFile());
}
$tmpThemeDir = md5(time());
$zip = new ZipArchive;
$res = $zip->open(ROOT_DIR . $themeShopForm->getItem('path_to_archive'));
if ($res === TRUE) {
if (!is_dir(RESOURCES_DIR . '/tmp/ms/')) {
$oldMask = umask(0);
mkdir(RESOURCES_DIR . '/tmp/ms/', 0775, true);
umask($oldMask);
}
$tmpModuleShopDirFull = RESOURCES_DIR . '/tmp/ms/' . $tmpThemeDir . "/";
$zip->extractTo($tmpModuleShopDirFull);
$zip->close();
if (file_exists($tmpModuleShopDirFull . "meta/app/manifest.json")){
$themeInfo = $this->moduleShopService->getModuleInfo($tmpModuleShopDirFull . "meta/app");
$themeShopForm->load($themeInfo);
}
else {
throw new \Exception("Manifest.json file not found");
}
$this->files->recursiveRemoveDir($tmpModuleShopDirFull);
}
else {
throw new \Exception("zip not found");
}
if ($themeShopForm->validate()) {
$theme = $this->moduleShopService->create($themeShopForm);
if ($theme) {
Flash::setMessage("success", "Тема сайта добавлена.");
$this->redirect("/admin/module_shop/view/" . $theme->id);
}
}
Flash::setMessage("error", "Ошибка добавления темы сайта: <br>" . $themeShopForm->getErrorsStr());
$this->redirect("/admin/module_shop/theme/create");
}
}

View File

@ -0,0 +1,11 @@
{
"name": "Магазин модулей",
"version": "0.1",
"author": "ITGuild",
"slug": "module_shop",
"description": "Магазин модулей для IGF",
"app_module_path": "{APP}/modules/{slug}",
"module_class": "app\\modules\\module_shop\\ModuleShopModule",
"routs": "routs/ms.php",
"dependence": "menu"
}

View File

@ -0,0 +1,37 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
/**
* Run the migrations.
*/
public function up(): void
{
\kernel\App::$db->schema->create('module_shop', function (Blueprint $table) {
$table->increments('id');
$table->string("name", 255)->nullable(false);
$table->string("slug", 255)->nullable(false);
$table->string("type", 255)->nullable(false);
$table->text("description")->nullable(false);
$table->string("version", 255)->nullable(false);
$table->string("author", 255)->nullable(false);
$table->string("dependence", 255)->nullable(true);
$table->text("path_to_archive")->nullable(false);
$table->integer("status")->default(1);
$table->integer("installations")->nullable(false)->default(0);
$table->integer("views")->nullable(false)->default(0);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
\kernel\App::$db->schema->dropIfExists('module_shop');
}
};

View File

@ -0,0 +1,57 @@
<?php
namespace app\modules\module_shop\models;
use Illuminate\Database\Eloquent\Model;
/**
* @property int $id
* @property string $name
* @property string $slug
* @property string $type
* @property string $version
* @property string $description
* @property string $author
* @property int $status
* @property int $installations
* @property int $views
* @property string $path_to_archive
* @property string $dependence
*/
class ModuleShop extends Model
{
const DISABLE_STATUS = 0;
const ACTIVE_STATUS = 1;
protected $table = "module_shop";
protected $fillable = ['name', 'slug', 'type', 'version', 'description', 'author', 'status', 'dependence', 'installations', 'views'];
public static function labels(): array
{
return [
'name' => 'Название',
'version' => 'Версия',
'description' => 'Описание',
'author' => 'Автор',
'status' => 'Статус',
'slug' => 'Slug',
'type' => 'Тип',
'dependence' => 'Зависимости',
'installations' => 'Установки',
'views' => 'Просмотры',
];
}
/**
* @return string[]
*/
public static function getStatus(): array
{
return [
self::DISABLE_STATUS => "Не активный",
self::ACTIVE_STATUS => "Активный",
];
}
}

View File

@ -0,0 +1,22 @@
<?php
namespace app\modules\module_shop\models\forms;
use kernel\FormModel;
class CreateAdminThemeShopForm extends FormModel
{
public function rules(): array
{
return [
'name' => 'required|min-str-len:3',
'version' => 'required',
'description' => '',
'author' => 'required',
'status' => 'required',
'slug' => 'required',
'type' => 'required',
'path_to_archive' => 'required',
];
}
}

View File

@ -0,0 +1,22 @@
<?php
namespace app\modules\module_shop\models\forms;
use kernel\FormModel;
class CreateKernelShopForm extends FormModel
{
public function rules(): array
{
return [
'name' => 'required',
'version' => 'required',
'author' => 'required',
'status' => 'required',
'slug' => 'required',
'type' => 'required',
'description' => '',
'path_to_archive' => 'required',
];
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace app\modules\module_shop\models\forms;
use kernel\FormModel;
class CreateModuleShopForm extends FormModel
{
public function rules(): array
{
return [
'name' => 'required|min-str-len:3',
'version' => 'required',
'description' => 'required|min-str-len:10',
'author' => 'required',
'status' => 'required',
'slug' => 'required',
'type' => 'required',
'path_to_archive' => 'required',
'dependence' => '',
];
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace app\modules\module_shop\models\forms;
use kernel\FormModel;
class CreateThemeShopForm extends FormModel
{
public function rules(): array
{
return [
'name' => 'required|min-str-len:3',
'version' => 'required',
'description' => '',
'author' => 'required',
'status' => 'required',
'slug' => 'required',
'type' => 'required',
'path_to_archive' => 'required',
'dependence' => ''
];
}
}

View File

@ -0,0 +1,49 @@
<?php
use kernel\App;
use kernel\CgRouteCollector;
App::$collector->filter('bearer', [\kernel\modules\secure\middlewares\BearerAuthMiddleware::class, "handler"]);
App::$collector->group(["prefix" => "admin"], function (CgRouteCollector $router) {
App::$collector->group(["prefix" => "module_shop"], function (CgRouteCollector $router) {
App::$collector->get('/', [\app\modules\module_shop\controllers\ModuleShopController::class, 'actionIndex']);
App::$collector->get('/page/{page_number}', [\app\modules\module_shop\controllers\ModuleShopController::class, 'actionIndex']);
App::$collector->get('/view/{id}', [\app\modules\module_shop\controllers\ModuleShopController::class, 'actionView']);
App::$collector->any('/update/{id}', [\app\modules\module_shop\controllers\ModuleShopController::class, 'actionUpdate']);
App::$collector->any("/edit/{id}", [\app\modules\module_shop\controllers\ModuleShopController::class, 'actionEdit']);
App::$collector->get('/delete/{id}', [\app\modules\module_shop\controllers\ModuleShopController::class, 'actionDelete']);
App::$collector->get('/pack/{id}', [\app\modules\module_shop\controllers\ModuleShopController::class, 'actionPack']);
App::$collector->group(["prefix" => "module"], function (CgRouteCollector $router) {
App::$collector->get('/create', [\app\modules\module_shop\controllers\ModuleShopController::class, 'actionCreate']);
App::$collector->post("/", [\app\modules\module_shop\controllers\ModuleShopController::class, 'actionAdd']);
});
App::$collector->group(["prefix" => "kernel"], function (CgRouteCollector $router) {
App::$collector->get('/create', [\app\modules\module_shop\controllers\KernelShopController::class, 'actionCreate']);
App::$collector->post("/", [\app\modules\module_shop\controllers\KernelShopController::class, 'actionAdd']);
});
App::$collector->group(["prefix" => "admin_theme"], function (CgRouteCollector $router) {
App::$collector->get('/create', [\app\modules\module_shop\controllers\AdminThemeShopController::class, 'actionCreate']);
App::$collector->post("/", [\app\modules\module_shop\controllers\AdminThemeShopController::class, 'actionAdd']);
});
App::$collector->group(["prefix" => "theme"], function (CgRouteCollector $router) {
App::$collector->get('/create', [\app\modules\module_shop\controllers\ThemeShopController::class, 'actionCreate']);
App::$collector->post("/", [\app\modules\module_shop\controllers\ThemeShopController::class, 'actionAdd']);
});
});
});
App::$collector->group(["prefix" => "api"], function (CgRouteCollector $router) {
App::$collector->group(['before' => 'bearer'], function (CgRouteCollector $router) {
App::$collector->group(["prefix" => "module_shop"], function (CgRouteCollector $router) {
App::$collector->get('/gb_slug', [\app\modules\module_shop\controllers\ModuleShopRestController::class, 'actionIndexGroupBySlug']);
App::$collector->get('/install/{id}', [\app\modules\module_shop\controllers\ModuleShopRestController::class, 'actionInstall']);
App::$collector->get('/get_all_dependencies/{slug}', [\app\modules\module_shop\controllers\ModuleShopRestController::class, 'actionGetDependenciesBySlug']);
App::$collector->group(["prefix" => "kernel"], function (CgRouteCollector $router) {
App::$collector->get('/update/{id}', [\app\modules\module_shop\controllers\KernelShopRestController::class, 'actionUpdate']);
});
});
$router->rest("module_shop", [\app\modules\module_shop\controllers\ModuleShopRestController::class]);
});
});

View File

@ -0,0 +1,90 @@
<?php
namespace app\modules\module_shop\services;
use app\modules\module_shop\models\ModuleShop;
use kernel\FormModel;
use kernel\helpers\Debug;
use kernel\helpers\Files;
use kernel\helpers\Manifest;
use kernel\helpers\Slug;
use kernel\services\ModuleService;
class ModuleShopService extends ModuleService
{
public function create(FormModel $form_model): false|ModuleShop
{
$model = new ModuleShop();
$model->name = $form_model->getItem("name");
$model->version = $form_model->getItem("version");
$model->description = $form_model->getItem("description");
$model->author = $form_model->getItem("author");
$model->status = $form_model->getItem("status");
$model->path_to_archive = $form_model->getItem("path_to_archive");
$model->dependence = $form_model->getItem("dependence");
$model->slug = $form_model->getItem("slug");
$model->type = $form_model->getItem("type");
if ($model->save()) {
return $model;
}
return false;
}
public function update(FormModel $form_model, ModuleShop $model): false|ModuleShop
{
$model->name = $form_model->getItem("name");
$model->version = $form_model->getItem("version");
$model->description = $form_model->getItem("description");
$model->author = $form_model->getItem("author");
$model->status = $form_model->getItem("status");
$model->path_to_archive = $form_model->getItem("path_to_archive");
$model->dependence = $form_model->getItem("dependence");
$model->slug = $form_model->getItem("slug");
$model->type = $form_model->getItem("type");
if ($model->save()) {
return $model;
}
return false;
}
public static function getAllDependencies(string $slug, array $depArr = []): array
{
$query = ModuleShop::query();
$query->select('ms1.*')
->from('module_shop as ms1')
->leftJoin('module_shop as ms2', function ($join) {
$join->on('ms1.slug', '=', 'ms2.slug')
->on('ms1.id', '<', 'ms2.id');
})
->where('ms2.slug', '=', null);
$query->where('ms1.slug', $slug);
$module = $query->first();
if ($module){
if ($module->dependence !== null){
$moduleDependencies = explode(",", $module->dependence);
foreach ($moduleDependencies as $dependency){
if (!in_array($dependency, $depArr)){
$depArr[] = $dependency;
$depArrTmp = self::getAllDependencies($dependency, $depArr);
foreach ($depArrTmp as $item){
if (!in_array($item, $depArr)){
$depArr[] = $item;
}
}
}
}
}
}
return array_diff($depArr, [$slug]);
}
}

View File

@ -0,0 +1,51 @@
<?php
/**
* @var ModuleShop $model
*/
use app\modules\module_shop\models\ModuleShop;
$form = new \itguild\forms\ActiveForm();
$form->beginForm("/admin/module_shop/admin_theme", enctype: 'multipart/form-data');
$form->field(class: \itguild\forms\inputs\File::class, name: "path_to_archive", params: [
'class' => "form-control",
'placeholder' => 'Путь к файлу темы админ-панели',
'value' => $model->path_to_archive ?? ''
])
->setLabel("Путь к файлу темы админ-панели")
->render();
$form->field(class: \itguild\forms\inputs\Select::class, name: "status", params: [
'class' => "form-control",
'value' => $model->status ?? ''
])
->setLabel("Статус")
->setOptions(ModuleShop::getStatus())
->render();
?>
<div class="row">
<div class="col-sm-2">
<?php
$form->field(\itguild\forms\inputs\Button::class, name: "btn-submit", params: [
'class' => "btn btn-primary ",
'value' => 'Отправить',
'typeInput' => 'submit'
])
->render();
?>
</div>
<div class="col-sm-2">
<?php
$form->field(\itguild\forms\inputs\Button::class, name: "btn-reset", params: [
'class' => "btn btn-warning",
'value' => 'Сбросить',
'typeInput' => 'reset'
])
->render();
?>
</div>
</div>
<?php
$form->endForm();

View File

@ -0,0 +1,53 @@
<?php
/**
* @var ModuleShop $model
*/
use app\modules\module_shop\models\ModuleShop;
$form = new \itguild\forms\ActiveForm();
$form->beginForm("/admin/module_shop/module", enctype: 'multipart/form-data');
$form->field(class: \itguild\forms\inputs\File::class, name: "path_to_archive", params: [
'class' => "form-control",
'placeholder' => 'Путь к файлу модуля',
'value' => $model->path_to_archive ?? ''
])
->setLabel("Путь к файлу модуля")
->render();
$form->field(class: \itguild\forms\inputs\Select::class, name: "status", params: [
'class' => "form-control",
'value' => $model->status ?? ''
])
->setLabel("Статус")
->setOptions(ModuleShop::getStatus())
->render();
?>
<div class="row">
<div class="col-sm-2">
<?php
$form->field(\itguild\forms\inputs\Button::class, name: "btn-submit", params: [
'class' => "btn btn-primary ",
'value' => 'Отправить',
'typeInput' => 'submit'
])
->render();
?>
</div>
<div class="col-sm-2">
<?php
$form->field(\itguild\forms\inputs\Button::class, name: "btn-reset", params: [
'class' => "btn btn-warning",
'value' => 'Сбросить',
'typeInput' => 'reset'
])
->render();
?>
</div>
</div>
<?php
$form->endForm();

View File

@ -0,0 +1,36 @@
<?php
/**
* @var \Illuminate\Database\Eloquent\Collection $module
* @var int $page_number
*/
use app\modules\module_shop\models\ModuleShop;
use Itguild\EloquentTable\EloquentDataProvider;
use Itguild\EloquentTable\ListEloquentTable;
use kernel\IGTabel\action_column\DeleteActionColumn;
use kernel\IGTabel\action_column\ViewActionColumn;
use kernel\IGTabel\btn\PrimaryBtn;
$table = new ListEloquentTable(new EloquentDataProvider(\app\modules\module_shop\models\ModuleShop::class, [
'currentPage' => $page_number,
'perPage' => 8,
'params' => ["class" => "table table-bordered", "border" => "2"],
'baseUrl' => "/admin/module_shop",
]));
$table->columns([
'status' => function ($data) {
return ModuleShop::getStatus()[$data];
}
]);
$table->beforePrint(function () {
$btn = PrimaryBtn::create("Добавить модуль", "/admin/module_shop/module/create", width: '250px')->fetch();
$btn .= PrimaryBtn::create("Добавить ядро", "/admin/module_shop/kernel/create", '250px')->fetch();
$btn .= PrimaryBtn::create("Добавить тему админ-панели", "/admin/module_shop/admin_theme/create", '250px')->fetch();
$btn .= PrimaryBtn::create("Добавить тему сайта", "/admin/module_shop/theme/create", '250px')->fetch();
return $btn;
});
$table->addAction(ViewActionColumn::class);
$table->addAction(DeleteActionColumn::class);
$table->create();
$table->render();

View File

@ -0,0 +1,53 @@
<?php
/**
* @var ModuleShop $model
*/
use app\modules\module_shop\models\ModuleShop;
$form = new \itguild\forms\ActiveForm();
$form->beginForm("/admin/module_shop/kernel", enctype: 'multipart/form-data');
$form->field(class: \itguild\forms\inputs\File::class, name: "path_to_archive", params: [
'class' => "form-control",
'placeholder' => 'Путь к ядра',
'value' => $model->path_to_archive ?? ''
])
->setLabel("Путь к файлу ядра")
->render();
$form->field(class: \itguild\forms\inputs\Select::class, name: "status", params: [
'class' => "form-control",
'value' => $model->status ?? ''
])
->setLabel("Статус")
->setOptions(ModuleShop::getStatus())
->render();
?>
<div class="row">
<div class="col-sm-2">
<?php
$form->field(\itguild\forms\inputs\Button::class, name: "btn-submit", params: [
'class' => "btn btn-primary ",
'value' => 'Отправить',
'typeInput' => 'submit'
])
->render();
?>
</div>
<div class="col-sm-2">
<?php
$form->field(\itguild\forms\inputs\Button::class, name: "btn-reset", params: [
'class' => "btn btn-warning",
'value' => 'Сбросить',
'typeInput' => 'reset'
])
->render();
?>
</div>
</div>
<?php
$form->endForm();

View File

@ -0,0 +1,51 @@
<?php
/**
* @var ModuleShop $model
*/
use app\modules\module_shop\models\ModuleShop;
$form = new \itguild\forms\ActiveForm();
$form->beginForm("/admin/module_shop/theme", enctype: 'multipart/form-data');
$form->field(class: \itguild\forms\inputs\File::class, name: "path_to_archive", params: [
'class' => "form-control",
'placeholder' => 'Путь к файлу темы сайта',
'value' => $model->path_to_archive ?? ''
])
->setLabel("Путь к файлу темы сайта")
->render();
$form->field(class: \itguild\forms\inputs\Select::class, name: "status", params: [
'class' => "form-control",
'value' => $model->status ?? ''
])
->setLabel("Статус")
->setOptions(ModuleShop::getStatus())
->render();
?>
<div class="row">
<div class="col-sm-2">
<?php
$form->field(\itguild\forms\inputs\Button::class, name: "btn-submit", params: [
'class' => "btn btn-primary ",
'value' => 'Отправить',
'typeInput' => 'submit'
])
->render();
?>
</div>
<div class="col-sm-2">
<?php
$form->field(\itguild\forms\inputs\Button::class, name: "btn-reset", params: [
'class' => "btn btn-warning",
'value' => 'Сбросить',
'typeInput' => 'reset'
])
->render();
?>
</div>
</div>
<?php
$form->endForm();

View File

@ -0,0 +1,30 @@
<?php
/**
* @var Collection $module
*/
use Illuminate\Database\Eloquent\Collection;
use kernel\modules\user\models\User;
use Itguild\EloquentTable\ViewEloquentTable;
use Itguild\EloquentTable\ViewJsonTableEloquentModel;
use kernel\IGTabel\btn\DangerBtn;
use kernel\IGTabel\btn\PrimaryBtn;
use kernel\IGTabel\btn\SuccessBtn;
$table = new ViewEloquentTable(new ViewJsonTableEloquentModel($module, [
'params' => ["class" => "table table-bordered", "border" => "2"],
'baseUrl' => "/admin/module_shop",
]));
$table->beforePrint(function () use ($module) {
$btn = PrimaryBtn::create("Список", "/admin/module_shop")->fetch();
$btn .= DangerBtn::create("Удалить", "/admin/module_shop/delete/" . $module->id)->fetch();
return $btn;
});
$table->rows([
'status' => (function ($data) {
return \app\modules\module_shop\models\ModuleShop::getStatus()[$data];
})
]);
$table->create();
$table->render();

View File

@ -5,4 +5,9 @@ namespace app\modules\tag\controllers;
class TagController extends \kernel\app_modules\tag\controllers\TagController
{
public function actionByEntity()
{
// TODO
}
}

View File

@ -7,5 +7,6 @@
"app_module_path": "{APP}/modules/{slug}",
"module_class": "app\\modules\\tag\\TagModule",
"module_class_file": "{APP}/modules/tag/TagModule.php",
"routs": "routs/tag.php"
"routs": "routs/tag.php",
"dependence": "menu"
}

View File

@ -0,0 +1,18 @@
<?php
namespace app\themes\custom\assets;
use kernel\Assets;
class CustomThemesAssets extends Assets
{
protected function createCSS(): void
{
$this->registerCSS(slug: "main", resource: "/css/styles.css");
}
protected function createJS(): void
{
$this->registerJS(slug: "webpack", resource: "/js/scripts.js");
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace app\themes\custom\controllers;
use kernel\Controller;
class MainController extends Controller
{
protected function init(): void
{
parent::init();
$this->cgView->viewPath = APP_DIR . "/themes/custom/views/main/";
$this->cgView->layout = "main.php";
$this->cgView->layoutPath = APP_DIR . "/themes/custom/views/layout/";
$this->cgView->addVarToLayout("resources", "/resources/themes/custom");
}
public function actionIndex(): void
{
$this->cgView->render("index.php");
}
public function actionAbout(): void
{
$this->cgView->render("about.php");
}
}

View File

@ -0,0 +1,12 @@
{
"name": "Custom",
"version": "0.1",
"author": "ItGuild",
"slug": "custom",
"type": "theme",
"description": "Custom theme",
"preview": "preview.png",
"resource": "/resources/themes/custom",
"resource_path": "{RESOURCES}/themes/custom",
"routs": "routs/custom.php"
}

View File

@ -0,0 +1,12 @@
<?php
use kernel\App;
App::$collector->get('/', [\app\themes\custom\controllers\MainController::class, 'actionIndex']);
App::$collector->get('/about', [\app\themes\custom\controllers\MainController::class, 'actionAbout']);
//App::$collector->get('/page/{page_number}', [\app\modules\tag\controllers\TagController::class, 'actionIndex']);
//App::$collector->get('/create', [\app\modules\tag\controllers\TagController::class, 'actionCreate']);

View File

@ -0,0 +1,92 @@
<?php
/**
* @var string $content
* @var string $resources
* @var string $title
* @var \kernel\CgView $view
*/
$assets = new \app\themes\custom\assets\CustomThemesAssets($resources);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/>
<?php $assets->getCSSAsSTR(); ?>
<meta name="description" content=""/>
<meta name="author" content=""/>
<title><?= $title ?></title>
<?= $view->getMeta() ?>
<link rel="icon" type="image/x-icon" href="<?= $resources ?>/assets/favicon.ico"/>
<!-- Font Awesome icons (free version)-->
<script src="https://use.fontawesome.com/releases/v6.3.0/js/all.js" crossorigin="anonymous"></script>
<!-- Google fonts-->
<link href="https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet"
type="text/css"/>
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800"
rel="stylesheet" type="text/css"/>
<!-- Core theme CSS (includes Bootstrap)-->
</head>
<body>
<!-- Navigation-->
<nav class="navbar navbar-expand-lg navbar-light" id="mainNav">
<div class="container px-4 px-lg-5">
<a class="navbar-brand" href="/">Custom theme</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarResponsive"
aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
Menu
<i class="fas fa-bars"></i>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ms-auto py-4 py-lg-0">
<li class="nav-item"><a class="nav-link px-lg-3 py-3 py-lg-4" href="/">На главную</a></li>
<li class="nav-item"><a class="nav-link px-lg-3 py-3 py-lg-4" href="/about">О нас</a></li>
</ul>
</div>
</div>
</nav>
<?= $content ?>
<!-- Footer-->
<footer class="border-top">
<div class="container px-4 px-lg-5">
<div class="row gx-4 gx-lg-5 justify-content-center">
<div class="col-md-10 col-lg-8 col-xl-7">
<ul class="list-inline text-center">
<li class="list-inline-item">
<a href="#!">
<span class="fa-stack fa-lg">
<i class="fas fa-circle fa-stack-2x"></i>
<i class="fab fa-twitter fa-stack-1x fa-inverse"></i>
</span>
</a>
</li>
<li class="list-inline-item">
<a href="#!">
<span class="fa-stack fa-lg">
<i class="fas fa-circle fa-stack-2x"></i>
<i class="fab fa-facebook-f fa-stack-1x fa-inverse"></i>
</span>
</a>
</li>
<li class="list-inline-item">
<a href="#!">
<span class="fa-stack fa-lg">
<i class="fas fa-circle fa-stack-2x"></i>
<i class="fab fa-github fa-stack-1x fa-inverse"></i>
</span>
</a>
</li>
</ul>
<div class="small text-center text-muted fst-italic">Copyright &copy; IT Guild Micro Framework</div>
</div>
</div>
</div>
</footer>
<!-- Bootstrap core JS-->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
<!-- Core theme JS-->
<?php $assets->getJSAsStr(); ?>
</body>
</html>

View File

@ -0,0 +1,36 @@
<?php
/**
* @var string $resources;
* @var \kernel\CgView $view
*/
$view->setTitle("Старт Bootstrap");
$view->setMeta([
'description' => 'Дефолтная bootstrap тема'
]);
?>
<!-- Page Header-->
<header class="masthead" style="background-image: url('<?= $resources ?>/assets/img/about-bg.jpeg')">
<div class="container position-relative px-4 px-lg-5">
<div class="row gx-4 gx-lg-5 justify-content-center">
<div class="col-md-10 col-lg-8 col-xl-7">
<div class="page-heading">
<h1>About Me</h1>
<span class="subheading">This is what I do.</span>
</div>
</div>
</div>
</div>
</header>
<!-- Main Content-->
<main class="mb-4">
<div class="container px-4 px-lg-5">
<div class="row gx-4 gx-lg-5 justify-content-center">
<div class="col-md-10 col-lg-8 col-xl-7">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Saepe nostrum ullam eveniet pariatur voluptates odit, fuga atque ea nobis sit soluta odio, adipisci quas excepturi maxime quae totam ducimus consectetur?</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eius praesentium recusandae illo eaque architecto error, repellendus iusto reprehenderit, doloribus, minus sunt. Numquam at quae voluptatum in officia voluptas voluptatibus, minus!</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aut consequuntur magnam, excepturi aliquid ex itaque esse est vero natus quae optio aperiam soluta voluptatibus corporis atque iste neque sit tempora!</p>
</div>
</div>
</div>
</main>

View File

@ -0,0 +1,86 @@
<?php
/**
* @var string $resources;
* @var \kernel\CgView $view
*/
$view->setTitle("IT Guild Micro Framework");
$view->setMeta([
'description' => 'Default IT Guild Micro Framework theme'
]);
?>
<!-- Page Header-->
<header class="masthead" style="background-image: url('<?= $resources ?>/assets/img/home-bg.jpeg')">
<div class="container position-relative px-4 px-lg-5">
<div class="row gx-4 gx-lg-5 justify-content-center">
<div class="col-md-10 col-lg-8 col-xl-7">
<div class="site-heading">
<h1>Clean Blog</h1>
<span class="subheading">A Blog Theme by IT Guild Micro Framework</span>
</div>
</div>
</div>
</div>
</header>
<!-- Main Content-->
<div class="container px-4 px-lg-5">
<div class="row gx-4 gx-lg-5 justify-content-center">
<div class="col-md-10 col-lg-8 col-xl-7">
<!-- Post preview-->
<div class="post-preview">
<a href="#!">
<h2 class="post-title">Man must explore, and this is exploration at its greatest</h2>
<h3 class="post-subtitle">Problems look mighty small from 150 miles up</h3>
</a>
<p class="post-meta">
Posted by
<a href="#!">Start Bootstrap</a>
on September 24, 2023
</p>
</div>
<!-- Divider-->
<hr class="my-4" />
<!-- Post preview-->
<div class="post-preview">
<a href="#!"><h2 class="post-title">I believe every human has a finite number of heartbeats. I don't intend to waste any of mine.</h2></a>
<p class="post-meta">
Posted by
<a href="#!">Start Bootstrap</a>
on September 18, 2023
</p>
</div>
<!-- Divider-->
<hr class="my-4" />
<!-- Post preview-->
<div class="post-preview">
<a href="#!">
<h2 class="post-title">Science has not yet mastered prophecy</h2>
<h3 class="post-subtitle">We predict too much for the next year and yet far too little for the next ten.</h3>
</a>
<p class="post-meta">
Posted by
<a href="#!">Start Bootstrap</a>
on August 24, 2023
</p>
</div>
<!-- Divider-->
<hr class="my-4" />
<!-- Post preview-->
<div class="post-preview">
<a href="#!">
<h2 class="post-title">Failure is not an option</h2>
<h3 class="post-subtitle">Many say exploration is part of our destiny, but its actually our duty to future generations.</h3>
</a>
<p class="post-meta">
Posted by
<a href="#!">Start Bootstrap</a>
on July 8, 2023
</p>
</div>
<!-- Divider-->
<hr class="my-4" />
<!-- Pager-->
<div class="d-flex justify-content-end mb-4"><a class="btn btn-primary text-uppercase" href="#!">Older Posts →</a></div>
</div>
</div>
</div>

View File

@ -6,13 +6,14 @@ $dotenv->load();
include_once __DIR__ . "/bootstrap/db.php";
include_once __DIR__ . "/bootstrap/header.php";
include_once __DIR__ . "/bootstrap/secure.php";
const ROOT_DIR = __DIR__;
const KERNEL_DIR = __DIR__ . "/kernel";
const KERNEL_MODULES_DIR = __DIR__ . "/kernel/modules";
const KERNEL_ADMIN_THEMES_DIR = __DIR__ . "/kernel/admin_themes";
const CONSOLE_DIR = __DIR__ . "/kernel/console";
const RESOURCES_DIR = __DIR__ . "/resources";
const KERNEL_TEMPLATES_DIR = __DIR__ . "/kernel/templates";
const KERNEL_APP_MODULES_DIR = KERNEL_DIR . "/app_modules";
const APP_DIR = ROOT_DIR . "/app";
@ -28,11 +29,13 @@ function getConst($text): array|false|string
"{KERNEL}" => KERNEL_DIR,
"{KERNEL_MODULES}" => KERNEL_MODULES_DIR,
"{KERNEL_APP_MODULES}" => KERNEL_APP_MODULES_DIR,
"{KERNEL_TEMPLATES}" => KERNEL_TEMPLATES_DIR,
"{CONSOLE}" => CONSOLE_DIR,
"{APP}" => APP_DIR,
];
$str = $text;
foreach($constStr as $key => $value)
{
$str = str_replace($key, $value, $str);

0
bootstrap/db.php Normal file → Executable file
View File

0
bootstrap/header.php Normal file → Executable file
View File

9
bootstrap/secure.php Executable file
View File

@ -0,0 +1,9 @@
<?php
$secure_config = [
'web_auth_type' => 'login_password', // login_password, email_code
'token_type' => 'hash', // random_bytes, md5, crypt, hash, JWT
'token_expired_time' => "+30 days", // +1 day
];
\kernel\App::$secure = $secure_config;

View File

@ -14,7 +14,14 @@
"itguild/forms": "^0.1.1",
"samejack/php-argv": "dev-master",
"itguild/eloquent-table": "^0.4.1",
"ext-zip": "*"
"ext-zip": "*",
"josantonius/session": "^2.0",
"firebase/php-jwt": "^6.10",
"k-adam/env-editor": "^2.0",
"guzzlehttp/guzzle": "^7.9",
"phpmailer/phpmailer": "^6.9",
"zircote/swagger-php": "^4.11",
"doctrine/annotations": "^2.0"
},
"autoload": {
"psr-4": {

2503
composer.lock generated

File diff suppressed because it is too large Load Diff

3
kernel/AdminController.php Normal file → Executable file
View File

@ -5,14 +5,17 @@ namespace kernel;
use kernel\Controller;
use kernel\helpers\Debug;
use kernel\services\AdminThemeService;
use kernel\services\ThemeService;
class AdminController extends Controller
{
protected AdminThemeService $adminThemeService;
protected ThemeService $themeService;
protected function init(): void
{
$this->adminThemeService = new AdminThemeService();
$this->themeService = new ThemeService();
$active_theme = $this->adminThemeService->getActiveAdminThemeInfo();
$this->cgView->layoutPath = getConst($active_theme['layout_path']);
$this->cgView->layout = "/" . $active_theme['layout'];

14
kernel/App.php Normal file → Executable file
View File

@ -5,7 +5,9 @@ namespace kernel;
use kernel\helpers\Debug;
use kernel\modules\user\models\User;
use kernel\services\ModuleService;
use kernel\services\ThemeService;
use Phroute\Phroute\Dispatcher;
class App
@ -17,8 +19,14 @@ class App
static Header $header;
static User $user;
static array $secure;
public ModuleService $moduleService;
public ThemeService $themeService;
public static Database $db;
public function run(): void
@ -48,6 +56,12 @@ class App
foreach ($modules_routs as $rout){
include "$rout";
}
$themeService = new ThemeService();
$activeTheme = getConst($themeService->getActiveTheme());
if (!empty($activeTheme)){
include $activeTheme . "/" . $themeService->getThemeRout($activeTheme);
}
}
public static function create(): App

66
kernel/Assets.php Normal file
View File

@ -0,0 +1,66 @@
<?php
namespace kernel;
class Assets
{
protected array $jsHeader = [];
protected array $jsBody = [];
protected array $css = [];
protected string $resourceURI = "/resource";
public function __construct(string $resourceURI)
{
$this->setResourceURI($resourceURI);
$this->createCSS();
$this->createJS();
}
protected function createCSS(){}
protected function createJS(){}
public function setResourceURI(string $resourceURI): void
{
$this->resourceURI = $resourceURI;
}
public function registerJS(string $slug, string $resource, bool $body = true, bool $addResourceURI = true): void
{
$resource = $addResourceURI ? $this->resourceURI . $resource : $resource;
if ($body) {
$this->jsBody[$slug] = $resource;
} else {
$this->jsHeader[$slug] = $resource;
}
}
public function registerCSS(string $slug, string $resource, bool $addResourceURI = true): void
{
$resource = $addResourceURI ? $this->resourceURI . $resource : $resource;
$this->css[$slug] = $resource;
}
public function getJSAsStr(bool $body = true): void
{
if ($body) {
foreach ($this->jsBody as $key => $item){
echo "<script src='$item'></script>";
}
}
else {
foreach ($this->jsHeader as $key => $item){
echo "<script src='$item'></script>";
}
}
}
public function getCSSAsSTR(): void
{
foreach ($this->css as $key => $item){
echo "<link rel='stylesheet' href='$item'>";
}
}
}

View File

@ -46,8 +46,16 @@ class CgRouteCollector extends RouteCollector
//TODO
}
public function console($route, $handler, array $filters = []): void
/**
* @param $route
* @param $handler
* @param array $filters
* @param array $additionalInfo
* @return void
*/
public function console($route, $handler, array $filters = [], array $additionalInfo = []): void
{
$this->addRoute(Route::GET, $route, $handler, $filters);
$additionalInfo['type'] = "console";
$this->addRoute(Route::GET, $route, $handler, $filters, $additionalInfo);
}
}

42
kernel/CgView.php Normal file → Executable file
View File

@ -2,6 +2,8 @@
namespace kernel;
use kernel\helpers\Debug;
class CgView
{
public string $viewPath = '';
@ -10,6 +12,8 @@ class CgView
public array $varToLayout = [];
public bool|string $layout = false;
protected array $metaArr = [];
public function __construct()
{
@ -34,14 +38,44 @@ class CgView
$this->varToLayout[$key] = $value;
}
private function createContent(string $view, array $data = []): false|string
public function setTitle(string $title): void
{
$this->addVarToLayout('title', $title);
}
public function setMeta(array $meta): void
{
foreach ($meta as $key => $value){
$this->metaArr[$key] = $value;
}
}
public function getMeta(): string
{
$meta = "";
foreach ($this->metaArr as $key => $value){
$meta .= "<meta name='$key' content='$value'>";
}
return $meta;
}
private function createContent(string $viewFile, array $data = []): false|string
{
ob_start();
if ($this->varToLayout){
foreach ($this->varToLayout as $key => $datum) {
${"$key"} = $datum;
}
}
$view = $this;
foreach ($data as $key => $datum) {
${"$key"} = $datum;
}
include($this->viewPath . $view);
include($this->viewPath . $viewFile);
$content = ob_get_contents();
ob_end_clean();
@ -50,6 +84,10 @@ class CgView
$file_content = $content;
if (!isset($title)){
$title = "No Title";
}
$layoutPath = $this->viewPath;
if ($this->layout) {

0
kernel/Controller.php Normal file → Executable file
View File

279
kernel/EntityRelation.php Executable file
View File

@ -0,0 +1,279 @@
<?php
namespace kernel;
use Illuminate\Database\Eloquent\Model;
use kernel\helpers\Debug;
use kernel\models\Option;
use kernel\modules\option\service\OptionService;
use kernel\services\ModuleService;
class EntityRelation
{
protected ModuleService $moduleService;
public function __construct()
{
$this->moduleService = new ModuleService();
}
public static function getEntityList(): array
{
$list = [];
$moduleService = new ModuleService();
$activeModules = $moduleService->getActiveModules();
foreach ($activeModules as $module) {
if (isset($module['type']) and $module['type'] === "entity") {
$list[$module['slug']] = $module['slug'];
}
}
return $list;
}
public function getAdditionalPropertyList(): array
{
$list = [];
$activeModules = $this->moduleService->getActiveModules();
foreach ($activeModules as $module) {
if (isset($module['type']) and $module['type'] === "additional_property") {
$list[] = $module['slug'];
}
}
return $list;
}
public static function getEntitiesRelations(): array|bool
{
$entity_relations = OptionService::getItem("entity_relations");
if ($entity_relations) {
return json_decode($entity_relations, true);
}
return false;
}
public static function removePropertyFromEntityRelations(string $entity, string $property): bool
{
$entity_relations_info = Option::where("key", "entity_relations")->first();
if ($entity_relations_info) {
$entity_relations = json_decode($entity_relations_info->value, true);
if ($entity_relations[$entity]) {
$propertyKey = array_search($property, $entity_relations[$entity]);
if ($entity_relations[$entity][$propertyKey] === $property) {
unset($entity_relations[$entity][$propertyKey]);
$entity_relations[$entity] = array_values($entity_relations[$entity]);
if (empty($entity_relations[$entity])) {
unset($entity_relations[$entity]);
}
$entity_relations_info->value = json_encode($entity_relations, JSON_UNESCAPED_UNICODE);
$entity_relations_info->save();
return true;
}
}
}
return false;
}
public static function removePropertyRelation(string $property): bool
{
$entity_relations_info = Option::where("key", "entity_relations")->first();
if ($entity_relations_info) {
$entity_relations = json_decode($entity_relations_info->value, true);
foreach ($entity_relations as $entity => $entity_relation) {
if (in_array($property, $entity_relation)) {
$index = array_search($property, $entity_relation);
unset($entity_relations[$entity][$index]);
}
}
$entity_relations_info->value = json_encode($entity_relations, JSON_UNESCAPED_UNICODE);
$entity_relations_info->save();
return true;
}
return false;
}
public static function removeEntityRelation(string $entity): bool
{
$entity_relations_info = Option::where("key", "entity_relations")->first();
if ($entity_relations_info) {
$entity_relations = json_decode($entity_relations_info->value, true);
if (isset($entity_relations[$entity])) {
unset($entity_relations[$entity]);
$entity_relations_info->value = json_encode($entity_relations, JSON_UNESCAPED_UNICODE);
$entity_relations_info->save();
return true;
}
}
return false;
}
public function getEntityRelationsBySlug(string $slug)
{
$entityRelations = $this->getEntitiesRelations();
if ($entityRelations) {
if (isset($entityRelations[$slug])) {
return $entityRelations[$slug];
}
}
return [];
}
public static function addEntityRelation(string $entity, string $property): bool
{
$entity_relations_info = Option::where("key", "entity_relations")->first();
if ($entity_relations_info) {
$entity_relations = json_decode($entity_relations_info->value, true);
if (isset($entity_relations[$entity])) {
$entity_relations[$entity][] = $property;
} else {
$entity_relations[$entity][] = $property;
}
$entity_relations_info->value = json_encode($entity_relations, JSON_UNESCAPED_UNICODE);
$entity_relations_info->save();
return true;
}
return false;
}
public function getAdditionalPropertyClassBySlug(string $slug)
{
$module = $this->moduleService->getModuleInfoBySlug($slug);
if (isset($module['module_class'])) {
return new $module['module_class']();
}
return false;
}
public function renderFormInputsBySlug(string $entity, string $slug, Model $model): void
{
$moduleClass = $this->getAdditionalPropertyClassBySlug($slug);
if ($moduleClass and method_exists($moduleClass, "formInputs")) {
$moduleClass->formInputs($entity, $model);
}
}
public function renderEntityAdditionalPropertyFormBySlug(string $entity, Model $model = null): void
{
$relations = $this->getEntityRelationsBySlug($entity);
if ($relations) {
foreach ($relations as $relation) {
$this->renderFormInputsBySlug($entity, $relation, $model);
}
}
}
public function saveEntityRelationBySlug(string $slug, string $entity, Model $model, Request $request): void
{
$moduleClass = $this->getAdditionalPropertyClassBySlug($slug);
if ($moduleClass and method_exists($moduleClass, "saveInputs")) {
$moduleClass->saveInputs($entity, $model, $request);
}
}
public function saveEntityRelation(string $entity, Model $model, Request $request): void
{
$relations = $this->getEntityRelationsBySlug($entity);
if ($relations) {
foreach ($relations as $relation) {
$this->saveEntityRelationBySlug($relation, $entity, $model, $request);
}
}
}
public function getEntityAdditionalProperty(string $entity, Model $model): array
{
$relations = $this->getEntityRelationsBySlug($entity);
if ($relations) {
$relationsArr = [];
foreach ($relations as $relation) {
$moduleClass = $this->getAdditionalPropertyClassBySlug($relation);
if ($moduleClass and method_exists($moduleClass, "getItems")) {
$relationsArr[$relation] = $moduleClass->getItems($entity, $model);
}
}
return $relationsArr;
}
return [];
}
public function getAdditionalPropertyByEntityId(string $entity, string $entity_id, string $additionalPropertySlug): string
{
$moduleClass = $this->getAdditionalPropertyClassBySlug($additionalPropertySlug);
if ($moduleClass and method_exists($moduleClass, "getItem")) {
return $moduleClass->getItem($entity, $entity_id);
}
return "";
}
public function deleteEntityRelationBySlug(string $slug, string $entity, Model $model): void
{
$moduleClass = $this->getAdditionalPropertyClassBySlug($slug);
if ($moduleClass and method_exists($moduleClass, "deleteItems")) {
$moduleClass->deleteItems($entity, $model);
}
}
public function deleteEntityRelation(string $entity, Model $model): void
{
$relations = $this->getEntityRelationsBySlug($entity);
if ($relations) {
foreach ($relations as $relation) {
$this->deleteEntityRelationBySlug($relation, $entity, $model);
}
}
}
public static function getEntityByProperty(string $data): array
{
$entityRelations = self::getEntitiesRelations();
$entities = [];
foreach ($entityRelations as $entity => $property) {
if (in_array($data, $property)) {
$entities[] = $entity;
}
}
return $entities;
}
public static function configurationEntitiesByProperty(array|null $entities, string $property): void
{
$entityRelations = self::getEntitiesRelations();
if (isset($entities)) {
foreach ($entities as $entity) {
if (!isset($entityRelations[$entity])) {
EntityRelation::addEntityRelation($entity, $property);
}
}
foreach ($entityRelations as $entity => $additionalProperty) {
if (in_array($entity, $entities)) {
if (!in_array($property, $additionalProperty)) {
EntityRelation::addEntityRelation($entity, $property);
}
} else {
if (in_array($property, $additionalProperty)) {
EntityRelation::removePropertyFromEntityRelations($entity, $property);
}
}
}
} else {
foreach ($entityRelations as $entity => $additionalProperty) {
EntityRelation::removePropertyFromEntityRelations($entity, $property);
}
}
}
}

8
kernel/FileUpload.php Normal file → Executable file
View File

@ -36,7 +36,9 @@ class FileUpload
$newFileName = md5(time() . $this->fileName) . '.' . $this->fileExtension;
if (in_array($this->fileExtension, $this->allowedFileExtensions)) {
$this->uploadDir = $uploadDir . mb_substr($newFileName, 0, 2) . '/' . mb_substr($newFileName, 2, 2) . '/';
mkdir(ROOT_DIR . $this->uploadDir, 0777, true);
$oldMask = umask(0);
mkdir(ROOT_DIR . $this->uploadDir, 0775, true);
umask($oldMask);
$uploadFileDir = ROOT_DIR . $this->uploadDir;
$this->destPath = $uploadFileDir . $newFileName;
$this->uploadFile = $this->uploadDir . $newFileName;
@ -49,7 +51,9 @@ class FileUpload
} else {
if (in_array($this->fileExtension, $this->allowedFileExtensions)) {
$this->uploadDir = $uploadDir;
mkdir(ROOT_DIR . $this->uploadDir, 0777, true);
$oldMask = umask(0);
mkdir(ROOT_DIR . $this->uploadDir, 0775, true);
umask($oldMask);
$uploadFileDir = ROOT_DIR . $this->uploadDir;
$this->destPath = $uploadFileDir . $this->fileName;
$this->uploadFile = $this->uploadDir . $this->fileName;

29
kernel/Flash.php Executable file
View File

@ -0,0 +1,29 @@
<?php
namespace kernel;
use Josantonius\Session\Facades\Session;
class Flash
{
public static function setMessage(string $type, string $msg): void
{
Session::start();
Session::set($type, $msg);
}
public static function getMessage(string $type): string
{
$msg = Session::get($type, false);
Session::remove($type);
return $msg;
}
public static function hasMessage(string $type): bool
{
return Session::has($type);
}
}

27
kernel/FormModel.php Normal file → Executable file
View File

@ -42,7 +42,7 @@ class FormModel
public function getItem(string $name)
{
if (isset($this->data[$name])){
if (isset($this->data[$name])) {
return $this->data[$name];
}
@ -59,9 +59,34 @@ class FormModel
return false;
}
public function validateForUpdate(): bool
{
$res = $this->validator->validate($this->data, $this->rulesForUpdate());
if (!$res) {
return true;
}
return false;
}
public function getErrors(): array
{
return $this->validator->getProcessedErrors();
}
public function getErrorsStr(): string
{
$errorsArr = $this->getErrors();
$str = '';
if ($errorsArr['errors']) {
foreach ($errorsArr['errors'] as $key => $errorArr) {
foreach ($errorsArr['errors'][$key] as $error){
$str .= "$error <br>";
}
}
}
return $str;
}
}

0
kernel/IGTabel/action_column/DeleteActionColumn.php Normal file → Executable file
View File

0
kernel/IGTabel/action_column/EditActionColumn.php Normal file → Executable file
View File

View File

@ -0,0 +1,17 @@
<?php
namespace kernel\IGTabel\action_column;
use Itguild\Tables\ActionColumn\ActionColumn;
class InstallActionColumn extends ActionColumn
{
protected string $prefix = '/install/';
public function fetch()
{
$link = $this->baseUrl . $this->prefix . $this->id;
return " <a href='$link' class='btn btn-warning'>Установить</a> ";
}
}

3
kernel/IGTabel/action_column/ViewActionColumn.php Normal file → Executable file
View File

@ -3,10 +3,11 @@
namespace kernel\IGTabel\action_column;
use Itguild\Tables\ActionColumn\ActionColumn;
use kernel\helpers\Debug;
class ViewActionColumn extends ActionColumn
{
protected string $prefix = '/';
protected string $prefix = '/view/';
public function fetch(): string
{

0
kernel/IGTabel/btn/DangerBtn.php Normal file → Executable file
View File

8
kernel/IGTabel/btn/PrimaryBtn.php Normal file → Executable file
View File

@ -6,9 +6,9 @@ class PrimaryBtn
{
protected string $btn = '';
public function __construct(string $title, string $url)
public function __construct(string $title, string $url, $width)
{
$this->btn = "<a class='btn btn-primary' href='$url' style='margin: 3px; width: 150px;' >$title</a>";
$this->btn = "<a class='btn btn-primary' href='$url' style='margin: 3px; width: '$width >$title</a>";
}
public function fetch(): string
@ -16,9 +16,9 @@ class PrimaryBtn
return $this->btn;
}
public static function create(string $title, string $url): PrimaryBtn
public static function create(string $title, string $url, $width = '150px'): PrimaryBtn
{
return new self($title, $url);
return new self($title, $url, $width);
}
}

0
kernel/IGTabel/btn/SuccessBtn.php Normal file → Executable file
View File

50
kernel/Mailing.php Executable file
View File

@ -0,0 +1,50 @@
<?php
namespace kernel;
use kernel\helpers\Debug;
use kernel\helpers\SMTP;
use PHPMailer\PHPMailer\Exception;
class Mailing
{
protected SMTP $SMTP;
protected CgView $cgView;
protected array $data;
public function __construct(array $data = [])
{
$this->cgView = new CgView();
$this->cgView->viewPath = KERNEL_DIR . "/views/mailing/";
$this->data = $data;
$this->SMTP = new SMTP();
$this->init();
}
/**
* @throws Exception
*/
public function send_html(string $tpl, array $tplParams, array $mailParams): ?false
{
$mailParams['body'] = $this->cgView->fetch($tpl, $tplParams);
return $this->SMTP->send_html($mailParams);
}
public function run()
{
}
public static function create(array $data = []): static
{
return new static($data);
}
protected function init()
{
}
}

10
kernel/Middleware.php Executable file
View File

@ -0,0 +1,10 @@
<?php
namespace kernel;
abstract class Middleware
{
abstract function handler();
}

0
kernel/Module.php Normal file → Executable file
View File

0
kernel/Request.php Normal file → Executable file
View File

44
kernel/RestController.php Normal file → Executable file
View File

@ -17,13 +17,32 @@ class RestController
return [];
}
protected function filters(): array
{
return [];
}
#[NoReturn] public function actionIndex(): void
{
$request = new Request();
$get = $request->get();
$page = $request->get('page') ?? 1;
$perPage = $request->get('per_page') ?? 10;
$query = $this->model->query();
if ($this->filters()) {
foreach ($this->filters() as $filter){
if (key_exists($filter, $get)){
if (is_numeric($get[$filter])){
$query->where($filter, $get[$filter]);
}
elseif (is_string($get[$filter])){
$query->where($filter,'like', '%' . $get[$filter] . '%');
}
}
}
}
if ($page > 1) {
$query->skip(($page - 1) * $perPage)->take($perPage);
} else {
@ -31,7 +50,7 @@ class RestController
}
$expand = $this->expand();
$expandParams = explode( ",", $request->get('expand') ?? "");
$expandParams = explode(",", $request->get('expand') ?? "");
$finalExpand = array_intersect($expandParams, $expand);
if ($finalExpand) {
$res = $query->get()->load($finalExpand)->toArray();
@ -46,14 +65,14 @@ class RestController
{
$expand = $this->expand();
$request = new Request();
$expandParams = explode( ",", $request->get('expand') ?? "");
$expandParams = explode(",", $request->get('expand') ?? "");
$model = $this->model->where("id", $id)->first();
$finalExpand = array_intersect($expandParams, $expand);
if ($finalExpand){
if ($finalExpand) {
$model->load($finalExpand);
}
$res = [];
if ($model){
if ($model) {
$res = $model->toArray();
}
@ -64,7 +83,7 @@ class RestController
{
$model = $this->model->where("id", $id)->first();
$res = [];
if ($model){
if ($model) {
$res = $model->toArray();
}
@ -78,7 +97,7 @@ class RestController
{
$request = new Request();
$data = $request->post();
foreach ($this->model->getFillable() as $item){
foreach ($this->model->getFillable() as $item) {
$this->model->{$item} = $data[$item] ?? null;
}
$this->model->save();
@ -93,14 +112,22 @@ class RestController
$model = $this->model->where('id', $id)->first();
foreach ($model->getFillable() as $item){
$model->{$item} = $data[$item] ?? null;
foreach ($model->getFillable() as $item) {
if (!empty($data[$item])) {
$model->{$item} = $data[$item] ?? null;
}
}
$model->save();
$this->renderApi($model->toArray());
}
#[NoReturn] public function returnError(int $code): void
{
http_response_code($code);
die('Forbidden');
}
#[NoReturn] protected function renderApi(array $data): void
{
header("Content-Type: application/json");
@ -108,4 +135,5 @@ class RestController
exit();
}
}

2
kernel/Widget.php Normal file → Executable file
View File

@ -11,7 +11,7 @@ class Widget
public function __construct(array $data = [])
{
$this->cgView = new CgView();
$this->cgView->viewPath = ROOT_DIR . "/views/widgets";
$this->cgView->viewPath = KERNEL_DIR . "/views/widgets";
$this->data = $data;

View File

@ -0,0 +1,25 @@
<?php
namespace kernel\admin_themes\default;
use kernel\Assets;
class DefaultAdminThemeAssets extends Assets
{
protected function createJS(): void
{
$this->registerJS(slug: "jquery", resource: "/js/jquery.min.js");
$this->registerJS(slug: "popper", resource: "/js/popper.js");
$this->registerJS(slug: "bootstrap", resource: "/js/bootstrap.min.js");
$this->registerJS(slug: "main", resource: "/js/main.js");
}
protected function createCSS()
{
$this->registerCSS(slug: "font-awesome", resource: "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css", addResourceURI: false);
$this->registerCSS(slug: "bootstrap", resource: "/css/bootstrap.min.css");
$this->registerCSS(slug: "style", resource: "/css/style.css");
}
}

17
kernel/admin_themes/default/layout/login.php Normal file → Executable file
View File

@ -14,12 +14,23 @@
<link href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700,800,900" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="<?=$resources?>/css/style.css">
<link rel="stylesheet" href="<?= $resources ?>/css/bootstrap.min.css">
<link rel="stylesheet" href="<?= $resources ?>/css/style.css">
</head>
<body>
<div class="wrapper d-flex align-items-stretch">
<?php if (\kernel\Flash::hasMessage("error")): ?>
<div class="alert alert-danger alert-dismissible mainAlert">
<?= \kernel\Flash::getMessage("error"); ?>
<button type="button" class="btn-close closeAlertBtn"></button>
</div>
<?php endif; ?>
<?php if (\kernel\Flash::hasMessage("success")): ?>
<div class="alert alert-success alert-dismissible">
<?= \kernel\Flash::getMessage("success"); ?>
<button type="button" class="btn-close closeAlertBtn" ></button>
</div>
<?php endif; ?>
<!-- Page Content -->
<div id="content" class="p-4 p-md-5">
<?= $content ?>

38
kernel/admin_themes/default/layout/main.php Normal file → Executable file
View File

@ -2,29 +2,37 @@
/**
* @var $content
* @var string $resources
* @var string $title
* @var \kernel\CgView $view
*/
\Josantonius\Session\Facades\Session::start();
$assets = new \kernel\admin_themes\default\DefaultAdminThemeAssets($resources)
?>
<!doctype html>
<html lang="en">
<head>
<title>Sidebar 01</title>
<title><?= $title ?></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<?= $view->getMeta() ?>
<link href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700,800,900" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="<?= $resources ?>/css/style.css">
<?php $assets->getCSSAsSTR(); ?>
<?php $assets->getJSAsStr(body: false); ?>
</head>
<body>
<div class="wrapper d-flex align-items-stretch">
<nav id="sidebar">
<div class="p-4 pt-5">
<a href="#" class="img logo rounded-circle mb-5"
style="background-image: url(/resources/admin_theme/images/logo.jpg);"></a>
<a href="<?= '/admin/user/profile' ?>" class="img logo rounded-circle mb-5"
style="background-image: url(<?= \kernel\modules\user\service\UserService::getAuthUserPhoto() ?? '/resources/default_user_photo/noPhoto.png' ?>);">
</a>
<p>
<?= \kernel\modules\user\service\UserService::getAuthUsername() ?>
<a href="<?= '/admin/user/profile' ?>">
<?= \kernel\modules\user\service\UserService::getAuthUsername() ?>
</a>
</p>
<?php \kernel\widgets\MenuWidget::create()->run(); ?>
<div class="footer">
@ -68,14 +76,22 @@
</div>
</div>
</nav>
<?php if (\kernel\Flash::hasMessage("error")): ?>
<div class="alert alert-danger alert-dismissible mainAlert">
<?= \kernel\Flash::getMessage("error"); ?>
<button type="button" class="btn-close closeAlertBtn"></button>
</div>
<?php endif; ?>
<?php if (\kernel\Flash::hasMessage("success")): ?>
<div class="alert alert-success alert-dismissible">
<?= \kernel\Flash::getMessage("success"); ?>
<button type="button" class="btn-close closeAlertBtn"></button>
</div>
<?php endif; ?>
<?= $content ?>
</div>
</div>
<script src="<?= $resources ?>/js/jquery.min.js"></script>
<script src="<?= $resources ?>/js/popper.js"></script>
<script src="<?= $resources ?>/js/bootstrap.min.js"></script>
<script src="<?= $resources ?>/js/main.js"></script>
<?php $assets->getJSAsStr(); ?>
</body>
</html>

5
kernel/admin_themes/default/manifest.json Normal file → Executable file
View File

@ -3,10 +3,11 @@
"version": "0.1",
"author": "ItGuild",
"slug": "default",
"type": "admin_theme",
"description": "Default admin theme",
"preview": "preview.png",
"resource": "/resources/default",
"resource_path": "{RESOURCES}/default",
"resource": "/resources/admin_themes/default",
"resource_path": "{RESOURCES}/admin_themes/default",
"layout": "main.php",
"layout_path": "{KERNEL_ADMIN_THEMES}/default/layout"
}

2
kernel/admin_themes/simple/layout/main.php Normal file → Executable file
View File

@ -13,7 +13,7 @@
<link href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700,800,900" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css">
<link rel="stylesheet" href="<?=$resources?>/css/style.css">
</head>
<body>

4
kernel/admin_themes/simple/manifest.json Normal file → Executable file
View File

@ -5,8 +5,8 @@
"slug": "simple",
"description": "Simple admin theme",
"preview": "preview.png",
"resource": "/resources/simple",
"resource_path": "{RESOURCES}/simple",
"resource": "/resources/admin_themes/simple",
"resource_path": "{RESOURCES}/admin_themes/simple",
"layout": "main.php",
"layout_path": "{KERNEL_ADMIN_THEMES}/simple/layout"
}

View File

@ -8,10 +8,6 @@ use Itguild\EloquentTable\EloquentDataProvider;
use Itguild\EloquentTable\ListEloquentTable;
use kernel\app_modules\tag\models\Tag;
use kernel\IGTabel\btn\PrimaryBtn;
use kernel\models\Menu;
use kernel\modules\menu\table\columns\MenuDeleteActionColumn;
use kernel\modules\menu\table\columns\MenuEditActionColumn;
use kernel\modules\menu\table\columns\MenuViewActionColumn;
$table = new ListEloquentTable(new EloquentDataProvider(Tag::class, [
'currentPage' => $page_number,

0
kernel/console/CgMigrationCreator.php Normal file → Executable file
View File

View File

@ -4,6 +4,8 @@
namespace kernel\console;
use kernel\helpers\Debug;
class Out
{
private $foreground_colors = array();
@ -64,6 +66,11 @@ class Out
echo $this->get($string, $foreground_color, $background_color) . "\n";
}
public function inLine($string, $foreground_color = null, $background_color = null): void
{
echo $this->get($string, $foreground_color, $background_color) ;
}
// Returns all foreground color names
public function getForegroundColors()
{
@ -75,4 +82,16 @@ class Out
{
return array_keys($this->background_colors);
}
// public function printHeaderTable(): void
// {
// echo "\n+-----------------------------+-----------------------------+-----------------------------+-----------------------------+\n";
// printf("%-30s", "| Routs");
// printf("%-30s", "| Description");
// printf("%-30s", "| Params");
// printf("%-30s", "| Params description");
// printf("%-30s", "|");
// echo "\n+-----------------------------+-----------------------------+-----------------------------+-----------------------------+\n";
// }
}

77
kernel/console/controllers/AdminConsoleController.php Normal file → Executable file
View File

@ -46,6 +46,9 @@ class AdminConsoleController extends ConsoleController
$out = $this->migrationService->runAtPath("kernel/modules/post/migrations");
$this->out->r("create post table", "green");
$out = $this->migrationService->runAtPath("kernel/modules/secure/migrations");
$this->out->r("create secret_code table", "green");
$this->optionService->createFromParams(
key: "admin_theme_paths",
value: "{\"paths\": [\"{KERNEL_ADMIN_THEMES}\", \"{APP}/admin_themes\"]}",
@ -60,6 +63,20 @@ class AdminConsoleController extends ConsoleController
);
$this->out->r("create option active_admin_theme", "green");
$this->optionService->createFromParams(
key: "theme_paths",
value: "{\"paths\": [\"{KERNEL}/themes\", \"{APP}/themes\"]}",
label: "Пути к темам сайта"
);
$this->out->r("create option theme_paths", "green");
$this->optionService->createFromParams(
key: "active_theme",
value: "{KERNEL}/themes/default",
label: "Активная тема сайта"
);
$this->out->r("create option active_theme", "green");
$this->optionService->createFromParams(
key: "module_paths",
value: "{\"paths\": [\"{KERNEL_MODULES}\", \"{APP}/modules\"]}",
@ -69,11 +86,18 @@ class AdminConsoleController extends ConsoleController
$this->optionService->createFromParams(
key: "active_modules",
value: "{\"modules\":[\"admin_themes\", \"secure\"]}",
value: "{\"modules\":[\"admin_themes\",\"themes\",\"secure\", \"user\", \"menu\", \"post\", \"option\"]}",
label: "Активные модули"
);
$this->out->r("create option active_modules", "green");
$this->optionService->createFromParams(
key: "entity_relations",
value: "{}",
label: "Свойства сущностей"
);
$this->out->r("create option entity_relations", "green");
$this->menuService->createItem([
"label" => "Модули",
"url" => "/admin",
@ -82,9 +106,35 @@ class AdminConsoleController extends ConsoleController
]);
$this->out->r("create item menu module", "green");
$this->menuService->createItem([
"label" => "Пользователи",
"url" => "#",
"slug" => "user",
]);
$this->menuService->createItem([
"label" => "Список",
"url" => "/admin/user",
"slug" => "user_list",
"parent_slug" => "user",
]);
$this->menuService->createItem([
"label" => "Создать",
"url" => "/admin/user/create",
"slug" => "user_create",
"parent_slug" => "user",
]);
$this->out->r("create item menu user", "green");
$this->menuService->createItem([
"label" => "Посты",
"url" => "/admin/post",
"slug" => "post",
]);
$this->out->r("create item menu post", "green");
$this->menuService->createItem([
"label" => "Настройки",
"url" => "/admin/settings",
"url" => "#",
"slug" => "settings",
]);
$this->out->r("create item menu settings", "green");
@ -97,6 +147,29 @@ class AdminConsoleController extends ConsoleController
]);
$this->out->r("create item menu admin-themes", "green");
$this->menuService->createItem([
"label" => "Темы сайта",
"url" => "/admin/settings/themes",
"slug" => "themes",
"parent_slug" => "settings"
]);
$this->out->r("create item menu themes", "green");
$this->menuService->createItem([
"label" => "Меню",
"url" => "/admin/settings/menu",
"slug" => "menu",
"parent_slug" => "settings"
]);
$this->out->r("create item menu menu", "green");
$this->menuService->createItem([
"label" => "Опции",
"url" => "/admin/option",
"slug" => "option"
]);
$this->out->r("create item menu option", "green");
$user = new CreateUserForm();
$user->load([
'username' => 'admin',

66
kernel/console/controllers/AdminThemeController.php Normal file → Executable file
View File

@ -18,31 +18,15 @@ class AdminThemeController extends ConsoleController
throw new \Exception('Missing admin theme path "--path" specified');
}
$zip = new ZipArchive;
$tmpThemeDir = md5(time());
$res = $zip->open(ROOT_DIR . $this->argv['path']);
if ($res === TRUE) {
$tmpThemeDirFull = RESOURCES_DIR . '/tmp/ad/' . $tmpThemeDir . "/";
$zip->extractTo($tmpThemeDirFull);
$zip->close();
$this->out->r('Архив распакован', 'green');
if (file_exists(ROOT_DIR . $this->argv['path'])) {
$adminThemeService = new AdminThemeService();
if ($adminThemeService->install($this->argv['path'])) {
$this->out->r("Тема админ-панели установлена", 'green');
} else {
$this->out->r("Ошибка установки темы админ-панели", 'red');
}
} else {
$this->out->r('Message: Ошибка чтения архива', 'red');
}
if (file_exists($tmpThemeDirFull . "meta/manifest.json")){
$manifestJson = getConst(file_get_contents($tmpThemeDirFull . "meta/manifest.json"));
$manifest = Manifest::getWithVars($manifestJson);
$this->out->r('manifest.json инициализирован', 'green');
$fileHelper = new Files();
$fileHelper->copy_folder($tmpThemeDirFull . "meta", $manifest['theme_path']);
$fileHelper->copy_folder($tmpThemeDirFull . "resources", $manifest['resource_path']);
$this->out->r("Удаляем временные файлы", 'green');
$fileHelper->recursiveRemoveDir($tmpThemeDirFull);
$this->out->r("Тема " . $manifest['name'] . " установлена", 'green');
$this->out->r("Тема админ-панели не найдена", 'red');
}
}
@ -53,17 +37,11 @@ class AdminThemeController extends ConsoleController
}
if (file_exists(ROOT_DIR . $this->argv['path'])) {
$themeName = basename($this->argv['path']);
$active_admin_theme = Option::where("key", "active_admin_theme")->first();
if ($active_admin_theme->value === ROOT_DIR . $this->argv['path']) {
$this->out->r("Меняем тему на базовую", 'green');
$adminThemeService = new AdminThemeService();
$adminThemeService->setActiveAdminTheme(KERNEL_ADMIN_THEMES_DIR . '/default');
$this->out->r("Тема изменена", 'green');
}
$fileHelper = new Files();
$fileHelper->recursiveRemoveDir(ROOT_DIR . $this->argv['path']);
$fileHelper->recursiveRemoveDir(RESOURCES_DIR . '/' . $themeName);
$adminThemeService = new AdminThemeService();
$adminThemeService->uninstall($this->argv['path']);
$this->out->r("Тема удалена", 'green');
} else {
@ -71,4 +49,22 @@ class AdminThemeController extends ConsoleController
}
}
/**
* @throws \Exception
*/
public function actionPackTheme(): void
{
if (!isset($this->argv['path'])) {
throw new \Exception('Missing admin theme path "--path" specified');
}
if (file_exists(ROOT_DIR . $this->argv['path'])) {
$adminThemeService = new AdminThemeService();
$adminThemeService->pack($this->argv['path']);
$this->out->r("Тема админ-панели заархивирована", 'green');
} else {
$this->out->r("Тема админ-панели не найдена", 'red');
}
}
}

View File

@ -0,0 +1,128 @@
<?php
namespace kernel\console\controllers;
use kernel\console\ConsoleController;
use kernel\helpers\Files;
use ZipArchive;
class KernelController extends ConsoleController
{
protected Files $files;
public function __construct()
{
parent::__construct();
$this->files = new Files();
}
/**
* @throws \Exception
*/
public function actionPackKernel(): void
{
if (!isset($this->argv['path'])) {
throw new \Exception('Missing kernel path "--path" specified');
}
if (file_exists(ROOT_DIR . $this->argv['path'])) {
$tmpKernelDirFull = RESOURCES_DIR . '/tmp/ad/kernel/kernel';
$this->files->copyKernelFolder(ROOT_DIR . $this->argv['path'], $tmpKernelDirFull);
$this->out->r("Ядро скопировано во временную папку", 'green');
} else {
$this->out->r("Ядро не найдено", 'red');
}
if (file_exists(ROOT_DIR . '/bootstrap')) {
$tmpBootstrapDirFull = RESOURCES_DIR . '/tmp/ad/kernel/bootstrap';
$this->files->copyKernelFolder(ROOT_DIR . '/bootstrap', $tmpBootstrapDirFull);
$this->out->r("/bootstrap скопирован во временную папку", 'green');
} else {
$this->out->r("/bootstrap не найден", 'red');
}
if (file_exists(ROOT_DIR . '/bootstrap.php')) {
$tmpBootstrapPhpDirFull = RESOURCES_DIR . '/tmp/ad/kernel/bootstrap.php';
copy(ROOT_DIR . '/bootstrap.php', $tmpBootstrapPhpDirFull);
$this->out->r("/bootstrap.php скопирован во временную папку", 'green');
} else {
$this->out->r("/bootstrap.php не найден", 'red');
}
if (file_exists(ROOT_DIR . '/.env.example')) {
$tmpEnvDirFull = RESOURCES_DIR . '/tmp/ad/kernel/env.example';
copy(ROOT_DIR . '/.env.example', $tmpEnvDirFull);
$this->out->r("/.env.example скопирован во временную папку", 'green');
} else {
$this->out->r("/.env.example не найден", 'red');
}
if (file_exists(ROOT_DIR . '/composer.json')) {
$tmpComposerDirFull = RESOURCES_DIR . '/tmp/ad/kernel/composer.json';
copy(ROOT_DIR . '/composer.json', $tmpComposerDirFull);
$this->out->r("/composer.json скопирован во временную папку", 'green');
} else {
$this->out->r("/composer.json не найден", 'red');
}
if (!is_dir(RESOURCES_DIR . '/tmp/kernel')) {
mkdir(RESOURCES_DIR . '/tmp/kernel');
}
if (file_exists(KERNEL_DIR . '/manifest.json')) {
$manifest = json_decode(file_get_contents(KERNEL_DIR . '/manifest.json'), true);
$version = $manifest['version'] ?? '';
$this->files->pack(RESOURCES_DIR . '/tmp/ad/kernel/', RESOURCES_DIR . '/tmp/kernel/kernel_v' . $version . '.igk');
}
else {
$this->files->pack(RESOURCES_DIR . '/tmp/ad/kernel/', RESOURCES_DIR . '/tmp/kernel/kernel.igk');
}
$this->files->recursiveRemoveDir(RESOURCES_DIR . '/tmp/ad/kernel/');
}
/**
* @throws \Exception
*/
public function actionUpdateKernel(): void
{
if (!isset($this->argv['path'])) {
throw new \Exception('Missing kernel path "--path" specified');
}
$zip = new ZipArchive;
if (file_exists(ROOT_DIR . $this->argv['path'])) {
$tmpKernelDir = md5(time());
$res = $zip->open(ROOT_DIR . $this->argv['path']);
if ($res === TRUE) {
$tmpKernelDirFull = RESOURCES_DIR . '/tmp/kernel/' . $tmpKernelDir . "/";
$zip->extractTo($tmpKernelDirFull);
$zip->close();
$this->files->recursiveRemoveKernelDir();
$this->files->copyKernelFolder($tmpKernelDirFull . 'kernel' , ROOT_DIR . "/kernel");
if (isset($this->argv['bootstrap'])) {
$this->files->recursiveRemoveDir(ROOT_DIR . '/bootstrap');
$this->files->copyKernelFolder($tmpKernelDirFull . 'bootstrap' , ROOT_DIR . '/bootstrap');
copy($tmpKernelDirFull . '/bootstrap.php' , ROOT_DIR . '/bootstrap.php');
}
if (isset($this->argv['env'])) {
copy($tmpKernelDirFull . 'env.example', ROOT_DIR . '/.env.example');
}
if (isset($this->argv['composer'])) {
copy($tmpKernelDirFull . 'composer.json', ROOT_DIR . '/composer.json');
}
$this->files->recursiveRemoveDir($tmpKernelDirFull);
$this->out->r('Ядро обновлено.', 'green');
} else {
$this->out->r('unable to open zip archive', 'red');
}
} else {
$this->out->r("archive not found", 'red');
}
}
}

23
kernel/console/controllers/MainController.php Normal file → Executable file
View File

@ -2,7 +2,9 @@
namespace kernel\console\controllers;
use kernel\App;
use kernel\console\ConsoleController;
use kernel\helpers\Debug;
class MainController extends ConsoleController
{
@ -12,4 +14,25 @@ class MainController extends ConsoleController
$this->out->r("Привет", "green");
}
public function actionHelp(): void
{
$routs = App::$collector->getData()->getStaticRoutes();
foreach ($routs as $rout => $data){
$additionalInfo = $data['GET'][3];
if (isset($additionalInfo['description']) and $additionalInfo['type'] === "console"){
$this->out->inLine($rout . " - ", "green");
$this->out->inLine($additionalInfo['description'], 'yellow');
$this->out->r("");
if (isset($additionalInfo['params'])){
foreach ($additionalInfo['params'] as $key => $param){
$this->out->inLine($key . " - ", "green");
$this->out->inLine($param, 'yellow');
$this->out->r("");
}
}
$this->out->r("");
}
}
}
}

0
kernel/console/controllers/MigrationController.php Normal file → Executable file
View File

45
kernel/console/controllers/ModuleController.php Normal file → Executable file
View File

@ -24,7 +24,11 @@ class ModuleController extends ConsoleController
if (file_exists(ROOT_DIR . $this->argv['path'])) {
$moduleService = new ModuleService();
$moduleService->installModule($this->argv['path']);
if ($moduleService->installModule($this->argv['path'])) {
$this->out->r("Модуль установлен", 'green');
} else {
$this->out->r("Ошибка установки модуля", 'red');
}
} else {
$this->out->r("Модуль не найден", 'red');
}
@ -42,6 +46,7 @@ class ModuleController extends ConsoleController
if (file_exists(ROOT_DIR . $this->argv['path'])) {
$moduleService = new ModuleService();
$moduleService->uninstallModule($this->argv['path']);
$this->out->r("Модуль удален", 'green');
} else {
$this->out->r("Модуль не найден", 'red');
}
@ -59,6 +64,7 @@ class ModuleController extends ConsoleController
if (file_exists(ROOT_DIR . $this->argv['path'])) {
$moduleService = new ModuleService();
$moduleService->packModule($this->argv['path']);
$this->out->r("Модуль заархивирован", 'green');
} else {
$this->out->r("Модуль не найден", 'red');
}
@ -74,8 +80,43 @@ class ModuleController extends ConsoleController
}
if (file_exists(ROOT_DIR . $this->argv['path'])) {
$moduleService = new ModuleService();
$moduleService->updateModule($this->argv['path']);
if ($moduleService->updateModule($this->argv['path'])) {
$this->out->r("Модуль обновлен", 'green');
} else {
$this->out->r("Ошибка обновления модуля", 'red');
}
} else {
$this->out->r("Модуль не найден", 'red');
}
}
public function actionConstructModule(): void
{
$this->out->r("Введите slug модуля:", 'yellow');
$slug = substr(fgets(STDIN), 0, -1);
$slug = strtolower($slug);
$this->out->r("Введите название модуля:", 'yellow');
$name = substr(fgets(STDIN), 0, -1);
$this->out->r("Введите автора модуля:", 'yellow');
$author = substr(fgets(STDIN), 0, -1);
$this->out->r("Введите название пунтка меню для модуля:", 'yellow');
$label = substr(fgets(STDIN), 0, -1);
$moduleService = new ModuleService();
$moduleService->createDirs($slug);
$moduleService->createModuleByParams([
'slug' => $slug,
'model' => ucfirst($slug),
'author' => $author,
'name' => $name,
'label' => $label,
]);
$this->out->r("Модуль $slug создан", 'green');
}
}

View File

@ -0,0 +1,25 @@
<?php
namespace kernel\console\controllers;
use kernel\console\ConsoleController;
use kernel\services\TokenService;
use Random\RandomException;
class SecureController extends ConsoleController
{
/**
* @throws RandomException
*/
public function actionCreateSecretKey(): void
{
$envFile = \EnvEditor\EnvFile::loadFrom(ROOT_DIR . "/.env");
$envFile->setValue("SECRET_KEY", TokenService::random_bytes(15));
$envFile->saveTo(ROOT_DIR . "/.env");
$this->out->r("Secret key successfully created.", "green");
}
}

View File

@ -0,0 +1,73 @@
<?php
namespace kernel\console\controllers;
use kernel\console\ConsoleController;
use kernel\helpers\Files;
use kernel\helpers\Manifest;
use kernel\models\Option;
use kernel\services\AdminThemeService;
use kernel\services\ThemeService;
use ZipArchive;
class ThemeController extends ConsoleController
{
/**
* @throws \Exception
*/
public function actionInstallTheme(): void
{
if (!isset($this->argv['path'])) {
throw new \Exception('Missing theme path "--path" specified');
}
if (file_exists(ROOT_DIR . $this->argv['path'])) {
$themeService = new ThemeService();
if ($themeService->install($this->argv['path'])) {
$this->out->r("Тема сайта установлена", 'green');
} else {
$this->out->r("Ошибка установки темы сайта", 'red');
}
} else {
$this->out->r("Тема сайта не найдена", 'red');
}
}
/**
* @throws \Exception
*/
public function actionUninstallTheme(): void
{
if (!isset($this->argv['path'])) {
throw new \Exception('Missing theme path "--path" specified');
}
if (file_exists(ROOT_DIR . $this->argv['path'])) {
$themeService = new ThemeService();
$themeService->uninstall($this->argv['path']);
$this->out->r("Тема сайта удалена", 'green');
} else {
$this->out->r("Тема сайта не найдена", 'red');
}
}
/**
* @throws \Exception
*/
public function actionPackTheme(): void
{
if (!isset($this->argv['path'])) {
throw new \Exception('Missing theme path "--path" specified');
}
if (file_exists(ROOT_DIR . $this->argv['path'])) {
$themeService = new ThemeService();
$themeService->pack($this->argv['path']);
$this->out->r("Тема сайта заархивирована", 'green');
} else {
$this->out->r("Тема сайта не найдена", 'red');
}
}
}

View File

@ -6,6 +6,7 @@ use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public string $migration;
/**
* Run the migrations.
*/

107
kernel/console/routs/cli.php Normal file → Executable file
View File

@ -1,30 +1,115 @@
<?php
use kernel\App;
use kernel\console\controllers\MigrationController;
use Phroute\Phroute\RouteCollector;
App::$collector->console("hello", [\kernel\console\controllers\MainController::class, "indexAction"]);
App::$collector->console("help", [\kernel\console\controllers\MainController::class, "actionHelp"]);
App::$collector->group(["prefix" => "migration"], callback: function (RouteCollector $router){
App::$collector->console('run', [\kernel\console\controllers\MigrationController::class, 'actionRun']);
App::$collector->console('init', [\kernel\console\controllers\MigrationController::class, 'actionCreateMigrationTable']);
App::$collector->console('create', [\kernel\console\controllers\MigrationController::class, 'actionCreate']);
App::$collector->console('rollback', [\kernel\console\controllers\MigrationController::class, 'actionRollback']);
App::$collector->console('run',
[MigrationController::class, 'actionRun'],
additionalInfo: ['description' => 'Запуск существующих миграций']
);
App::$collector->console('init',
[MigrationController::class, 'actionCreateMigrationTable'],
additionalInfo: ['description' => 'Инициализация миграций']
);
App::$collector->console('create',
[MigrationController::class, 'actionCreate'],
additionalInfo: ['description' => 'Создание миграции', 'params' => ['--name' => 'Название миграции', '--path' => 'Путь по которому будет создана миграция']]
);
App::$collector->console('rollback',
[MigrationController::class, 'actionRollback'],
additionalInfo: ['description' => 'Откатить миграции']
);
});
App::$collector->group(["prefix" => "admin-theme"], callback: function (RouteCollector $router){
App::$collector->console('install', [\kernel\console\controllers\AdminThemeController::class, 'actionInstallTheme']);
App::$collector->console('uninstall', [\kernel\console\controllers\AdminThemeController::class, 'actionUninstallTheme']);
App::$collector->console('install',
[\kernel\console\controllers\AdminThemeController::class, 'actionInstallTheme'],
additionalInfo: ['description' => 'Установить тему админ-панели', 'params' => ['--path' => 'Путь к устанавливаемой теме']]
);
App::$collector->console('uninstall',
[\kernel\console\controllers\AdminThemeController::class, 'actionUninstallTheme'],
additionalInfo: ['description' => 'Удалить тему админ-панели', 'params' => ['--path' => 'Путь к удаляемой теме']]
);
App::$collector->console('pack',
[\kernel\console\controllers\AdminThemeController::class, 'actionPackTheme'],
additionalInfo: ['description' => 'Заархивировать тему админ-панели', 'params' => ['--path' => 'Путь к теме, которую нужно заархивировать']]
);
});
App::$collector->group(["prefix" => "theme"], callback: function (RouteCollector $router){
App::$collector->console('install',
[\kernel\console\controllers\ThemeController::class, 'actionInstallTheme'],
additionalInfo: ['description' => 'Установить тему сайта', 'params' => ['--path' => 'Путь к устанавливаемой теме']]
);
App::$collector->console('uninstall',
[\kernel\console\controllers\ThemeController::class, 'actionUninstallTheme'],
additionalInfo: ['description' => 'Удалить тему сайта', 'params' => ['--path' => 'Путь к удаляемой теме']]
);
App::$collector->console('pack',
[\kernel\console\controllers\ThemeController::class, 'actionPackTheme'],
additionalInfo: ['description' => 'Заархивировать тему сайта', 'params' => ['--path' => 'Путь к теме, которую нужно заархивировать']]
);
});
App::$collector->group(["prefix" => "secure"], callback: function (RouteCollector $router){
App::$collector->console('create-secret-key',
[\kernel\console\controllers\SecureController::class, 'actionCreateSecretKey'],
additionalInfo: ['description' => 'Генерация секрктного ключа и запись его в .env']
);
});
App::$collector->group(["prefix" => "admin"], callback: function (RouteCollector $router){
App::$collector->console('init', [\kernel\console\controllers\AdminConsoleController::class, 'actionInit']);
App::$collector->console('init',
[\kernel\console\controllers\AdminConsoleController::class, 'actionInit'],
additionalInfo: ['description' => 'Инициализация админ-панели']
);
});
App::$collector->group(["prefix" => "module"], callback: function (RouteCollector $router){
App::$collector->console('install', [\kernel\console\controllers\ModuleController::class, 'actionInstallModule']);
App::$collector->console('uninstall', [\kernel\console\controllers\ModuleController::class, 'actionUninstallModule']);
App::$collector->console('pack', [\kernel\console\controllers\ModuleController::class, 'actionPackModule']);
App::$collector->console('update', [\kernel\console\controllers\ModuleController::class, 'actionUpdateModule']);
App::$collector->console('install',
[\kernel\console\controllers\ModuleController::class, 'actionInstallModule'],
additionalInfo: ['description' => 'Установка модуля', 'params' => ['--path' => 'Путь к устанавливаемому модулю']]
);
App::$collector->console('uninstall',
[\kernel\console\controllers\ModuleController::class, 'actionUninstallModule'],
additionalInfo: ['description' => 'Удалить модуль', 'params' => ['--path' => 'Путь к удаляемому модулю']]
);
App::$collector->console('pack',
[\kernel\console\controllers\ModuleController::class, 'actionPackModule'],
additionalInfo: ['description' => 'Заархивировать модуль', 'params' => ['--path' => 'Путь к модулю, который нужно заархивировать']]
);
App::$collector->console('update',
[\kernel\console\controllers\ModuleController::class, 'actionUpdateModule'],
additionalInfo: ['description' => 'Обновить модуль', 'params' => ['--path' => 'Путь к архиву с модулем']]
);
App::$collector->console('construct',
[\kernel\console\controllers\ModuleController::class, 'actionConstructModule'],
additionalInfo: ['description' => 'Сгенерировать модуль']
);
});
App::$collector->group(["prefix" => "kernel"], callback: function (RouteCollector $router){
App::$collector->console('pack',
[\kernel\console\controllers\KernelController::class, 'actionPackKernel'],
additionalInfo: ['description' => 'Заархивировать ядро', 'params' => ['--path' => 'Путь к ядру']]
);
App::$collector->console('update',
[\kernel\console\controllers\KernelController::class, 'actionUpdateKernel'],
additionalInfo: [
'description' => 'Обновить модуль',
'params' =>
[
'--path' => 'Путь к архиву ядра',
'bootstrap' => 'Обновить bootstrap',
'composer' => 'Обновить composer',
'env' => 'Обновить .env.example'
]
]
);
});

61
kernel/controllers/ModuleController.php Normal file → Executable file
View File

@ -3,10 +3,11 @@
namespace kernel\controllers;
use DirectoryIterator;
use JetBrains\PhpStorm\NoReturn;
use Josantonius\Session\Facades\Session;
use kernel\AdminController;
use kernel\helpers\Debug;
use kernel\models\Option;
use kernel\modules\user\service\UserService;
use kernel\Request;
use kernel\services\ModuleService;
@ -22,36 +23,71 @@ class ModuleController extends AdminController
$this->moduleService = new ModuleService();
}
public function actionIndex(): void
public function actionIndex($page_number = 1): void
{
$admin_theme_paths = Option::where("key", "module_paths")->first();
$per_page = 8;
$module_paths = Option::where("key", "module_paths")->first();
$dirs = [];
if ($admin_theme_paths){
$path = json_decode($admin_theme_paths->value);
if ($module_paths){
$path = json_decode($module_paths->value);
foreach ($path->paths as $p){
$dirs[] = getConst($p);
}
}
$modules_info = [];
$i = 1;
foreach ($dirs as $dir){
$i = 1;
foreach (new DirectoryIterator($dir) as $fileInfo) {
$info = [];
if($fileInfo->isDot()) continue;
$mi = $this->moduleService->getModuleInfo($fileInfo->getPathname());
if (isset($mi['show_in_admin'])){
if ($mi['show_in_admin'] == 0){
continue;
}
}
$info['id'] = $i;
$modules_info[] = array_merge($info, $this->moduleService->getModuleInfo($fileInfo->getPathname()));
$modules_info[] = array_merge($info, $mi);
$i++;
}
}
$this->cgView->render("index.php", ['modules_info' => $modules_info, 'moduleService' => $this->moduleService]);
$module_count = count($modules_info);
$modules_info = array_slice($modules_info, $per_page*($page_number-1), $per_page);
$this->cgView->render("index.php", [
'modules_info' => $modules_info,
'moduleService' => $this->moduleService,
'page_number' => $page_number,
'module_count' => $module_count,
'per_page' => $per_page,
]);
}
public function actionActivate(): void
{
$request = new Request();
$this->moduleService->toggleModule($request->get("slug"));
$active_res = $this->moduleService->setActiveModule($request->get("slug"));
if (!$active_res) {
Session::start();
Session::set("error", implode(";", $this->moduleService->getErrors()));
$this->redirect("/admin", 302);
}
$mod_info = $this->moduleService->getModuleInfoBySlug($request->get('slug'));
$this->cgView->render("view.php", ['data' => $mod_info]);
}
public function actionDeactivate(): void
{
$request = new Request();
$active_res = $this->moduleService->deactivateModule($request->get("slug"));
if (!$active_res){
Session::start();
Session::set("error", implode(";", $this->moduleService->getErrors()));
$this->redirect("/admin", 302);
}
$mod_info = $this->moduleService->getModuleInfoBySlug($request->get('slug'));
$this->cgView->render("view.php", ['data' => $mod_info]);
@ -65,4 +101,11 @@ class ModuleController extends AdminController
$this->cgView->render("view.php", ['data' => $mod_info]);
}
#[NoReturn] public function actionUpdate(): void
{
$request = new Request();
$slug = $request->get('slug');
$this->redirect("/admin/module_shop_client/update/?slug=" . $slug, 302);
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace kernel\filters;
use itguild\forms\builders\SelectBuilder;
use Itguild\Tables\Filter\Filter;
use kernel\helpers\Debug;
class BootstrapSelectFilter extends Filter
{
public function fetch(): string
{
$select = SelectBuilder::build($this->name, [
'class' => 'form-control',
'options' => $this->params['options'],
'value' => $this->value,
'prompt' => $this->params['prompt'] ?? null,
]);
return "<td>" . $select->create()->fetch() . "</td>";
}
}

View File

@ -0,0 +1,21 @@
<?php
namespace kernel\filters;
use itguild\forms\builders\TextInputBuilder;
use Itguild\Tables\Filter\Filter;
class BootstrapTextFilter extends Filter
{
public function fetch()
{
$textInput = TextInputBuilder::build($this->name, [
'value' => $this->value,
'class' => "form-control"
]);
return "<td>" . $textInput->create()->fetch() . "</td>";
}
}

0
kernel/helpers/Debug.php Normal file → Executable file
View File

63
kernel/helpers/Files.php Normal file → Executable file
View File

@ -7,11 +7,13 @@ use ZipArchive;
class Files
{
public function copy_folder($d1, $d2): void
public function copy_folder($d1, $d2, int $permissions = 0775, bool $recursive = true): void
{
if (is_dir($d1)) {
if (!file_exists($d2)){
$_d2 = mkdir($d2, permissions: 0755, recursive: true);
$old_mask = umask(0);
$_d2 = mkdir($d2, permissions: $permissions, recursive: $recursive);
umask($old_mask);
if (!$_d2) {
return;
}
@ -26,6 +28,32 @@ class Files
$d->close();
} else {
copy($d1, $d2);
chmod($d2, permissions: $permissions);
}
}
public function copyKernelFolder($d1, $d2, int $permissions = 0775, bool $recursive = true): void
{
if (is_dir($d1)) {
if (!file_exists($d2)){
$old_mask = umask(0);
$_d2 = mkdir($d2, permissions: $permissions, recursive: $recursive);
umask($old_mask);
if (!$_d2) {
return;
}
}
$d = dir($d1);
while (false !== ($entry = $d->read())) {
if ($entry != '.' && $entry != '..' && $entry != 'app_modules') {
$this->copyKernelFolder("$d1/$entry", "$d2/$entry");
}
}
$d->close();
} else {
copy($d1, $d2);
chmod($d2, permissions: $permissions);
}
}
@ -43,13 +71,25 @@ class Files
rmdir($dir);
}
public function recursiveRemoveKernelDir(): void
{
$includes = new FilesystemIterator(KERNEL_DIR);
foreach ($includes as $include) {
if ($include->getFilename() === 'app_modules') continue;
if(is_dir($include) && !is_link($include)) {
$this->recursiveRemoveDir($include);
}
else {
unlink($include);
}
}
}
public function pack(string $source, string $destination/*, bool $include_source = true*/): void
{
$zip = new ZipArchive();
$zip->open($destination, ZipArchive::CREATE | ZipArchive::OVERWRITE);
// if ($include_source) {
// $zip->addEmptyDir(basename($source));
// }
if (is_file($source)) {
$zip->addFile(basename($source));
@ -62,20 +102,25 @@ class Files
$zip->close();
}
public static function uploadByUrl(string $url, string $uploadDir = RESOURCES_DIR . "/upload"): void
{
$file_name = basename($url);
file_put_contents($uploadDir . '/' . $file_name, file_get_contents($url));
}
private function recursiveAddFile(ZipArchive $zip, string $dir, string $folder = ''): void
{
$includes = new FilesystemIterator($dir);
foreach ($includes as $include) {
if(is_dir($include)) {
// $folder .= '/' . $include->getFilename() . '/';
// $this->recursiveAddFile($zip, $include, $folder);
if ($include->getFilename() === 'app_modules') continue;
$tmpFolder = $folder . '/' . $include->getFilename() . '/';
$tmpFolder = $folder . '/' . $include->getFilename();
$this->recursiveAddFile($zip, $include, $tmpFolder);
}
if (is_file($include)) {
$zip->addFile($include->getPathName(), $folder . $include->getFilename());
$zip->addFile($include->getPathName(), $folder . "/" . $include->getFilename());
}
}
}

42
kernel/helpers/Html.php Executable file
View File

@ -0,0 +1,42 @@
<?php
namespace kernel\helpers;
class Html
{
public static function img(string $src, array $params = [])
{
$paramsStr = self::createParams($params);
return "<img src='$src' $paramsStr>";
}
public static function h(string|int $type = 1, string $title = '', array $params = [])
{
$paramsStr = self::createParams($params);
return "<h$type $paramsStr>$title</h$type>";
}
public static function a(string $link, array $params = []): string
{
$paramsStr = self::createParams($params);
return "<a href='$link' $paramsStr>";
}
/**
* @param array $data
* @return string
*/
public static function createParams(array $data = []): string
{
$paramsString = "";
foreach($data as $key => $param){
if(is_string($param)){
$paramsString .= $key . "='" . $param . "'";
}
}
return $paramsString;
}
}

View File

@ -0,0 +1,48 @@
<?php
namespace kernel\helpers;
class ImageGD
{
public \GdImage $img;
public function __construct(string $resource = '', int $width = 200, int $height = 200)
{
if ($resource){
$this->img = imagecreatefrompng($resource);
}
else {
$this->img = imagecreatetruecolor($width, $height);
}
imagesavealpha($this->img, true);
}
public function addText(string $font_size, int $degree, int $x, int $y, string $color, string $font, string $text): void
{
$rgbArr = $this->hexToRgb($color);
$color = imagecolorallocate($this->img, $rgbArr[0], $rgbArr[1], $rgbArr[2]);
imagettftext($this->img, $font_size, $degree, $x, $y, $color, $font, $text);
}
public function addImg(\GdImage $gdImage, int $location_x, int $location_y, int $offset_src_x, int $offset_src_y, int $src_width, int $src_height, int $no_transparent): void
{
imagecopymerge($this->img, $gdImage, $location_x, $location_y, $offset_src_x, $offset_src_y, $src_width, $src_height, $no_transparent);
}
public function getImg()
{
return $this->img;
}
public function save(string $path): void
{
imagepng($this->img, $path);
imagedestroy($this->img);
}
protected function hexToRgb(string $hex)
{
return sscanf($hex, "#%02x%02x%02x");
}
}

0
kernel/helpers/Manifest.php Normal file → Executable file
View File

52
kernel/helpers/RESTClient.php Executable file
View File

@ -0,0 +1,52 @@
<?php
namespace kernel\helpers;
use GuzzleHttp\Exception\GuzzleException;
use http\Client;
class RESTClient
{
/**
* @throws GuzzleException
*/
public static function request(string $url, string $method = 'GET'): \Psr\Http\Message\ResponseInterface
{
$client = new \GuzzleHttp\Client();
return $client->request($method, $url, [
'headers' => [
'Authorization' => 'Bearer ' . $_ENV['MODULE_SHOP_TOKEN']
]
]);
}
/**
* @throws GuzzleException
*/
public static function request_without_auth(string $url, string $method = 'GET'): \Psr\Http\Message\ResponseInterface
{
$client = new \GuzzleHttp\Client();
return $client->request($method, $url);
}
/**
* @throws GuzzleException
*/
public static function post(string $url, array $data = [], bool $auth = true): \Psr\Http\Message\ResponseInterface
{
$headers = [];
if ($auth){
$headers = [
'Authorization' => 'Bearer ' . $_ENV['MODULE_SHOP_TOKEN']
];
}
$client = new \GuzzleHttp\Client();
return $client->request("POST", $url, [
'form_params' => $data,
'headers' => $headers,
]);
}
}

40
kernel/helpers/SMTP.php Executable file
View File

@ -0,0 +1,40 @@
<?php
namespace kernel\helpers;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
class SMTP
{
public PHPMailer $mail;
public function __construct()
{
$this->mail = new PHPMailer(true);
$this->mail->CharSet = 'UTF-8';
$this->mail->isSMTP();
$this->mail->SMTPAuth = true;
$this->mail->SMTPDebug = 0;
$this->mail->Host = $_ENV['MAIL_SMTP_HOST'];
$this->mail->Port = $_ENV['MAIL_SMTP_PORT'];
$this->mail->Username = $_ENV['MAIL_SMTP_USERNAME'];
$this->mail->Password = $_ENV['MAIL_SMTP_PASSWORD'];
}
/**
* @throws Exception
*/
public function send_html(array $params)
{
if (!isset($params['address'])){
return false;
}
$this->mail->setFrom($this->mail->Username, $params['from_name'] ?? $this->mail->Host);
$this->mail->addAddress($params['address']);
$this->mail->Subject = $params['subject'] ?? 'Без темы';
$body = $params['body'] ?? 'Нет информации';
$this->mail->msgHTML($body);
$this->mail->send();
}
}

4
kernel/helpers/Slug.php Normal file → Executable file
View File

@ -132,9 +132,9 @@ class Slug
* @param $model
* @return string
*/
public static function createSlug(string $title, $model = null): string
public static function createSlug(string $data, $model = null): string
{
$slug = Slug::url_slug($title, ['transliterate' => true, 'lowercase' => true]);
$slug = Slug::url_slug($data, ['transliterate' => true, 'lowercase' => true]);
if ($model === null) {
return $slug;
}

16
kernel/helpers/Version.php Executable file
View File

@ -0,0 +1,16 @@
<?php
namespace kernel\helpers;
class Version
{
public static function getIntVersionByString(string $version): int
{
$version = preg_replace('/[^0-9]+/', '', $version);
return match (strlen($version)) {
1 => intval($version) * 100,
2 => intval($version) * 10,
3 => intval($version),
};
}
}

8
kernel/manifest.json Executable file
View File

@ -0,0 +1,8 @@
{
"name": "Kernel",
"version": "0.1.5",
"author": "ITGuild",
"slug": "kernel",
"type": "kernel",
"description": "Kernel"
}

View File

@ -0,0 +1,19 @@
<?php
namespace kernel\middlewares;
use kernel\Middleware;
class AuthMiddleware extends Middleware
{
function handler()
{
if(!isset($_COOKIE['user_id']))
{
header('Location: /admin/login', true, 302);
return false;
}
}
}

0
kernel/models/Menu.php Normal file → Executable file
View File

0
kernel/models/Option.php Normal file → Executable file
View File

0
kernel/modules/admin_themes/AdminThemesModule.php Normal file → Executable file
View File

View File

0
kernel/modules/admin_themes/manifest.json Normal file → Executable file
View File

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