Powerful and easy to use cms to build websites, blogs or ecommerce stores.
HTML backendblogblog-engineblog-platformbloggingcmscontent-managementcontent-management-systemecommerceecommerce-platformno-codepage-builderphpphp-cmsphp7php8self-hostedshopping-cartweb-applicationwebsite-builder
Add admin tools: queue manager, database/media/plugins/themes backups
Givanf2b1be468d3f
diff --git a/admin/controller/order/subscription.php b/admin/controller/order/subscription.phpold mode 100644new mode 100755index 1b2c919..62ae796--- a/admin/controller/order/subscription.php+++ b/admin/controller/order/subscription.php@@ -24,19 +24,300 @@ namespace Vvveb\Controller\Order;use function Vvveb\__;use Vvveb\Controller\Crud;+use function Vvveb\model;+use Vvveb\System\SubscriptionManager;class Subscription extends Crud {- protected $type = 'subscription';+ protected string $type = 'subscription';- protected $controller = 'subscription';+ protected string $controller = 'subscription';- protected $module = 'order';+ protected string $module = 'order';- function index() {- parent :: index();+ /** Subscription status IDs matching the seed data. */+ public const STATUS_PENDING = 1;+ public const STATUS_ACTIVE = 2;+ public const STATUS_FAILED = 3;+ public const STATUS_CANCELLED = 4;+ public const STATUS_DENIED = 5;+ public const STATUS_EXPIRED = 6;- $this->view->period = ['day' => __('Day'), 'week' => __('Week'), 'month' => __('Month'), 'year' => __('Year')];- $this->view->trial_period = $this->view->period;- $this->view->trial_status = $this->view->status;+ /**+ * Display the subscription edit form with period, trial, status, and log data.+ *+ * @return void+ */+ public function index(): void {+ parent::index();++ $this->view->period = ['day' => __('Day'), 'week' => __('Week'), 'month' => __('Month'), 'year' => __('Year')];+ $this->view->trial_period = $this->view->period;++ //load subscription statuses+ $statusModel = model('subscription_status');+ $statuses = $statusModel->getAll(['language_id' => $this->global['language_id'] ?? 1] + $this->global);+ $statusOptions = [];++ if (isset($statuses['subscription_status'])) {+ foreach ($statuses['subscription_status'] as $status) {+ $statusOptions[$status['subscription_status_id']] = $status['name'];+ }+ }++ $this->view->subscription_status = $statusOptions;++ //load subscription logs for the current subscription+ $subscriptionId = $this->request->get['subscription_id'] ?? false;++ if ($subscriptionId) {+ $this->loadLogs($subscriptionId);+ }+ }++ /**+ * Load subscription history logs and pass them to the view.+ *+ * @param int|string $subscriptionId+ *+ * @return void+ */+ private function loadLogs(int|string $subscriptionId): void {+ $logModel = model('subscription_log');+ $logs = $logModel->getAll([+ 'subscription_id' => $subscriptionId,+ 'language_id' => $this->global['language_id'] ?? 1,+ ] + $this->global);++ $this->view->subscription_logs = $logs['subscription_log'] ?? [];+ }++ /**+ * Change the subscription status and record a log entry.+ *+ * @param int $statusId Target subscription_status_id.+ * @param string $note Optional note for the log entry.+ *+ * @return void+ */+ protected function changeStatus(int $statusId, string $note = ''): void {+ $this->checkCsrf();++ $subscriptionId = $this->request->get['subscription_id'] ?? false;++ if (!$subscriptionId) {+ $this->view->errors[] = __('Subscription ID is required!');++ return;+ }++ $model = model($this->type);+ $result = $model->edit([+ 'subscription' => [+ 'subscription_status_id' => $statusId,+ 'updated_at' => date('Y-m-d H:i:s'),+ ],+ 'subscription_id' => $subscriptionId,+ ] + $this->global);++ if ($result) {+ //record log entry+ $logModel = model('subscription_log');+ $logModel->add([+ 'subscription_log' => [+ 'subscription_id' => $subscriptionId,+ 'subscription_status_id' => $statusId,+ 'notify' => 1,+ 'note' => $note,+ 'created_at' => date('Y-m-d H:i:s'),+ ],+ ] + $this->global);++ $this->view->success[] = __('Subscription status updated!');+ } else {+ $this->view->errors[] = __('Error updating subscription status!');+ }+ }++ /**+ * Load a subscription row with its original order (if any).+ *+ * @param int|string $subscriptionId Subscription id.+ *+ * @return array{0: array<string, mixed>|null, 1: array<string, mixed>|null} [subscription, order].+ */+ private function loadSubscription(int|string $subscriptionId): array {+ $subscription = null;+ $order = null;++ try {+ $result = model('subscription')->get([+ 'subscription_id' => $subscriptionId,+ 'language_id' => $this->global['language_id'] ?? 1,+ ] + $this->global);++ if (is_array($result) && (isset($result['subscription_id']) || isset($result['subscription']))) {+ $subscription = $result['subscription'] ?? $result;+ }+ } catch (\Throwable $e) {+ }++ if ($subscription && !empty($subscription['order_id'])) {+ try {+ $orderResult = model('order')->get(['order_id' => (int)$subscription['order_id']] + $this->global);+ $order = $orderResult['order'] ?? null;+ } catch (\Throwable $e) {+ }+ }++ return [$subscription, $order];+ }++ /**+ * Run a gateway lifecycle operation before changing local status.+ *+ * The local status only changes when there is no gateway provisioning+ * or the gateway call succeeded; gateway failures are shown and the+ * local status is left untouched.+ *+ * @param string $operation Gateway operation (cancelSubscription, ...).+ * @param int $statusId Target local status on success.+ * @param string $note Log note.+ *+ * @return void+ */+ private function applyLifecycle(string $operation, int $statusId, string $note): void {+ //lifecycle actions propagate to the live gateway: never accept plain GET links+ if ($this->request->getMethod() !== 'post') {+ $this->view->errors[] = __('Invalid request!');+ $this->index();++ return;+ }++ $subscriptionId = $this->request->get['subscription_id'] ?? $this->request->post['subscription_id'] ?? false;++ if ($subscriptionId) {+ [$subscription, $order] = $this->loadSubscription($subscriptionId);++ if ($subscription && ($error = SubscriptionManager::gatewayOperation($operation, $subscription, $order))) {+ $this->view->errors[] = $error;+ $this->index();++ return;+ }+ }++ $this->changeStatus($statusId, $note);+ $this->index();+ }++ /**+ * Cancel the subscription.+ *+ * @return void+ */+ public function cancel(): void {+ $note = $this->request->post['note'] ?? __('Cancelled by admin');+ $this->applyLifecycle('cancelSubscription', self::STATUS_CANCELLED, $note);+ }++ /**+ * Pause the subscription (set to pending).+ *+ * @return void+ */+ public function pause(): void {+ $note = $this->request->post['note'] ?? __('Paused by admin');+ $this->applyLifecycle('pauseSubscription', self::STATUS_PENDING, $note);+ }++ /**+ * Resume/activate the subscription.+ *+ * @return void+ */+ public function resume(): void {+ $note = $this->request->post['note'] ?? __('Resumed by admin');+ $this->applyLifecycle('resumeSubscription', self::STATUS_ACTIVE, $note);+ }++ /**+ * Mark subscription as expired.+ *+ * For gateway-provisioned active subscriptions billing stops at the end+ * of the current term instead of immediately; the gateway webhook flips+ * the local status to cancelled when the term actually ends. Rows that+ * already ended (or were never provisioned) expire locally only.+ *+ * @return void+ */+ public function expire(): void {+ $note = $this->request->post['note'] ?? __('Expired by admin');++ if ($this->request->getMethod() !== 'post') {+ $this->view->errors[] = __('Invalid request!');+ $this->index();++ return;+ }++ $subscriptionId = $this->request->get['subscription_id'] ?? $this->request->post['subscription_id'] ?? false;++ if ($subscriptionId) {+ [$subscription, $order] = $this->loadSubscription($subscriptionId);+ $statusId = (int)($subscription['subscription_status_id'] ?? 0);++ if ($subscription && in_array($statusId, [self::STATUS_PENDING, self::STATUS_ACTIVE], true)) {+ if ($error = SubscriptionManager::gatewayOperation('cancelSubscription', $subscription, $order, ['at_period_end' => true])) {+ $this->view->errors[] = $error;+ $this->index();++ return;+ }++ $note .= ' ' . __('(billing ends at term end)');+ }+ }++ $this->changeStatus(self::STATUS_EXPIRED, $note);+ $this->index();+ }++ /**+ * Add a log/note entry to a subscription without changing status.+ *+ * @return void+ */+ public function addLog(): void {+ $this->checkCsrf();++ $subscriptionId = $this->request->get['subscription_id'] ?? false;+ $note = $this->request->post['note'] ?? '';+ $statusId = (int)($this->request->post['subscription_status_id'] ?? 0);++ if (!$subscriptionId || !$note) {+ $this->view->errors[] = __('Subscription ID and note are required!');++ return;+ }++ $logModel = model('subscription_log');+ $result = $logModel->add([+ 'subscription_log' => [+ 'subscription_id' => $subscriptionId,+ 'subscription_status_id' => $statusId ?: self::STATUS_ACTIVE,+ 'notify' => 0,+ 'note' => $note,+ 'created_at' => date('Y-m-d H:i:s'),+ ],+ ] + $this->global);++ if ($result) {+ $this->view->success[] = __('Log entry added!');+ } else {+ $this->view->errors[] = __('Error adding log entry!');+ }++ $this->index();}}diff --git a/admin/controller/order/subscriptions.php b/admin/controller/order/subscriptions.phpold mode 100755new mode 100644index 71a63ff..57a8a7c--- a/admin/controller/order/subscriptions.php+++ b/admin/controller/order/subscriptions.php@@ -25,15 +25,16 @@ namespace Vvveb\Controller\Order;use Vvveb\Controller\Listing;class Subscriptions extends Listing {- protected $additionalPermissionCheck = ['order/subscription/save'];-- protected $type = 'subscription';+ /** @var list<string> */+ protected ?array $additionalPermissionCheck = ['order/subscription/save'];- protected $controller = 'subscription';+ protected string $type = 'subscription';- protected $listController = 'subscriptions';+ protected string $controller = 'subscription';- protected $list = 'subscription';+ protected string $listController = 'subscriptions';- protected $module = 'order';+ protected string $list = 'subscription';++ protected string $module = 'order';}diff --git a/admin/controller/order/warehouse.php b/admin/controller/order/warehouse.phpnew file mode 100644index 0000000..04ea086--- /dev/null+++ b/admin/controller/order/warehouse.php@@ -0,0 +1,90 @@+<?php++/**+ * Vvveb+ *+ * Copyright (C) 2022 Ziadin Givan+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ */++namespace Vvveb\Controller\Order;++use function Vvveb\__;+use Vvveb\Controller\Crud;+use Vvveb\Sql\CountrySQL;+use Vvveb\Sql\RegionSQL;+use Vvveb\Sql\WarehouseSQL;++class Warehouse extends Crud {+ protected string $type = 'warehouse';++ protected string $controller = 'warehouse';++ protected string $module = 'order';++ /**+ * Save the warehouse and its assigned products.+ *+ * @return void+ */+ public function save(): void {+ parent::save();++ $post = &$this->request->post;+ $get = &$this->request->get;+ $warehouse_id = $post['warehouse_id'] ?? $get['warehouse_id'] ?? $this->warehouse_id ?? false;+ $products = $post['warehouse_product'] ?? [];++ if ($warehouse_id && $products) {+ $warehouseSQL = new WarehouseSQL();+ $warehouseSQL->setProducts(['warehouse_product' => $products, 'warehouse_id' => $warehouse_id]);+ }++ $this->index();+ }++ /**+ * Display the warehouse edit form with countries, regions and products.+ *+ * @return void+ */+ public function index(): void {+ parent::index();++ $get = &$this->request->get;+ $warehouse_id = $get['warehouse_id'] ?? false;++ $warehouseSQL = new WarehouseSQL();+ $this->view->warehouse += $warehouseSQL->getProducts(['warehouse_id' => $warehouse_id] + $this->global) ?? [];++ $options = [+ 'language_id' => $this->global['language_id'] ?? 1,+ 'status' => 1,+ ];++ $countryModel = new CountrySQL();+ $country = $countryModel->getAll($options);+ $this->view->countries = $country['country'] ?? [];++ $country_id = $this->view->warehouse['country_id'] ?? ($this->view->countries[0]['country_id'] ?? 0);++ $regionModel = new RegionSQL();+ $regions = $regionModel->getAll($options + ['country_id' => $country_id]);+ $this->view->regions = $regions['region'] ?? [];++ $this->view->status = ['0' => __('Disabled'), '1' => __('Enabled')];+ }+}diff --git a/admin/controller/order/warehouses.php b/admin/controller/order/warehouses.phpnew file mode 100644index 0000000..8c130f4--- /dev/null+++ b/admin/controller/order/warehouses.php@@ -0,0 +1,37 @@+<?php++/**+ * Vvveb+ *+ * Copyright (C) 2022 Ziadin Givan+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ */++namespace Vvveb\Controller\Order;++use Vvveb\Controller\Listing;++class Warehouses extends Listing {+ protected string $type = 'warehouse';++ protected string $controller = 'warehouse';++ protected string $listController = 'warehouses';++ protected string $list = 'warehouse';++ protected string $module = 'order';+}diff --git a/admin/controller/tools/backup.php b/admin/controller/tools/backup.phpold mode 100644new mode 100755index f887ccd..004e578--- a/admin/controller/tools/backup.php+++ b/admin/controller/tools/backup.php@@ -163,7 +163,7 @@ class Backup extends Base {$i = 0;foreach ($rows as $row) {- array_walk($row, function (&$v) {+ array_walk($row, function(&$v): void {if (is_null($v)) {$v = 'null';} else {@@ -263,6 +263,10 @@ class Backup extends Base {* @return void*/public function nextRestore(): void {+ if ($this->request->getMethod() !== 'post') {+ $this->notFound(__('Invalid request method!'), 405);+ }+$position = $this->request->get['position'] ?? 0;$file = sanitizeFileName($this->request->get['file'] ?? '');$filename = $this->dirBackup . $file;diff --git a/admin/controller/tools/cache.php b/admin/controller/tools/cache.phpold mode 100755new mode 100644index ee445df..cd59143--- a/admin/controller/tools/cache.php+++ b/admin/controller/tools/cache.php@@ -27,49 +27,92 @@ use Vvveb\Controller\Base;use Vvveb\System\CacheManager;class Cache extends Base {- private function clear($fn) {+ /**+ * Execute a cache clearing operation and display the result.+ *+ * @param callable(): bool $fn The cache clearing function to execute.+ *+ * @return void+ */+ private function clear(callable $fn): void {if ($fn()) {$this->view->success[] = __('Cache deleted!');} else {$this->view->errors[] = __('Error purging cache!');}- return $this->index();+ $this->index();}- function delete() {- return $this->clear(fn () => CacheManager :: delete());+ /**+ * Delete all cache types.+ *+ * @return void+ */+ public function delete(): void {+ $this->clear(fn () => CacheManager :: delete());}- function template() {- return $this->clear(fn () => CacheManager :: clearCompiledFiles());+ /**+ * Clear compiled template cache.+ *+ * @return void+ */+ public function template(): void {+ $this->clear(fn () => CacheManager :: clearCompiledFiles());}- function page() {- return $this->clear(fn () => CacheManager :: clearPageCache($this->global['site_url']));+ /**+ * Clear page cache.+ *+ * @return void+ */+ public function page(): void {+ $this->clear(fn () => CacheManager :: clearPageCache($this->global['site_url']));}- function database() {- return $this->clear(fn () => CacheManager :: clearObjectCache());+ /**+ * Clear database object cache.+ *+ * @return void+ */+ public function database(): void {+ $this->clear(fn () => CacheManager :: clearObjectCache());}- function asset() {- return $this->clear(fn () => CacheManager :: clearFrontend());+ /**+ * Clear frontend asset cache.+ *+ * @return void+ */+ public function asset(): void {+ $this->clear(fn () => CacheManager :: clearFrontend());}- function model() {- return $this->clear(fn () => CacheManager :: clearModelCache());+ /**+ * Clear model cache.+ *+ * @return void+ */+ public function model(): void {+ $this->clear(fn () => CacheManager :: clearModelCache());}- function image() {- return $this->clear(fn () => CacheManager :: clearImageCache());+ /**+ * Clear image cache.+ *+ * @return void+ */+ public function image(): void {+ $this->clear(fn () => CacheManager :: clearImageCache());}- function stale() {- return $this->index();- }-- function index() {+ /**+ * Display the cache management page with folder writability checks.+ *+ * @return void+ */+ public function index(): void {$folders = ['/public/page-cache' => DIR_PUBLIC . PAGE_CACHE_DIR,'/public/image-cache' => DIR_PUBLIC . DS . 'image-cache',@@ -81,7 +124,7 @@ class Cache extends Base {$unwritable = [];foreach ($folders as $folder => $path) {- if (! is_writable($path)) {+ if (!is_writable($path)) {$unwritable[] = $folder;}}diff --git a/admin/controller/tools/cron.php b/admin/controller/tools/cron.phpindex c727854..c3cc8da 100755--- a/admin/controller/tools/cron.php+++ b/admin/controller/tools/cron.php@@ -28,7 +28,12 @@ use Vvveb\System\Cron as CronList;use Vvveb\System\Sites;class Cron extends Base {- function index() {+ /**+ * Display the cron job management page with cron URL and CLI command.+ *+ * @return void+ */+ public function index(): void {$view = View :: getInstance();$site = Sites::getSiteById($this->global['site_id']);diff --git a/admin/controller/tools/errorlog.php b/admin/controller/tools/errorlog.phpindex 8b62d9f..b5d1c0f 100755--- a/admin/controller/tools/errorlog.php+++ b/admin/controller/tools/errorlog.php@@ -26,11 +26,26 @@ use function Vvveb\__;use Vvveb\Controller\Base;class ErrorLog extends Base {- function download() {- $filename = ini_get('error_log');+ /**+ * Download the PHP error log file as a plain text attachment.+ *+ * @return void+ */+ public function download(): void {+ $log = $this->request->get['log'] ?? 'error_log';+ $filename = '';++ switch ($log) {+ case 'error_log':+ $filename = ini_get('error_log');+ break;+ case 'mail_log':+ $filename = DIR_STORAGE . 'logs/mail_log';+ break;+ }if (is_file($filename)) {- $fp = fopen($filename, 'rb');+ $fp = fopen($filename, 'r');header('Content-Description: File Transfer');//header('Content-Type: application/octet-stream');@@ -47,12 +62,27 @@ class ErrorLog extends Base {} else {$this->view->errors[] = __('Error downloading log!');- return $this->index();+ $this->index();}}- function clear() {- $filename = ini_get('error_log');+ /**+ * Clear the PHP error log file contents.+ *+ * @return void+ */+ public function clear(): void {+ $log = $this->request->get['log'] ?? 'error_log';+ $filename = '';++ switch ($log) {+ case 'error_log':+ $filename = ini_get('error_log');+ break;+ case 'mail_log':+ $filename = DIR_STORAGE . 'logs/mail_log';+ break;+ }if (is_file($filename)) {@$handle = fopen($filename, 'r+');@@ -71,16 +101,31 @@ class ErrorLog extends Base {$this->view->errors[] = __('Log not a valid file!');}- return $this->index();+ $this->index();}- function index() {+ /**+ * Display the last lines of the PHP error log.+ *+ * @return void+ */+ public function index(): void {+ $name = $this->request->get['log'] ?? 'error_log';$count = 100;- $error_log = ini_get('error_log');$is_readable = null;$text = null;+ $error_log = '';++ switch ($name) {+ case 'error_log':+ $error_log = ini_get('error_log');+ break;+ case 'mail_log':+ $error_log = DIR_STORAGE . 'logs/mail_log';+ break;+ }- if (! empty($error_log)) {+ if (!empty($error_log)) {$is_readable = is_readable($error_log);if ($is_readable) {diff --git a/admin/controller/tools/export.php b/admin/controller/tools/export.phpindex 902a9e7..e234007 100755--- a/admin/controller/tools/export.php+++ b/admin/controller/tools/export.php@@ -29,12 +29,26 @@ use Vvveb\System\Extensions\Themes;use Vvveb\System\Import\Xml;class Export extends Base {- function __construct() {+ /**+ * Initialize the XML exporter.+ *+ * @return void+ */+ public function __construct() {$this->xml = new Xml();}- function export() {- $tables = $this->request->post['table'];+ /**+ * Export selected database tables as XML and download the file.+ *+ * @return void+ */+ public function export(): void {+ $tables = (array)($this->request->post['table'] ?? []);++ //only allow real table names, they are interpolated into the dump queries+ $known = $this->xml->getTableNames();+ $tables = array_values(array_intersect($tables, $known));$xml = new Xml();$xmlData = $xml->export($tables);@@ -44,14 +58,20 @@ class Export extends Base {echo $xmlData;- die();+ exit();}- private function namespaceTree() {+ /**+ * Build a namespaced tree structure of database tables.+ *+ * @return array<string, array<string, string>> Namespaced table tree.+ */+ private function namespaceTree(): array {$tableNames = $this->xml->getTableNames();+ $namespaces = [];foreach ($tableNames as $tableName) {- $pos = strpos($tableName,'_');+ $pos = strpos($tableName, '_');$namespace = substr($tableName, 0, $pos);if ($namespace) {@@ -76,9 +96,14 @@ class Export extends Base {return $namespaces;}- function index() {+ /**+ * Display the export page with available namespaces, plugins, and themes.+ *+ * @return void+ */+ public function index(): void {$this->view->namespaces = $this->namespaceTree();- $this->view->plugins = Plugins::getList(null);- $this->view->themes = Themes::getList(null);+ $this->view->plugins = Plugins::getList();+ $this->view->themes = Themes::getList();}}diff --git a/admin/controller/tools/import.php b/admin/controller/tools/import.phpold mode 100755new mode 100644index 3974b67..c3782ad--- a/admin/controller/tools/import.php+++ b/admin/controller/tools/import.php@@ -24,15 +24,31 @@ namespace Vvveb\Controller\Tools;use function Vvveb\__;use Vvveb\Controller\Base;+use Vvveb\System\Core\FrontController;+use Vvveb\System\Import\Sql;use Vvveb\System\Import\Xml;#[\AllowDynamicProperties]class Import extends Base {- function __construct() {+ /**+ * Initialize the XML and SQL importers.+ *+ * @return void+ */+ public function __construct() {$this->xml = new Xml();+ $this->sql = new Sql();}- function importFile($file, $name = '') {+ /**+ * Import a single file and display success or error messages.+ *+ * @param string $file The temporary file path to import.+ * @param string $name The original file name.+ *+ * @return void+ */+ public function importFile(string $file, string $name = ''): void {$result = false;if ($file) {@@ -54,7 +70,12 @@ class Import extends Base {}}- function upload() {+ /**+ * Handle file uploads and process each uploaded or specified file.+ *+ * @return void+ */+ public function upload(): void {$files = $this->request->files;//check for uploaded files@@ -77,10 +98,18 @@ class Import extends Base {}}- return $this->index();+ $this->index();}- private function import($file, $name = '') {+ /**+ * Import a file based on its extension (xml or sql).+ *+ * @param string $file The file path to import.+ * @param string $name The file name used to determine the import type.+ *+ * @return bool True if import succeeded, false otherwise.+ */+ private function import(string $file, string $name = ''): bool {$extension = substr($name, -3, 3);$result = false;@@ -90,10 +119,24 @@ class Import extends Base {$result = $this->xml->import($content);}+ if ($extension == 'sql') {+ /*+ $content = file_get_contents($file);+ $result = $this->sql->multiQuery($content, $file);+ */+ //use database backup restore+ FrontController::redirect('tools/backup', 'restore');+ }+return $result;}- function index() {+ /**+ * Display the import page.+ *+ * @return void+ */+ public function index(): void {//$this->import();}}diff --git a/admin/controller/tools/queue.php b/admin/controller/tools/queue.phpnew file mode 100755index 0000000..afa11b5--- /dev/null+++ b/admin/controller/tools/queue.php@@ -0,0 +1,209 @@+<?php++/**+ * Vvveb+ *+ * Copyright (C) 2022 Ziadin Givan+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ */++namespace Vvveb\Controller\Tools;++use function Vvveb\__;+use function Vvveb\config;+use Vvveb\Controller\Base;+use function Vvveb\setConfig;+use Vvveb\System\Queue as QueueApi;+use Vvveb\System\Sites;++class Queue extends Base {+ /**+ * Display queue monitoring page: provider info, worker commands,+ * per-queue stats and failed jobs list.+ *+ * @return void+ */+ public function index(): void {+ $providerName = QueueApi::providerName();+ $config = config('queue', []);+ $queues = $config['queues'] ?? ['default'];++ if (!in_array('default', $queues)) {+ $queues[] = 'default';+ }++ try {+ foreach ($queues as $queue) {+ $this->view->queueStats[$queue] = QueueApi::stats($queue);+ }+ } catch (\Throwable $e) {+ $this->view->errors[] = sprintf(__('Error connecting to queue provider: %s'), $e->getMessage());+ $this->view->queueStats = [];+ }++ try {+ $this->view->failedJobs = QueueApi::failedJobs(null, 100);+ $this->view->failedCount = count($this->view->failedJobs);+ } catch (\Throwable $e) {+ $this->view->failedJobs = [];+ $this->view->failedCount = 0;+ }++ $site = Sites::getSiteById($this->global['site_id'] ?? 1);+ $this->view->cronkey = \Vvveb\getConfig('app.cronkey');+ $this->view->worker_cli = 'php ' . DIR_ROOT . 'cli.php queue:work --queue=default --sleep=1 --max-jobs=0';+ $this->view->drain_cli = 'php ' . DIR_ROOT . 'cli.php queue:work --drain=1';+ $this->view->cron_url = ($site['url'] ?? '') . '/run-cron/' . $this->view->cronkey;++ $this->view->config = $config;+ $this->view->provider = $providerName;+ $this->view->providers = [+ 'database' => [+ 'name' => __('Database'),+ 'available' => true,+ 'note' => __('Reuses the site database connection. Driver auto-detected: PostgreSQL, MySQL/MariaDB or SQLite.'),+ ],+ 'redis' => [+ 'name' => __('Redis'),+ 'available' => class_exists('\Redis'),+ 'note' => __('Requires the phpredis extension. Recommended for multiple workers and higher throughput.'),+ ],+ ];+ $this->view->driverLabel = match (DB_ENGINE) {+ 'pgsql' => __('PostgreSQL'),+ 'sqlite' => __('SQLite'),+ default => __('MySQL / MariaDB'),+ };+ }++ /**+ * Save queue settings (provider selection + retry options).+ *+ * @return void+ */+ public function save(): void {+ $settings = $this->request->post['settings'] ?? null;++ if ($settings && is_array($settings)) {+ $current = config('queue', []);++ $provider = $settings['default'] ?? 'database';++ if (!in_array($provider, ['database', 'redis'])) {+ $provider = 'database';+ }++ $current['default'] = $provider;+ $current['max_attempts'] = max(1, (int)($settings['max_attempts'] ?? 3));+ $current['retry']['base_delay_seconds'] = max(1, (int)($settings['retry']['base_delay_seconds'] ?? 30));+ $current['retry']['max_delay_seconds'] = max(1, (int)($settings['retry']['max_delay_seconds'] ?? 3600));+ $current['reserved_timeout_seconds'] = max(10, (int)($settings['reserved_timeout_seconds'] ?? 300));+ $current['cron_pass']['enabled'] = !empty($settings['cron_pass']['enabled']);++ if (setConfig('queue', $current)) {+ $this->view->success[] = __('Settings saved!');+ } else {+ $this->view->errors[] = __('Error saving!');+ }+ } else {+ $this->view->errors[] = __('Invalid settings data!');+ }++ $this->index();+ }++ /**+ * Retry a single failed job.+ *+ * @return void+ */+ public function retry(): void {+ $jobId = $this->request->post['job_id'] ?? '';++ if ($jobId && QueueApi::retryFailedJob((string)$jobId)) {+ $this->view->success[] = __('Job queued for retry!');+ } else {+ $this->view->errors[] = __('Error retrying job!');+ }++ $this->index();+ }++ /**+ * Retry all failed jobs (bulk action).+ *+ * @return void+ */+ public function retryAll(): void {+ if ($this->request->getMethod() !== 'post') {+ $this->notFound(__('Invalid request method!'), 405);+ }++ $count = 0;++ foreach (QueueApi::failedJobs() as $job) {+ if (QueueApi::retryFailedJob((string)$job['id'])) {+ $count++;+ }+ }++ if ($count > 0) {+ $this->view->success[] = sprintf(__('%d jobs queued for retry!'), $count);+ } else {+ $this->view->errors[] = __('No failed jobs to retry!');+ }++ $this->index();+ }++ /**+ * Delete a single failed job.+ *+ * @return void+ */+ public function delete(): void {+ $jobId = $this->request->post['job_id'] ?? '';++ if ($jobId && QueueApi::deleteFailedJob((string)$jobId)) {+ $this->view->success[] = __('Failed job deleted!');+ } else {+ $this->view->errors[] = __('Error deleting job!');+ }++ $this->index();+ }++ /**+ * Delete all failed jobs (bulk action).+ *+ * @return void+ */+ public function clearFailed(): void {+ if ($this->request->getMethod() !== 'post') {+ $this->notFound(__('Invalid request method!'), 405);+ }++ $count = QueueApi::clearFailedJobs();++ if ($count > 0) {+ $this->view->success[] = sprintf(__('%d failed jobs deleted!'), $count);+ } else {+ $this->view->errors[] = __('No failed jobs to delete!');+ }++ $this->index();+ }+}diff --git a/admin/controller/tools/search.php b/admin/controller/tools/search.phpold mode 100644new mode 100755index 0ef5535..6105bcc--- a/admin/controller/tools/search.php+++ b/admin/controller/tools/search.php@@ -25,24 +25,33 @@ namespace Vvveb\Controller\Tools;use function Vvveb\__;use Vvveb\Controller\Base;use function Vvveb\htmlToText;+use Vvveb\System\Extensions\Plugins;use Vvveb\System\Images;use function Vvveb\truncateWords;use function Vvveb\url;-class Search extends Base {- private function searchMenu($text, &$results, &$menu) {+ /**+ * Recursively search the admin menu for matching items.+ *+ * @param string $text The search text to match.+ * @param array<array-key, array<string, mixed>> $results Found results (passed by reference).+ * @param array<int|string, mixed> $menu The menu array to search through.+ *+ * @return array<array-key, array<string, mixed>> The updated results array.+ */+ private function searchMenu(string $text, array &$results, array $menu): array {foreach ($menu as $key => $value) {if (isset($value['heading'])) {continue;}- if (isset($value['name']) && (stripos($value['name'], $text) !== false)) {+ if (isset($value['name']) && is_string($value['name']) && (stripos($value['name'], $text) !== false)) {$results[$value['name']] = [- 'icon' => $value['icon'] ?? '',- 'icon-img' => $value['icon-img'] ?? '',- 'text' => $value['name'],- 'url' => $value['url'],+ 'icon' => $value['icon'] ?? '',+ 'icon-img' => $value['icon-img'] ?? '',+ 'text' => $value['name'],+ 'url' => $value['url'],];}@@ -54,8 +63,13 @@ class Search extends Base {return $results;}- function index() {- $text = $this->request->get['search'] ?? '';+ /**+ * Perform a global search across products, posts, users, categories, menu, pages and plugins.+ *+ * @return void+ */+ public function index(): void {+ $text = $this->request->get['search'] ?? '';$type = $this->request->get['type'] ?? '';$this->view->search = $text;@@ -63,6 +77,7 @@ class Search extends Base {if (strlen($text) < 3) {$this->view->search = [];+return;}@@ -82,14 +97,13 @@ class Search extends Base {$key = __('product');foreach ($results['product'] as $product) {$product['image'] = Images::image($product['image'], 'product', 'thumb');- $url = url(['module' => 'product/product', 'slug'=> $product['slug'], 'product_id' => $product['product_id'], 'type' => $product['type']]);+ $url = url(['module' => 'product/product', 'slug' => $product['slug'], 'product_id' => $product['product_id'], 'type' => $product['type']]);$search[$key][] = [- 'type' => 'cardimage',- 'src' => $product['image'],- 'text' => $product['name'],+ 'src' => $product['image'],+ 'text' => $product['name'],'description' => htmlToText(truncateWords($product['excerpt'] ?? $product['content'], 50)),- 'url' => $url,+ 'url' => $url,];}}@@ -102,14 +116,13 @@ class Search extends Base {$key = __('post');foreach ($results['post'] as $post) {$post['image'] = Images::image($post['image'], 'post', 'thumb');- $url = url(['module' => 'content/post', 'slug'=> $post['slug'], 'post_id' => $post['post_id'], 'type' => $post['type']]);+ $url = url(['module' => 'content/post', 'slug' => $post['slug'], 'post_id' => $post['post_id'], 'type' => $post['type']]);$search[$key][] = [- 'type' => 'cardimage',- 'src' => $post['image'],- 'text' => $post['name'],+ 'src' => $post['image'],+ 'text' => $post['name'],'description' => htmlToText(truncateWords($post['excerpt'] ?? $post['content'], 50)),- 'url' => $url,+ 'url' => $url,];}}@@ -123,45 +136,43 @@ class Search extends Base {foreach ($results['user'] as $user) {$url = url(['module' => 'user/user', 'user_id' => $user['user_id']]);if (isset($user['avatar'])) {- $user['image']= Images::image($user['avatar'], 'user');+ $user['image'] = Images::image($user['avatar'], 'user');}-$search[$key][] = [- 'type' => 'cardimage',- 'src' => $user['image'],- 'text' => $user['first_name'] . ' ' . $user['last_name'] . ' (' . $user['username'] . ') ' . $user['email'],- 'url' => $url,+ 'src' => $user['image'],+ 'text' => $user['first_name'] . ' ' . $user['last_name'],+ 'description' => '(' . $user['username'] . ') ' . $user['email'],+ 'url' => $url,];}}$categories = new \Vvveb\Sql\CategorySQL();- $results = $categories->getCategories($options + ['search' => $text]);+ $results = $categories->getCategories($options + ['search' => $text]);if (isset($results['categories'])) {$key = __('taxonomy');foreach ($results['categories'] as $category) {$url = url(['module' => 'content/categories', 'taxonomy_id' => $category['taxonomy_id']]);if (isset($category['avatar'])) {- $category['image']= Images::image($category['avatar'], 'category');+ $category['image'] = Images::image($category['avatar'], 'category');}$search[$key][] = [- 'type' => 'cardimage',- 'src' => $category['image'],- 'text' => $category['name'],+ 'src' => $category['image'],+ 'text' => $category['name'],'description' => htmlToText(truncateWords($category['content'], 50)),- 'url' => $url,+ 'url' => $url,];}}- $results = [];- $this->searchMenu($text, $results, $this->view->menu);+ $menuResults = [];+ $this->searchMenu($text, $menuResults, $this->view->menu);- if ($results) {- $search[__('Settings')] = $results;+ if ($menuResults) {+ $search[__('Settings')] = $menuResults;}$pages = [@@ -178,20 +189,34 @@ class Search extends Base {$key = __('pages');foreach ($pages as $route => $name) {if (stripos($name, $text) !== false) {- $url = url($route);+ $url = url($route);$search[$key][$url] = [- 'icon' => 'la la-external-link-alt',+ 'icon' => 'la la-external-link-alt','text' => $name,- 'url' => $url,+ 'url' => $url,];break;}}- $this->view->search = $search;- }+ $plugins = Plugins :: getList($this->global['site_id']);+ $pluginsUrl = url(['module' => 'plugin/plugins']);+ $key = __('plugins');+ foreach ($plugins as $plugin) {+ if (stripos($plugin['name'] ?? '', $text) !== false ||+ stripos($plugin['description'] ?? '', $text) !== false) {+ $search[$key][$plugin['slug']] = [+ 'src' => $plugin['thumb_url'],+ 'text' => $plugin['name'],+ 'description' => $plugin['description'],+ 'url' => $plugin['settings'] ?? ($pluginsUrl . '#plugin-' . $plugin['slug'])+ ];++ break;+ }+ }- function autocomplete() {+ $this->view->search = $search;}}diff --git a/admin/controller/tools/security.php b/admin/controller/tools/security.phpindex 8d7715e..20d46f6 100755--- a/admin/controller/tools/security.php+++ b/admin/controller/tools/security.php@@ -25,15 +25,10 @@ namespace Vvveb\Controller\Tools;use Vvveb\Controller\Base;class Security extends Base {- function index() {- $info = [- 'general' => [- 'PHP version' => phpversion(),- 'OS version' => php_uname(),- 'Database driver & version' => DB_ENGINE,- ],- ];-- $this->view->info = $info;- }+ /**+ * Display the security settings page.+ *+ * @return void+ */+ public function index(): void {}}diff --git a/admin/controller/tools/systeminfo.php b/admin/controller/tools/systeminfo.phpindex 9c47090..687558b 100755--- a/admin/controller/tools/systeminfo.php+++ b/admin/controller/tools/systeminfo.php@@ -25,9 +25,15 @@ namespace Vvveb\Controller\Tools;use function Vvveb\__;use Vvveb\Controller\Base;use Vvveb\System\Event;+use Vvveb\System\Media\Image;class SystemInfo extends Base {- function index() {+ /**+ * Display system information including PHP, server, database, and extension details.+ *+ * @return void+ */+ public function index(): void {$database = DB_ENGINE;if (DB_ENGINE == 'mysqli') {@@ -47,40 +53,45 @@ class SystemInfo extends Base {$database .= ' | ' . sprintf(__('Server version: %s'), $info);}- (extension_loaded('imagick') && $imageLibrary = 'imagick') ||- (extension_loaded('gd') && $imageLibrary = 'gd') ||- ($imageLibrary = 'mockup (Imagick or GD not enabled!)');+ $imageLibrary = 'mockup (Imagick or GD not enabled!)';++ if (extension_loaded('imagick')) {+ $imageLibrary = 'imagick';+ } elseif (extension_loaded('gd')) {+ $imageLibrary = 'gd';+ }$objectcache = \Vvveb\getConfig('app.cache.driver');- $objectcache .= ($objectcache != 'file' && ! extension_loaded($objectcache)) ? ' extension not available!' : '';+ $objectcache .= ($objectcache != 'file' && !extension_loaded($objectcache)) ? ' extension not available!' : '';$info = ['general' => [- __('Vvveb version') => V_VERSION,- __('Admin path') => \Vvveb\adminPath(),- __('PHP version') => phpversion() . ' | ' . php_sapi_name(),- __('Server') => $_SERVER['SERVER_SOFTWARE'] ?? '',- __('OS version') => php_uname(),- __('Database driver & version') => $database,- __('PHP time limit') => ini_get('max_execution_time'),- __('PHP memory limit') => ini_get('memory_limit'),- __('Max input time') => ini_get('max_input_time'),- __('Upload max filesize') => ini_get('upload_max_filesize'),- __('PHP post max size') => ini_get('post_max_size'),- __('Extensions') => implode(' ', get_loaded_extensions()),- __('Page cache') => (defined('PAGE_CACHE') && PAGE_CACHE) ? __('enabled') : __('disabled'),- __('Object cache') => $objectcache,- __('Email Driver') => \Vvveb\getConfig('app.email.driver'),- __('Session Driver') => \Vvveb\getConfig('app.session.driver'),- __('Debug') => DEBUG ? __('enabled') : __('disabled'),- __('Sql changes check') => SQL_CHECK ? __('enabled') : __('disabled'),- __('Image library') => $imageLibrary,- 'Rest API' => REST ? __('enabled') : __('disabled'),- 'GraphQL' => GRAPHQL ? __('enabled') : __('disabled'),+ __('Vvveb version') => V_VERSION,+ __('Admin path') => \Vvveb\adminPath(),+ __('PHP version') => PHP_VERSION . ' | ' . PHP_SAPI,+ __('Server') => $_SERVER['SERVER_SOFTWARE'] ?? '',+ __('OS version') => php_uname(),+ __('Database driver & version') => $database,+ __('PHP time limit') => ini_get('max_execution_time'),+ __('PHP memory limit') => ini_get('memory_limit'),+ __('Max input time') => ini_get('max_input_time'),+ __('Upload max filesize') => ini_get('upload_max_filesize'),+ __('PHP post max size') => ini_get('post_max_size'),+ __('Extensions') => implode(' ', get_loaded_extensions()),+ __('Page cache') => (defined('PAGE_CACHE') && PAGE_CACHE) ? __('enabled') : __('disabled'),+ __('Object cache') => $objectcache,+ __('Email Driver') => \Vvveb\getConfig('app.email.driver'),+ __('Session Driver') => \Vvveb\getConfig('app.session.driver'),+ __('Debug') => DEBUG ? __('enabled') : __('disabled'),+ __('Sql changes check') => SQL_CHECK ? __('enabled') : __('disabled'),+ __('Image library') => $imageLibrary,+ __('Image formats') => implode(' ', Image::formats()),+ 'Rest API' => REST ? __('enabled') : __('disabled'),+ 'GraphQL' => GRAPHQL ? __('enabled') : __('disabled'),],'server' => [__('Document root') => $_SERVER['DOCUMENT_ROOT'] ?? '',- __('Public path') => PUBLIC_PATH ?? '',+ __('Public path') => PUBLIC_PATH,],];@@ -89,7 +100,7 @@ class SystemInfo extends Base {$info['server'][$key] = $value;}- list($info) = Event::trigger(__CLASS__, __FUNCTION__, $info);+ [$info] = Event::trigger(__CLASS__, __FUNCTION__, $info);$this->view->info = $info;diff --git a/admin/controller/tools/update.php b/admin/controller/tools/update.phpold mode 100755new mode 100644index e254165..8b48a58--- a/admin/controller/tools/update.php+++ b/admin/controller/tools/update.php@@ -31,13 +31,31 @@ use Vvveb\System\User\Admin;use function Vvveb\url;class Update extends Base {- private $steps = ['checkPermissions', 'download', 'unzip', 'copyInstall', /*'backup',*/ 'copySystem', /* 'copyAdmin',*/ 'copyApp', 'copyCore', 'copyConfig', 'addNewColumns', 'createNewTables', 'copyPublic', 'copyPublicAdmin', 'copyPublicMedia', 'setFilePermissions', 'cleanUp', 'clearCache', 'complete'];-- function __construct() {+ /**+ * Ordered list of update step method names.+ *+ * @var list<string>+ */+ private array $steps = ['checkPermissions', 'download', 'unzip', 'copyInstall', 'addNewColumns', 'createNewTables', /*'backup', 'copySystem', 'copyAdmin', 'copyApp', 'copyCore', */ 'copyConfig', 'copyPublic', 'copyPublicAdmin', 'copyPublicMedia', 'moveFolders', 'setFilePermissions', 'cleanUp', 'clearCache', 'complete'];++ /**+ * Initialize the update system instance.+ *+ * @return void+ */+ public function __construct() {$this->update = new UpdateSys();}- private function checkUpdates($type = 'core', $force = false) {+ /**+ * Check for available updates of the specified type.+ *+ * @param string $type The update type to check (e.g. 'core').+ * @param bool $force Force check ignoring cache.+ *+ * @return array<string, mixed> Update information array.+ */+ private function checkUpdates(string $type = 'core', bool $force = false): array {$updateInfo = [];$errorMsg = __('Error checking updates!');@@ -47,30 +65,40 @@ class Update extends Base {$this->view->errors[] = $e->getMessage();}- if (! $updateInfo) {+ if (!$updateInfo) {$this->view->errors[] = $errorMsg;}return $updateInfo;}- function check() {+ /**+ * Check for updates and display the update page.+ *+ * @return void+ */+ public function check(): void {$type = $this->request->get['type'] ?? 'core';$updateInfo = $this->update->checkUpdates($type, true);if ($updateInfo) {//$this->view->success[] = __('Check succesful!');if ($updateInfo['hasUpdate']) {- $this->view->info[] = __('Updates available!') . ' <span class="badge bg-success">' . $updateInfo['version'] . '</span>';+ $this->view->info[] = __('Updates available!') . ' <span class="badge bg-success">' . htmlspecialchars((string)$updateInfo['version'], ENT_QUOTES, 'UTF-8') . '</span>';} else {$this->view->info[] = __('No updates available!');}}- return $this->index();+ $this->index();}- function updateNext() {+ /**+ * Execute the next update step in the update sequence.+ *+ * @return void+ */+ public function updateNext(): void {ignore_user_abort(true);$step = $this->request->get['step'] ?? false;$next = false;@@ -104,10 +132,10 @@ class Update extends Base {$count = count($this->steps);$url['info'] = sprintf(__('Step (%d/%d) %s ...'), $position, $count, humanReadable(camelToUnderscore($next)));$this->view->info[] = $url['info'];- $url += ['module'=>'tools/update', 'action' => 'updateNext', 'step' => $next, 'position' => $position, 'count' => $count];+ $url += ['module' => 'tools/update', 'action' => 'updateNext', 'step' => $next, 'position' => $position, 'count' => $count];if ($this->request->isAjax()) {- die(json_encode($url + ['url' => url($url)]));+ exit(json_encode($url + ['url' => url($url)]));} else {$this->redirect($url);}@@ -116,23 +144,34 @@ class Update extends Base {$message = __('Update finished');if ($this->request->isAjax()) {- die(json_encode($url + ['url' => url($url), 'success' => $message]));+ exit(json_encode($url + ['url' => url($url), 'success' => $message]));} else {$this->view->success[] = $message;- return $this->index();+ $this->index();}}}}- private function download() {+ /**+ * Download the update package.+ *+ * @return bool True if download succeeded, false otherwise.+ */+ private function download(): bool {$updateFile = false;$errorDownloadMsg = __('Error downloading update!');$updateInfo = $this->update->checkUpdates();//don't load plugins during update to avoid possible conflictsAdmin::session(['safemode' => true]);+ if (!$updateInfo || !isset($updateInfo['download'])) {+ $this->view->errors[] = $errorDownloadMsg . ' ' . $updateInfo['error'];++ return false;+ }+try {$updateFile = $this->update->download($updateInfo['download']);$this->session->set('updateFile', $updateFile);@@ -140,7 +179,7 @@ class Update extends Base {$this->view->errors[] = $e->getMessage();}- if (! $updateInfo || ! $updateFile) {+ if (!$updateFile) {$this->view->errors[] = $errorDownloadMsg;return false;@@ -151,7 +190,12 @@ class Update extends Base {return true;}- function checkPermissions() {+ /**+ * Check file and directory permissions for the update.+ *+ * @return bool True if permissions are OK, false otherwise.+ */+ public function checkPermissions(): bool {$result = false;try {@@ -171,7 +215,12 @@ class Update extends Base {return $result;}- function backup() {+ /**+ * Create a backup before applying the update.+ *+ * @return bool True if backup succeeded, false otherwise.+ */+ public function backup(): bool {$result = false;try {@@ -187,7 +236,12 @@ class Update extends Base {return $result;}- function addNewColumns() {+ /**+ * Add new database columns introduced by the update.+ *+ * @return bool True if columns were added successfully, false otherwise.+ */+ public function addNewColumns(): bool {$result = false;try {@@ -203,7 +257,12 @@ class Update extends Base {return $result;}- function createNewTables() {+ /**+ * Create new database tables introduced by the update.+ *+ * @return bool True if tables were created successfully, false otherwise.+ */+ public function createNewTables(): bool {$result = false;try {@@ -219,7 +278,12 @@ class Update extends Base {return $result;}- function unzip() {+ /**+ * Unzip the downloaded update package.+ *+ * @return bool True if unzip succeeded, false otherwise.+ */+ public function unzip(): bool {$errorInstallMsg = __('Error unzipping update!');$result = true;@@ -230,7 +294,7 @@ class Update extends Base {$this->view->errors[] = $e->getMessage();}- if (! $result) {+ if (!$result) {$this->view->errors[] = $errorInstallMsg;} else {$this->view->success[] = __('Unzip successful!');@@ -239,7 +303,14 @@ class Update extends Base {return $result;}- private function copy($method) {+ /**+ * Copy files for the specified update section.+ *+ * @param string $method The copy method name (e.g. 'Core', 'Config').+ *+ * @return bool True if copy succeeded, false otherwise.+ */+ private function copy(string $method): bool {$name = humanReadable(camelToUnderscore($method));$errorInstallMsg = sprintf(__('Error updating %s'), $name);$result = false;@@ -252,7 +323,7 @@ class Update extends Base {$this->view->errors[] = $e->getMessage();}- if (! $result) {+ if (!$result) {$this->view->errors[] = $errorInstallMsg;} else {$this->view->success[] = sprintf(__('Update %s successful!'), $name);@@ -261,15 +332,30 @@ class Update extends Base {return $result;}- function copyCore() {+ /**+ * Copy core framework files.+ *+ * @return bool+ */+ public function copyCore(): bool {return $this->copy('Core');}- function copyConfig() {+ /**+ * Copy configuration files.+ *+ * @return bool+ */+ public function copyConfig(): bool {return $this->copy('Config');}- function copySystem() {+ /**+ * Copy system and admin files in one step.+ *+ * @return bool+ */+ public function copySystem(): bool {//merge system and admin in one step so that the updater does not break if depends on older system code.$return = $this->copy('System');@@ -285,27 +371,66 @@ class Update extends Base {return $this->copy('Admin');}*/- function copyApp() {+ /**+ * Copy application files.+ *+ * @return bool+ */+ public function copyApp(): bool {return $this->copy('App');}- function copyInstall() {+ /**+ * Copy installation files.+ *+ * @return bool+ */+ public function copyInstall(): bool {return $this->copy('Install');}- function copyPublic() {+ /**+ * Copy public-facing files.+ *+ * @return bool+ */+ public function copyPublic(): bool {return $this->copy('Public');}- function copyPublicAdmin() {+ /**+ * Copy public admin assets.+ *+ * @return bool+ */+ public function copyPublicAdmin(): bool {return $this->copy('PublicAdmin');}- function copyPublicMedia() {+ /**+ * Copy public media files.+ *+ * @return bool+ */+ public function copyPublicMedia(): bool {return $this->copy('PublicMedia');}- function setFilePermissions() {+ /**+ * Move new folders and backup existing ones.+ *+ * @return bool+ */+ public function moveFolders(): bool {+ return $this->update->moveFolders();+ }++ /**+ * Set file permissions after the update.+ *+ * @return bool True if permissions were set successfully, false otherwise.+ */+ public function setFilePermissions(): bool {$errorInstallMsg = __('Error setting permissions');$result = false;@@ -315,7 +440,7 @@ class Update extends Base {$this->view->errors[] = $e->getMessage();}- if (! $result) {+ if (!$result) {$this->view->errors[] = $errorInstallMsg;} else {$this->view->success[] = __('Set permissions successful!');@@ -324,7 +449,12 @@ class Update extends Base {return $result;}- function cleanUp() {+ /**+ * Clean up temporary update files.+ *+ * @return bool True if cleanup succeeded, false otherwise.+ */+ public function cleanUp(): bool {$errorInstallMsg = __('Error cleaning up');$result = false;@@ -334,7 +464,7 @@ class Update extends Base {$this->view->errors[] = $e->getMessage();}- if (! $result) {+ if (!$result) {$this->view->errors[] = $errorInstallMsg;} else {$this->view->success[] = __('Cleanup successful!');@@ -343,7 +473,12 @@ class Update extends Base {return $result;}- function clearCache() {+ /**+ * Clear all caches after the update.+ *+ * @return bool True if cache was cleared successfully, false otherwise.+ */+ public function clearCache(): bool {$errorInstallMsg = __('Error clearing cache');$result = false;@@ -353,7 +488,7 @@ class Update extends Base {$this->view->errors[] = $e->getMessage();}- if (! $result) {+ if (!$result) {$this->view->errors[] = $errorInstallMsg;} else {$this->view->success[] = __('Clear cache successful!');@@ -362,30 +497,45 @@ class Update extends Base {return $result;}- function complete() {+ /**+ * Mark the update as complete and disable safe mode.+ *+ * @return bool Always returns true.+ */+ public function complete(): bool {$this->view->success[] = __('Update complete!');Admin::session(['safemode' => false]);return true;}- function update() {+ /**+ * Start the update process from the first step.+ *+ * @return void+ */+ public function update(): void {$this->request->get['step'] = $this->steps[0];$info = __('Update in progress, do not close this page ...');$this->view->info[] = $info;if ($this->request->isAjax()) {- $url = ['module'=>'tools/update', 'action' => 'updateNext', 'step' => $this->steps[0], 'position' => 0, 'count' => count($this->steps), 'info' => $info];+ $url = ['module' => 'tools/update', 'action' => 'updateNext', 'step' => $this->steps[0], 'position' => 0, 'count' => count($this->steps), 'info' => $info];- die(json_encode($url + ['url' => url($url)]));+ exit(json_encode($url + ['url' => url($url)]));} else {$this->updateNext();}- return $this->index();+ $this->index();}- function index() {+ /**+ * Display the update status page with current version information.+ *+ * @return void+ */+ public function index(): void {$updateInfo = $this->checkUpdates();if (isset($updateInfo['error']) && $updateInfo['error']) {diff --git a/public/js/admin/controller/backup.js b/public/js/admin/controller/backup.jsindex f0e5a66..4e150f5 100644--- a/public/js/admin/controller/backup.js+++ b/public/js/admin/controller/backup.js@@ -2,16 +2,23 @@ class BackupController {action(url, params, btn) {let next = url;- document.getElementById("progress").classList.remove("d-none");+ let progress = document.getElementById("progress");+ if (progress) progress.classList.remove("d-none");function disableBtn() {- btn.querySelector('.loading').classList.remove('d-none');- btn.querySelector('.button-text').classList.add('d-none');+ if (!btn) return;+ let loading = btn.querySelector('.loading');+ let text = btn.querySelector('.button-text');+ if (loading) loading.classList.remove('d-none');+ if (text) text.classList.add('d-none');}function enableBtn() {- btn.querySelector('.loading').classList.add('d-none');- btn.querySelector('.button-text').classList.remove('d-none');+ if (!btn) return;+ let loading = btn.querySelector('.loading');+ let text = btn.querySelector('.button-text');+ if (loading) loading.classList.add('d-none');+ if (text) text.classList.remove('d-none');}disableBtn();@@ -20,7 +27,7 @@ class BackupController {return fetch(next, {method: "POST", headers: {"X-Requested-With": "XMLHttpRequest","Content-Type": "application/x-www-form-urlencoded",- }, body: new URLSearchParams({...params, csrf: document.querySelector('[name=csrf]')?.value})})+ }, body: new URLSearchParams({...params, csrf: document.querySelector('[name=csrf]')?.value ?? ""})}).then((response) => {next = false;if (!response.ok) {@@ -28,52 +35,58 @@ class BackupController {return Promise.reject([response, responseInText]);});}- if (!response.ok) {- let message = response.statusText + " " + response.body();- throw new Error(message);- }return response.json()}).then((json) => {- document.getElementById('progress-status').innerHTML = '';+ const status = document.getElementById('progress-status');+ const progressBar = document.getElementById('progress-bar');+ const setText = (id, value) => {+ const el = document.getElementById(id);+ if (el && value !== undefined && value !== null) {+ el.textContent = value;+ }+ };++ if (status) status.textContent = '';if (json['error']) {- document.getElementById('progress-bar').classList.add('bg-danger');- document.getElementById('progress-status').innerHTML = '<div class="text-danger">' + json['error'] + '</div>';+ if (progressBar) progressBar.classList.add('bg-danger');+ if (status) {+ status.classList.add('text-danger');+ status.textContent = json['error'];+ }enableBtn();+ //stop on fatal errors instead of continuing to the next step+ return;}- let percent = (json['position']) * 100 / json['count'];+ let percent = (json['position'] || 0) * 100 / (json['count'] || 1);if (json['success']) {- document.getElementById('progress-bar').style.width = "100%";//.classList.add('bg-success');- document.getElementById('progress-status').innerHTML = '<div class="text-success">' + json['success'] + '</div>';+ if (progressBar) progressBar.style.width = "100%";//.classList.add('bg-success');+ if (status) {+ status.classList.remove('text-danger');+ status.classList.add('text-success');+ status.textContent = json['success'];+ }enableBtn();}if (json['table']) {- document.getElementById('progress-status').innerHTML = json['table'];- }-- if (json['file']) {- document.getElementById('progress-file').innerHTML = json['file'];- }-- if (json['position']) {- document.getElementById('progress-position').innerHTML = json['position'];- }-- if (json['count']) {- document.getElementById('progress-count').innerHTML = json['count'];- }-- if (json['page']) {- document.getElementById('progress-page').innerHTML = json['page'];+ if (status) {+ status.classList.remove('text-danger', 'text-success');+ status.textContent = json['table'];+ }}+ if (json['file']) setText('progress-file', json['file']);+ if (json['position'] !== undefined) setText('progress-position', json['position']);+ if (json['count'] !== undefined) setText('progress-count', json['count']);+ if (json['page']) setText('progress-page', json['page']);+if (json['url'] && (!json['count'] || (json['position'] < json['count']))) {next = json['url'];@@ -81,42 +94,59 @@ class BackupController {ajaxStack.add(request);} else {percent = 100;- document.getElementById('progress-bar').classList.add('bg-success');+ if (progressBar) {+ progressBar.classList.add('bg-success');+ progressBar.style.width = '100%';+ }enableBtn();- document.getElementById('progress-bar').style.width = '100%';if (json['success']) {- window.location.href += '&success=' + json['success'];- } else {+ let url = window.location.href;+ if (url.indexOf('success=') === -1) {+ url += (url.indexOf('?') > -1 ? '&' : '?') + 'success=' + encodeURIComponent(json['success']);+ window.location.href = url;+ } else {+ window.location.reload();+ }+ } else if (window.navigation?.reload) {window.navigation.reload();+ } else {+ window.location.reload();}}- document.getElementById('progress-bar').style.width = percent + '%';+ if (progressBar) progressBar.style.width = percent + '%';})/*.then((json) => {if (next) {ajaxStack.add(request);}})*/.catch(error => {- let [response, responseInText] = error;- let message = response.statusText ?? "Error!";- let progessSuccess, progressStatus;-- if (typeof error.json === "function") {- error.json().then(jsonError => {- message = jsonError;- }).catch(genericError => {- message = error.statusText + " " + message;- });- }-+ let response, responseInText;++ if (Array.isArray(error)) {+ [response, responseInText] = error;+ }++ let message = responseInText || response?.statusText || error?.message || "Error!";+ message = String(message);+displayToast("danger", "Error", message);- if (progessSuccess = document.getElementById('progress-success')) progessSuccess.innerHTML = '';- if (progressStatus = document.getElementById('progress-status')) progressStatus.innerHTML = '<div class="text-danger">' + message + '</div>';- //console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);- document.getElementById('progress-bar').classList.add('bg-danger');++ const progressSuccess = document.getElementById('progress-success');+ if (progressSuccess) progressSuccess.textContent = '';++ const progressStatus = document.getElementById('progress-status');+ if (progressStatus) {+ progressStatus.classList.add('text-danger');+ progressStatus.textContent = message;+ }++ const progressBar = document.getElementById('progress-bar');+ if (progressBar) progressBar.classList.add('bg-danger');+enableBtn();+ console.error(error);});};diff --git a/public/js/admin/controller/cache.js b/public/js/admin/controller/cache.jsindex 77182a9..55ab0c8 100644--- a/public/js/admin/controller/cache.js+++ b/public/js/admin/controller/cache.js@@ -1,21 +1,47 @@class CacheController {clear(e, element) {- let url = element.href;+ element = element ?? e.currentTarget;+ let url = element?.getAttribute('href');- fetch(url)+ //fallback for pages where the href was not generated from data-v-url-params+ if ((!url || url === '#') && element?.dataset.vUrlParams) {+ try {+ url = window.location.pathname + '?' + new URLSearchParams(JSON.parse(element.dataset.vUrlParams)).toString();+ } catch (error) {+ console.error("Invalid cache action url", error);+ }+ }++ if (!url || url === '#') {+ displayToast("danger", "Cache", "Invalid cache action!", "top");+ e.preventDefault();+ return false;+ }++ fetch(url, {+ method: "POST",+ headers: {+ "X-Requested-With": "XMLHttpRequest",+ "Content-Type": "application/x-www-form-urlencoded",+ },+ body: new URLSearchParams({csrf: document.querySelector('[name=csrf]')?.value ?? ""})+ }).then((response) => {if (!response.ok) { throw new Error(response) }return response.text()}).then((data) => {let response = new DOMParser().parseFromString(data, "text/html");- let message = response.querySelector(".notifications .alert [data-v-notification-text]")?.innerHTML;- displayToast("success", "Cache", message, "top");+ let notification = response.querySelector(".notifications .alert");+ let message = notification?.querySelector("[data-v-notification-text]")?.textContent?.trim();+ let success = !notification || notification.classList.contains("alert-success");++ displayToast(success ? "success" : "danger", "Cache", message || (success ? "Cache cleared" : "Error clearing cache"), "top");}).catch(error => {- displayToast("danger", "Cache", "Error", "top");- //displayToast("danger", "Error", "Error saving!");+ displayToast("danger", "Cache", "Error clearing cache", "top");+ console.error(error);});e.preventDefault();diff --git a/public/js/admin/controller/media-backup.js b/public/js/admin/controller/media-backup.jsnew file mode 100755index 0000000..b6e8ea4--- /dev/null+++ b/public/js/admin/controller/media-backup.js@@ -0,0 +1,179 @@+class MediaBackupController {++ action(url, params, btn) {+ let next = url;+ let progress = document.getElementById("progress");+ if (progress) progress.classList.remove("d-none");++ function disableBtn() {+ if (!btn) return;+ let loading = btn.querySelector('.loading');+ let text = btn.querySelector('.button-text');+ if (loading) loading.classList.remove('d-none');+ if (text) text.classList.add('d-none');+ }++ function enableBtn() {+ if (!btn) return;+ let loading = btn.querySelector('.loading');+ let text = btn.querySelector('.button-text');+ if (loading) loading.classList.add('d-none');+ if (text) text.classList.remove('d-none');+ }++ disableBtn();++ let request = function () {+ //handle themes array as comma-separated string for PHP+ let bodyParams = {...params};+ if (Array.isArray(bodyParams.themes)) {+ bodyParams.themes = bodyParams.themes.join(',');+ }+ return fetch(next, {method: "POST", headers: {+ "X-Requested-With": "XMLHttpRequest",+ "Content-Type": "application/x-www-form-urlencoded",+ }, body: new URLSearchParams({...bodyParams, csrf: document.querySelector('[name=csrf]')?.value ?? ""})})+ .then((response) => {+ next = false;+ if (!response.ok) {+ return Promise.resolve(response.text()).then((responseInText) => {+ return Promise.reject([response, responseInText]);+ });+ }+ return response.json()+ })++ .then((json) => {+ const status = document.getElementById('progress-status');+ const progressBar = document.getElementById('progress-bar');+ const setText = (id, value) => {+ const el = document.getElementById(id);+ if (el && value !== undefined && value !== null) {+ el.textContent = value;+ }+ };++ if (status) status.textContent = '';++ if (json['error']) {+ if (progressBar) progressBar.classList.add('bg-danger');+ if (status) {+ status.classList.add('text-danger');+ status.textContent = json['error'];+ }++ enableBtn();+ //stop on fatal errors instead of continuing to the next step+ return;+ }++ let percent = (json['position'] || 0) * 100 / (json['count'] || 1);++ if (json['success']) {+ if (progressBar) progressBar.style.width = "100%";+ if (status) {+ status.classList.remove('text-danger');+ status.classList.add('text-success');+ status.textContent = json['success'];+ }++ enableBtn();+ }++ if (json['theme']) {+ if (status) {+ status.classList.remove('text-danger', 'text-success');+ status.textContent = json['theme'];+ }+ } else if (json['table']) {+ if (status) {+ status.classList.remove('text-danger', 'text-success');+ status.textContent = json['table'];+ }+ }++ if (json['file']) setText('progress-file', json['file']);+ if (json['position'] !== undefined) setText('progress-position', json['position']);+ if (json['count'] !== undefined) setText('progress-count', json['count']);+ if (json['theme']) setText('progress-theme', json['theme']);++ if (json['url'] && (!json['count'] || (json['position'] < json['count']))) {+ next = json['url'];++ ajaxStack.add(request);+ } else {+ percent = 100;+ if (progressBar) {+ progressBar.classList.add('bg-success');+ progressBar.style.width = '100%';+ }+ enableBtn();++ if (json['success']) {+ let url = window.location.href;+ if (url.indexOf('success=') === -1) {+ url += (url.indexOf('?') > -1 ? '&' : '?') + 'success=' + encodeURIComponent(json['success']);+ window.location.href = url;+ } else {+ window.location.reload();+ }+ } else if (window.navigation?.reload) {+ window.navigation.reload();+ } else {+ window.location.reload();+ }+ }++ if (progressBar) progressBar.style.width = percent + '%';+ })+ .catch(error => {+ let response, responseInText;++ if (Array.isArray(error)) {+ [response, responseInText] = error;+ }++ let message = responseInText || response?.statusText || error?.message || "Error!";+ message = String(message);++ if (typeof displayToast === "function") {+ displayToast("danger", "Error", message);+ }++ const progressSuccess = document.getElementById('progress-success');+ if (progressSuccess) progressSuccess.textContent = '';++ const progressStatus = document.getElementById('progress-status');+ if (progressStatus) {+ progressStatus.classList.add('text-danger');+ progressStatus.textContent = message;+ }++ const progressBar = document.getElementById('progress-bar');+ if (progressBar) progressBar.classList.add('bg-danger');++ enableBtn();+ console.error(error);+ });+ };++ ajaxStack.add(request);+ }++ make(url, params = {}, btn = false) {+ url = url ?? (window.location.pathname + '?module=tools/media-backup&action=save');+ //if params contains themes array, we keep as array for POST body but also need to ensure URL carries themes for next steps via GET+ //The controller's save will create folder and return next url with themes encoded, so initial make only needs folder creation+ return this.action(url, params, btn);+ }++ restore(url, params = {}, btn = false) {+ return this.action(url, params, btn);+ }++}++let MediaBackup = new MediaBackupController();+export {MediaBackup};++window.MediaBackup = MediaBackup;diff --git a/public/js/admin/controller/plugins-backup.js b/public/js/admin/controller/plugins-backup.jsnew file mode 100755index 0000000..f9d0dcd--- /dev/null+++ b/public/js/admin/controller/plugins-backup.js@@ -0,0 +1,179 @@+class PluginsBackupController {++ action(url, params, btn) {+ let next = url;+ let progress = document.getElementById("progress");+ if (progress) progress.classList.remove("d-none");++ function disableBtn() {+ if (!btn) return;+ let loading = btn.querySelector('.loading');+ let text = btn.querySelector('.button-text');+ if (loading) loading.classList.remove('d-none');+ if (text) text.classList.add('d-none');+ }++ function enableBtn() {+ if (!btn) return;+ let loading = btn.querySelector('.loading');+ let text = btn.querySelector('.button-text');+ if (loading) loading.classList.add('d-none');+ if (text) text.classList.remove('d-none');+ }++ disableBtn();++ let request = function () {+ //handle plugins array as comma-separated string for PHP+ let bodyParams = {...params};+ if (Array.isArray(bodyParams.plugins)) {+ bodyParams.plugins = bodyParams.plugins.join(',');+ }+ return fetch(next, {method: "POST", headers: {+ "X-Requested-With": "XMLHttpRequest",+ "Content-Type": "application/x-www-form-urlencoded",+ }, body: new URLSearchParams({...bodyParams, csrf: document.querySelector('[name=csrf]')?.value ?? ""})})+ .then((response) => {+ next = false;+ if (!response.ok) {+ return Promise.resolve(response.text()).then((responseInText) => {+ return Promise.reject([response, responseInText]);+ });+ }+ return response.json()+ })++ .then((json) => {+ const status = document.getElementById('progress-status');+ const progressBar = document.getElementById('progress-bar');+ const setText = (id, value) => {+ const el = document.getElementById(id);+ if (el && value !== undefined && value !== null) {+ el.textContent = value;+ }+ };++ if (status) status.textContent = '';++ if (json['error']) {+ if (progressBar) progressBar.classList.add('bg-danger');+ if (status) {+ status.classList.add('text-danger');+ status.textContent = json['error'];+ }++ enableBtn();+ //stop on fatal errors instead of continuing to the next step+ return;+ }++ let percent = (json['position'] || 0) * 100 / (json['count'] || 1);++ if (json['success']) {+ if (progressBar) progressBar.style.width = "100%";+ if (status) {+ status.classList.remove('text-danger');+ status.classList.add('text-success');+ status.textContent = json['success'];+ }++ enableBtn();+ }++ if (json['plugin']) {+ if (status) {+ status.classList.remove('text-danger', 'text-success');+ status.textContent = json['plugin'];+ }+ } else if (json['table']) {+ if (status) {+ status.classList.remove('text-danger', 'text-success');+ status.textContent = json['table'];+ }+ }++ if (json['file']) setText('progress-file', json['file']);+ if (json['position'] !== undefined) setText('progress-position', json['position']);+ if (json['count'] !== undefined) setText('progress-count', json['count']);+ if (json['plugin']) setText('progress-plugin', json['plugin']);++ if (json['url'] && (!json['count'] || (json['position'] < json['count']))) {+ next = json['url'];++ ajaxStack.add(request);+ } else {+ percent = 100;+ if (progressBar) {+ progressBar.classList.add('bg-success');+ progressBar.style.width = '100%';+ }+ enableBtn();++ if (json['success']) {+ let url = window.location.href;+ if (url.indexOf('success=') === -1) {+ url += (url.indexOf('?') > -1 ? '&' : '?') + 'success=' + encodeURIComponent(json['success']);+ window.location.href = url;+ } else {+ window.location.reload();+ }+ } else if (window.navigation?.reload) {+ window.navigation.reload();+ } else {+ window.location.reload();+ }+ }++ if (progressBar) progressBar.style.width = percent + '%';+ })+ .catch(error => {+ let response, responseInText;++ if (Array.isArray(error)) {+ [response, responseInText] = error;+ }++ let message = responseInText || response?.statusText || error?.message || "Error!";+ message = String(message);++ if (typeof displayToast === "function") {+ displayToast("danger", "Error", message);+ }++ const progressSuccess = document.getElementById('progress-success');+ if (progressSuccess) progressSuccess.textContent = '';++ const progressStatus = document.getElementById('progress-status');+ if (progressStatus) {+ progressStatus.classList.add('text-danger');+ progressStatus.textContent = message;+ }++ const progressBar = document.getElementById('progress-bar');+ if (progressBar) progressBar.classList.add('bg-danger');++ enableBtn();+ console.error(error);+ });+ };++ ajaxStack.add(request);+ }++ make(url, params = {}, btn = false) {+ url = url ?? (window.location.pathname + '?module=tools/plugins-backup&action=save');+ //if params contains plugins array, we keep as array for POST body but also need to ensure URL carries plugins for next steps via GET+ //The controller's save will create folder and return next url with plugins encoded, so initial make only needs folder creation+ return this.action(url, params, btn);+ }++ restore(url, params = {}, btn = false) {+ return this.action(url, params, btn);+ }++}++let PluginsBackup = new PluginsBackupController();+export {PluginsBackup};++window.PluginsBackup = PluginsBackup;diff --git a/public/js/admin/controller/plugins.js b/public/js/admin/controller/plugins.jsindex 89d3241..55b77aa 100755--- a/public/js/admin/controller/plugins.js+++ b/public/js/admin/controller/plugins.js@@ -1,59 +1,94 @@import {Plugins as PluginsModel} from '../model/plugins.js';+function showImportModal() {+ let modal = document.getElementById("importModal");++ if (modal && window.bootstrap?.Modal) {+ bootstrap.Modal.getOrCreateInstance(modal).show();+ }+}+class PluginsController {- install(e) {- let element = e.currentTarget;+ install(e, element) {+ element = element ?? e.currentTarget;+ if (!element || !element.dataset) {+ return;+ }+let slug = element.dataset.slug;let market = element.dataset.market;-+ let loading = element.querySelector('.loading');+ let text = element.querySelector('.button-text');+element.classList.add("loading");- element.querySelector('.loading').toggleClass("d-none");- element.querySelector('.button-text').toggleClass("d-none");-+ if (loading) loading.classList.remove("d-none");+ if (text) text.classList.add("d-none");+PluginsModel.install(market, slug, function (data) {setTimeout(function () {element.classList.remove("loading");- element.querySelector('.loading').toggleClass("d-none");- element.querySelector('.button-text').toggleClass("d-none");+ if (loading) loading.classList.add("d-none");+ if (text) text.classList.remove("d-none");}, 5000);});-++ showImportModal();e.preventDefault();}-++ showModal() {+ let modal = document.getElementById("importModal");++ if (modal && window.bootstrap?.Modal) {+ bootstrap.Modal.getOrCreateInstance(modal).show();+ }+ }+importModal(e) {- document.getElementById("importModal").modal('show');+ showImportModal();e.preventDefault();}-- importTheme(e) {- document.getElementById("import-iframe").show();- document.getElementById("import-form").submit();- document.getElementById("import-options").style.display = "none";- e.target.style.display = "none";++ importTheme(e, element) {+ element = element ?? e.target;+ let iframe = document.getElementById("import-iframe");+ let form = document.getElementById("import-form");+ let options = document.getElementById("import-options");++ if (iframe) iframe.style.display = "";+ if (form) form.submit();+ if (options) options.style.display = "none";+ if (element) element.style.display = "none";+ e.preventDefault();}- import(e) {- console.log(document.getElementById("import-form").serialize());+ import(e, element) {+ let form = document.getElementById("import-form");+ if (form) {+ console.log(new URLSearchParams(new FormData(form)).toString());+ }}-- activate(e) {- let element = e.currentTarget;++ activate(e, element) {+ element = element ?? e.currentTarget;+ if (!element || !element.dataset) {+ return;+ }+let slug = element.dataset.slug;let market = element.dataset.market;-+element.classList.add("loading");-+PluginsModel.install(market, slug, function () {setTimeout(function () {element.classList.remove("loading");}, 5000);});-- document.getElementById("importModal").modal('show');-++ showImportModal();e.preventDefault();}}diff --git a/public/js/admin/controller/search.js b/public/js/admin/controller/search.jsindex 4f65b93..375a8e5 100644--- a/public/js/admin/controller/search.js+++ b/public/js/admin/controller/search.js@@ -3,10 +3,8 @@ var prevSearchValue;class SearchController {autocomplete(e, element) {- let url = element.href;-if (element.value) {- let loading = this.form.querySelector(".loading");+ let loading = (this.form ?? this.closest("form"))?.querySelector(".loading");if (loading && prevSearchValue != element.value) {loading.classList.remove('d-none');document.querySelector(".search-results")?.replaceChildren();diff --git a/public/js/admin/controller/table.js b/public/js/admin/controller/table.jsindex fdab5dd..593e77a 100755--- a/public/js/admin/controller/table.js+++ b/public/js/admin/controller/table.js@@ -2,11 +2,10 @@ class TableController {selectRow(e) {let selectedCount = document.querySelectorAll(".checkbox input[type='checkbox']:checked");+ let bulkActions = document.querySelector('.bulk-actions');- if (selectedCount.length > 0) {- document.querySelector('.bulk-actions').style.display = "block";- } else {- document.querySelector('.bulk-actions').style.display = "none";+ if (bulkActions) {+ bulkActions.style.display = selectedCount.length > 0 ? "block" : "none";}}@@ -14,10 +13,9 @@ class TableController {let bulkCheckbox = this;document.querySelectorAll(".checkbox input[type='checkbox']").forEach(e => e.checked = bulkCheckbox.checked);- if (bulkCheckbox.checked) {- document.querySelector('.bulk-actions').style.display = "block";- } else {- document.querySelector('.bulk-actions').style.display = "none";+ let bulkActions = document.querySelector('.bulk-actions');+ if (bulkActions) {+ bulkActions.style.display = bulkCheckbox.checked ? "block" : "none";}}}diff --git a/public/js/admin/controller/themes-backup.js b/public/js/admin/controller/themes-backup.jsnew file mode 100755index 0000000..bad54a9--- /dev/null+++ b/public/js/admin/controller/themes-backup.js@@ -0,0 +1,179 @@+class ThemesBackupController {++ action(url, params, btn) {+ let next = url;+ let progress = document.getElementById("progress");+ if (progress) progress.classList.remove("d-none");++ function disableBtn() {+ if (!btn) return;+ let loading = btn.querySelector('.loading');+ let text = btn.querySelector('.button-text');+ if (loading) loading.classList.remove('d-none');+ if (text) text.classList.add('d-none');+ }++ function enableBtn() {+ if (!btn) return;+ let loading = btn.querySelector('.loading');+ let text = btn.querySelector('.button-text');+ if (loading) loading.classList.add('d-none');+ if (text) text.classList.remove('d-none');+ }++ disableBtn();++ let request = function () {+ //handle themes array as comma-separated string for PHP+ let bodyParams = {...params};+ if (Array.isArray(bodyParams.themes)) {+ bodyParams.themes = bodyParams.themes.join(',');+ }+ return fetch(next, {method: "POST", headers: {+ "X-Requested-With": "XMLHttpRequest",+ "Content-Type": "application/x-www-form-urlencoded",+ }, body: new URLSearchParams({...bodyParams, csrf: document.querySelector('[name=csrf]')?.value ?? ""})})+ .then((response) => {+ next = false;+ if (!response.ok) {+ return Promise.resolve(response.text()).then((responseInText) => {+ return Promise.reject([response, responseInText]);+ });+ }+ return response.json()+ })++ .then((json) => {+ const status = document.getElementById('progress-status');+ const progressBar = document.getElementById('progress-bar');+ const setText = (id, value) => {+ const el = document.getElementById(id);+ if (el && value !== undefined && value !== null) {+ el.textContent = value;+ }+ };++ if (status) status.textContent = '';++ if (json['error']) {+ if (progressBar) progressBar.classList.add('bg-danger');+ if (status) {+ status.classList.add('text-danger');+ status.textContent = json['error'];+ }++ enableBtn();+ //stop on fatal errors instead of continuing to the next step+ return;+ }++ let percent = (json['position'] || 0) * 100 / (json['count'] || 1);++ if (json['success']) {+ if (progressBar) progressBar.style.width = "100%";+ if (status) {+ status.classList.remove('text-danger');+ status.classList.add('text-success');+ status.textContent = json['success'];+ }++ enableBtn();+ }++ if (json['theme']) {+ if (status) {+ status.classList.remove('text-danger', 'text-success');+ status.textContent = json['theme'];+ }+ } else if (json['table']) {+ if (status) {+ status.classList.remove('text-danger', 'text-success');+ status.textContent = json['table'];+ }+ }++ if (json['file']) setText('progress-file', json['file']);+ if (json['position'] !== undefined) setText('progress-position', json['position']);+ if (json['count'] !== undefined) setText('progress-count', json['count']);+ if (json['theme']) setText('progress-theme', json['theme']);++ if (json['url'] && (!json['count'] || (json['position'] < json['count']))) {+ next = json['url'];++ ajaxStack.add(request);+ } else {+ percent = 100;+ if (progressBar) {+ progressBar.classList.add('bg-success');+ progressBar.style.width = '100%';+ }+ enableBtn();++ if (json['success']) {+ let url = window.location.href;+ if (url.indexOf('success=') === -1) {+ url += (url.indexOf('?') > -1 ? '&' : '?') + 'success=' + encodeURIComponent(json['success']);+ window.location.href = url;+ } else {+ window.location.reload();+ }+ } else if (window.navigation?.reload) {+ window.navigation.reload();+ } else {+ window.location.reload();+ }+ }++ if (progressBar) progressBar.style.width = percent + '%';+ })+ .catch(error => {+ let response, responseInText;++ if (Array.isArray(error)) {+ [response, responseInText] = error;+ }++ let message = responseInText || response?.statusText || error?.message || "Error!";+ message = String(message);++ if (typeof displayToast === "function") {+ displayToast("danger", "Error", message);+ }++ const progressSuccess = document.getElementById('progress-success');+ if (progressSuccess) progressSuccess.textContent = '';++ const progressStatus = document.getElementById('progress-status');+ if (progressStatus) {+ progressStatus.classList.add('text-danger');+ progressStatus.textContent = message;+ }++ const progressBar = document.getElementById('progress-bar');+ if (progressBar) progressBar.classList.add('bg-danger');++ enableBtn();+ console.error(error);+ });+ };++ ajaxStack.add(request);+ }++ make(url, params = {}, btn = false) {+ url = url ?? (window.location.pathname + '?module=tools/themes-backup&action=save');+ //if params contains themes array, we keep as array for POST body but also need to ensure URL carries themes for next steps via GET+ //The controller's save will create folder and return next url with themes encoded, so initial make only needs folder creation+ return this.action(url, params, btn);+ }++ restore(url, params = {}, btn = false) {+ return this.action(url, params, btn);+ }++}++let ThemesBackup = new ThemesBackupController();+export {ThemesBackup};++window.ThemesBackup = ThemesBackup;diff --git a/public/js/admin/controller/themes.js b/public/js/admin/controller/themes.jsindex 0b3ca28..547d04a 100755--- a/public/js/admin/controller/themes.js+++ b/public/js/admin/controller/themes.js@@ -1,60 +1,94 @@import {Themes as ThemesModel} from '../model/themes.js';+function showImportModal() {+ let modal = document.getElementById("importModal");++ if (modal && window.bootstrap?.Modal) {+ bootstrap.Modal.getOrCreateInstance(modal).show();+ }+}+class ThemesController {- install(e) {- let element = e.currentTarget;+ install(e, element) {+ element = element ?? e.currentTarget;+ if (!element || !element.dataset) {+ return;+ }+let slug = element.dataset.slug;let market = element.dataset.market;-+ let loading = element.querySelector('.loading');+ let text = element.querySelector('.button-text');+element.classList.add("loading");-- element.querySelector('.loading').toggleClass("d-none");- element.querySelector('.button-text').toggleClass("d-none");-++ if (loading) loading.classList.remove("d-none");+ if (text) text.classList.add("d-none");+ThemesModel.install(market, slug, function () {setTimeout(function () {element.classList.remove("loading");- element.querySelector('.loading').toggleClass("d-none");- element.querySelector('.button-text').toggleClass("d-none");-+ if (loading) loading.classList.add("d-none");+ if (text) text.classList.remove("d-none");}, 5000);});-++ showImportModal();e.preventDefault();}-++ showModal() {+ let modal = document.getElementById("importModal");++ if (modal && window.bootstrap?.Modal) {+ bootstrap.Modal.getOrCreateInstance(modal).show();+ }+ }+importModal(e) {- document.getElementById("importModal").modal('show');+ showImportModal();e.preventDefault();}-- importTheme(e) {- document.getElementById("import-iframe").style.display = "";- document.getElementById("import-form").submit();- document.getElementById("import-options").style.display = "none";- e.target.style.display = "none";++ importTheme(e, element) {+ element = element ?? e.target;+ let iframe = document.getElementById("import-iframe");+ let form = document.getElementById("import-form");+ let options = document.getElementById("import-options");++ if (iframe) iframe.style.display = "";+ if (form) form.submit();+ if (options) options.style.display = "none";+ if (element) element.style.display = "none";+ e.preventDefault();}- import(e) {- console.log(document.getElementById("import-form").serialize());+ import(e, element) {+ let form = document.getElementById("import-form");+ if (form) {+ console.log(new URLSearchParams(new FormData(form)).toString());+ }}-- activate(e) {- let element = e.currentTarget;++ activate(e, element) {+ element = element ?? e.currentTarget;+ if (!element || !element.dataset) {+ return;+ }+let slug = element.dataset.slug;let market = element.dataset.market;-+element.classList.add("loading");-+ThemesModel.install(market, slug, function () {setTimeout(function () {element.classList.remove("loading");}, 5000);});-- document.getElementById("importModal").modal('show');-++ showImportModal();e.preventDefault();}}diff --git a/public/js/admin/controller/update.js b/public/js/admin/controller/update.jsindex 13d6938..02b6dbd 100755--- a/public/js/admin/controller/update.js+++ b/public/js/admin/controller/update.js@@ -2,16 +2,23 @@ class UpdateController {action(url, btn) {let next = url;- document.getElementById("progress").classList.remove("d-none");+ let progress = document.getElementById("progress");+ if (progress) progress.classList.remove("d-none");function disableBtn() {- btn.querySelector('.loading').classList.remove('d-none');- btn.querySelector('.button-text').classList.add('d-none');+ if (!btn) return;+ let loading = btn.querySelector('.loading');+ let text = btn.querySelector('.button-text');+ if (loading) loading.classList.remove('d-none');+ if (text) text.classList.add('d-none');}function enableBtn() {- btn.querySelector('.loading').classList.add('d-none');- btn.querySelector('.button-text').classList.remove('d-none');+ if (!btn) return;+ let loading = btn.querySelector('.loading');+ let text = btn.querySelector('.button-text');+ if (loading) loading.classList.add('d-none');+ if (text) text.classList.remove('d-none');}disableBtn();@@ -20,46 +27,56 @@ class UpdateController {return fetch(next, {method: "POST", headers: {"X-Requested-With": "XMLHttpRequest","Content-Type": "application/x-www-form-urlencoded",- }, body: new URLSearchParams({csrf: document.querySelector('[name=csrf]')?.value})})+ }, body: new URLSearchParams({csrf: document.querySelector('[name=csrf]')?.value ?? ""})}).then((response) => {next = false;if (!response.ok) {return Promise.resolve(response.text()).then((responseInText) => {return Promise.reject([response, responseInText]);});- }- if (!response.ok) {- let message = response.statusText + " " + response.body();- throw new Error(message);}return response.json()}).then((json) => {- document.getElementById('progress-message').innerHTML = '';+ let progressMessage = document.getElementById('progress-message');+ let progressError = document.getElementById('progress-error');+ let progressSuccess = document.getElementById('progress-success');+ const progressBar = document.getElementById('progress-bar');++ if (progressMessage) progressMessage.textContent = '';if (json['error']) {- document.getElementById('progress-bar').classList.add('bg-danger');- document.getElementById('progress-error').innerHTML = '<div class="text-danger">' + json['error'] + '</div>';+ if (progressBar) progressBar.classList.add('bg-danger');+ if (progressError) {+ progressError.textContent = json['error'];+ }enableBtn();+ //stop on fatal errors instead of marking the update as successful+ return;}- let percent = (json['position']) * 100 / json['count'];+ let percent = (json['position'] || 0) * 100 / (json['count'] || 1);if (json['success']) {//document.getElementById('progress-bar').style.width = '100%';.classList.add('bg-success');- document.getElementById('progress-success').innerHTML = '<div class="text-success">' + json['success'] + '</div>';+ if (progressSuccess) {+ progressSuccess.classList.add('text-success');+ progressSuccess.textContent = json['success'];+ }enableBtn();}- if (json['info']) {- document.getElementById('progress-message').innerHTML = json['info'];+ if (json['info'] && progressMessage) {+ //server generated status with an optional badge+ progressMessage.innerHTML = json['info'];}if (json['step']) {- document.getElementById('progress-status').innerHTML = json['step'];+ const progressStatus = document.getElementById('progress-status');+ if (progressStatus) progressStatus.textContent = json['step'];}if (json['url'] && json['step'] && !json['error']) {@@ -69,9 +86,9 @@ class UpdateController {} else {percent = 100;- document.getElementById('progress-bar').classList.add('bg-success');+ if (progressBar) progressBar.classList.add('bg-success');enableBtn();- document.getElementById('progress-bar').style.width = '100%';+ if (progressBar) progressBar.style.width = '100%';return;if (json['success']) {@@ -83,36 +100,40 @@ class UpdateController {}}- document.getElementById('progress-bar').style.width = percent + '%';+ if (progressBar) progressBar.style.width = percent + '%';})/*.then((json) => {if (next) {ajaxStack.add(request);}})*/.catch(error => {- let [response, responseInText] = error;- let message = response.statusText ?? "Error!";- displayToast("danger", "Error", message);+ let response, responseInText;++ if (Array.isArray(error)) {+ [response, responseInText] = error;+ }++ let message = responseInText || response?.statusText || error?.message || "Error!";+ message = String(message);- if (error.hasOwnProperty('text')) error.text().then( errorMessage => {- let message = errorMessage.substr(0, 200);+ if (typeof displayToast === "function") {displayToast("danger", "Error", message);- });+ }++ const success = document.getElementById('progress-success');+ if (success) success.textContent = '';++ const progressMessage = document.getElementById('progress-message');+ if (progressMessage) {+ progressMessage.classList.add('text-danger');+ progressMessage.textContent = message;+ }++ const progressBar = document.getElementById('progress-bar');+ if (progressBar) progressBar.classList.add('bg-danger');- if (typeof error.json === "function") {- error.json().then(jsonError => {- message = jsonError;- }).catch(genericError => {- message = error?.statusText + " " + message;- });- }-- console.log(error);- document.getElementById('progress-success').innerHTML = '';- document.getElementById('progress-message').innerHTML = '<div class="text-danger">' + message + '</div>';- //console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);- document.getElementById('progress-bar').classList.add('bg-danger');enableBtn();+ console.error(error);});};