Skip to content

armgit / Vvveb

Public Imported from GitHub
0

Powerful and easy to use cms to build websites, blogs or ecommerce stores.

Reject state changing actions over GET and remove GET id fallbacks, fix for GHSA-grxp-rj92-j8xr, reported by @vq4s

Givan5f5877165881
diff --git a/admin/controller/base.php b/admin/controller/base.php
index 9a0a801..6b8db67 100755
--- a/admin/controller/base.php
+++ b/admin/controller/base.php
@@ -25,11 +25,12 @@ namespace Vvveb\Controller;
use function Vvveb\__;
use function Vvveb\arrayInsertArrayAfter;
use function Vvveb\filter;
-use Vvveb\Sql\taxonomySQL;
+use Vvveb\Sql\TaxonomySQL;
use Vvveb\System\Cache;
use Vvveb\System\CacheManager;
use Vvveb\System\Core\FrontController;
use Vvveb\System\Core\Request;
+use Vvveb\System\Core\Response;
use Vvveb\System\Core\View;
use Vvveb\System\Event;
use Vvveb\System\Extensions\Plugins;
@@ -46,28 +47,44 @@ use Vvveb\System\User\Admin;
class Base {
use Permission;
- public $view;
+ /** @var View View instance injected by FrontController DI. */
+ public View $view;
- public $request;
+ /** @var Request Request instance injected by FrontController DI. */
+ public Request $request;
- public $sesssion;
+ /** @var Response Response instance injected by FrontController DI. */
+ public Response $response;
- protected $global;
+ /** @var Session Session instance injected by FrontController DI. */
+ public Session $session;
- protected function setSite($site_id = false) {
+ /** @var array<string, mixed> Global template variables */
+ protected array $global = [];
+
+ /** @var array<int, array<string, mixed>> Taxonomy records for current site */
+ protected array $taxonomies = [];
+
+ /**
+ * Set the current site and store its details in the session.
+ *
+ * @param int|false $site_id Site ID to set, or false for default
+ *
+ * @return int The site_id that was set
+ */
+ protected function setSite(int|false $site_id = false): int {
//if no id set default
if ($site_id) {
$site = Sites::getSiteById($site_id);
}
- if (! $site_id || ! $site) {
+ if (!$site_id || !$site) {
$site = Sites::getDefault();
}
$this->session->set('site', $site);
- $this->session->set('site_id', $site_id);
+ $this->session->set('site_id', $site['site_id']);
$this->session->set('site_url', $site['url']);
- $this->session->set('site', $site['site_id']);
$this->session->set('host', $site['host']);
$this->session->set('path', $site['path'] ?? '');
$this->session->set('state', $site['state'] ?? 'live');
@@ -75,40 +92,50 @@ class Base {
return $site['site_id'];
}
- protected function getTaxonomies() {
- $categories = new taxonomySQL();
+ /**
+ * Get all taxonomies for the current global context.
+ *
+ * @return array<int, array<string, mixed>> Array of taxonomy records
+ */
+ protected function getTaxonomies(): array {
+ $categories = new TaxonomySQL();
$taxonomies = $categories->getAll($this->global);
return $taxonomies['taxonomy'] ?? [];
}
- protected function customPost() {
+ /**
+ * Build the custom post types menu structure.
+ *
+ * @return array<string, array<string, mixed>> Associative array of post type menu items
+ */
+ protected function customPost(): array {
//custom posts -- add to menu
$default_custom_posts =
[
'post' => [
- 'type' => 'post',
- 'plural' => 'posts',
- 'icon' => 'icon-document-text-outline',
- 'comments'=> true,
+ 'type' => 'post',
+ 'plural' => 'posts',
+ 'icon' => 'file-text',
+ 'comments' => true,
],
'page' => [
- 'type' => 'page',
- 'plural' => 'pages',
- 'icon' => 'icon-document-outline',
- 'comments'=> false,
+ 'type' => 'page',
+ 'plural' => 'pages',
+ 'icon' => 'file',
+ 'comments' => false,
],
];
$custom_posts_types = \Vvveb\getSetting('post', 'types', []);
$custom_posts_types += $default_custom_posts;
- list($custom_posts_types) = Event::trigger('Vvveb\postTypes', __FUNCTION__, $custom_posts_types);
+ [$custom_posts_types] = Event::trigger('Vvveb\postTypes', __FUNCTION__, $custom_posts_types);
$custom_post_menu = \Vvveb\config('custom-post-menu', []);
$posts_menu = [];
foreach ($custom_posts_types as $type => $settings) {
- if ($type == 'page') {
+ if ($type === 'page') {
continue;
}
$posts_menu[$type] = $custom_post_menu;
@@ -121,7 +148,7 @@ class Base {
$posts_menu[$type]['icon-img'] = (isset($settings['icon-img']) && $settings['icon-img']) ? Images::image($settings['icon-img'], $type) : '';
$posts_menu[$type]['url'] .= "&type=$type";
- if (isset($settings['comments']) && ! $settings['comments']) {
+ if (isset($settings['comments']) && !$settings['comments']) {
unset($posts_menu[$type]['items']['comments']);
}
@@ -134,12 +161,12 @@ class Base {
$admin_path = \Vvveb\adminPath();
//add taxonomies for post type
foreach ($this->taxonomies as $taxonomy) {
- if ($taxonomy['post_type'] != $type) {
+ if ($taxonomy['post_type'] !== $type) {
continue;
}
$key = $taxonomy['post_type'] . '_' . $taxonomy['type'] . $taxonomy['taxonomy_id'];
$module = "content/{$taxonomy['type']}";
- $icon = $taxonomy['type'] == 'tags' ? 'la la-tags' : 'la la-boxes';
+ $icon = $taxonomy['type'] === 'tags' ? 'tags' : 'package';
$tax = [$key => [
'name' => __($taxonomy['name']),
//'subtitle' => __('(Flat)'),
@@ -156,26 +183,31 @@ class Base {
return $posts_menu;
}
- protected function customProduct() {
+ /**
+ * Build the custom product types menu structure.
+ *
+ * @return array<string, array<string, mixed>> Associative array of product type menu items
+ */
+ protected function customProduct(): array {
//custom products -- add to menu
$default_custom_products =
[
'product' => [
'type' => 'product',
'plural' => 'products',
- 'icon' => 'icon-cube-outline',
+ 'icon' => 'box',
],
];
$custom_products_types = \Vvveb\getSetting('product', 'types', []);
$custom_products_types += $default_custom_products;
- list($custom_products_types) = Event::trigger('Vvveb\postTypes', __FUNCTION__, $custom_products_types);
+ [$custom_products_types] = Event::trigger('Vvveb\postTypes', __FUNCTION__, $custom_products_types);
$custom_product_menu = \Vvveb\config('custom-product-menu', []);
$products_menu = [];
foreach ($custom_products_types as $type => $settings) {
- if ($type == 'page') {
+ if ($type === 'page') {
continue;
}
$products_menu[$type] = $custom_product_menu;
@@ -197,13 +229,13 @@ class Base {
$admin_path = \Vvveb\adminPath();
//add taxonomies for post type
foreach ($this->taxonomies as $taxonomy) {
- if ($taxonomy['post_type'] != $type) {
+ if ($taxonomy['post_type'] !== $type) {
continue;
}
$key = $taxonomy['post_type'] . '_' . $taxonomy['type'] . $taxonomy['taxonomy_id'];
$module = "content/{$taxonomy['type']}";
- $icon = $taxonomy['type'] == 'tags' ? 'la la-tags' : 'la la-boxes';
+ $icon = $taxonomy['type'] === 'tags' ? 'tags' : 'package';
$tax = [$key => [
'name' => __($taxonomy['name']),
//'subtitle' => __('(Flat)'),
@@ -220,8 +252,17 @@ class Base {
return $products_menu;
}
- protected function language($defaultLanguage = false, $defaultLanguageId = false, $defaultLocale = false, $defaultCode = false, $languages = null) {
- $languages = $languages ?? Locale::availableLanguages();
+ /**
+ * Set the current language and locale for the session.
+ *
+ * @param string|false $defaultLanguage Default language code
+ * @param string|false $defaultLanguageId Default language ID
+ * @param string|false $defaultLocale Default locale string
+ * @param string|false $defaultCode Default locale code (e.g. en_US)
+ * @param array<string, array<string, mixed>>|null $languages Available languages array
+ */
+ protected function language(string|false $defaultLanguage = false, string|false $defaultLanguageId = false, string|false $defaultLocale = false, string|false $defaultCode = false, ?array $languages = null): void {
+ $languages ??= Locale::availableLanguages();
$default_language = $this->session->get('default_language');
$default_language_id = $this->session->get('default_language_id');
@@ -229,8 +270,11 @@ class Base {
$default_code = $this->session->get('default_code');
$default_rtl = false;
$site_language = false;
+ $site_language_id = false;
+ $site_locale = false;
+ $site_code = false;
- if (($lang = ($this->request->post['language'] ?? false)) && ! is_array($lang)) {
+ if (($lang = ($this->request->post['language'] ?? false)) && !is_array($lang)) {
$language = filter('/[A-Za-z_-]+/', $lang, 10);
if (isset($languages[$language])) {
@@ -244,7 +288,7 @@ class Base {
}
}
- if (! $default_language) {
+ if (!$default_language) {
foreach ($languages as $code => $lang) {
//set site language
if ($defaultLanguageId && ($defaultLanguageId == $lang['language_id'])) {
@@ -274,12 +318,12 @@ class Base {
}
//no valid default site or global language? set english as default
- if (! $default_language) {
+ if (!$default_language) {
$default_language = 'en';
$default_language_id = 1;
$default_locale = 'en-us';
- $default_code = 'en_US';
- $default_rtl = false;
+ $default_code = 'en_US';
+ $default_rtl = false;
}
$this->session->set('default_language', $default_language);
@@ -296,8 +340,8 @@ class Base {
$rtl = $this->session->get('rtl') ?? false;
//if no default language configured then set first language as current language
- if (! isset($languages[$language])) {
- $language = null;
+ if (!isset($languages[$language])) {
+ $language = null;
$default_language = key($languages);
$lang = $languages[$default_language] ?? [];
@@ -310,7 +354,7 @@ class Base {
}
//if no language configured then set default language as current language
- if (! $language) {
+ if (!$language) {
$language = $default_language;
$language_id = $default_language_id;
$locale = $default_locale;
@@ -333,7 +377,7 @@ class Base {
$this->global['default_locale'] = $default_locale;
$this->global['default_language_id'] = $default_language_id;
- if (! $sessLang) {
+ if (!$sessLang) {
$this->session->set('language', $language);
$this->session->set('language_id', $language_id);
$this->session->set('locale', $locale);
@@ -343,14 +387,20 @@ class Base {
Locale::setLanguage($code);
- if (! defined('CLI')) {
+ if (!defined('CLI')) {
$view = $this->view;
$view->languagesList = $languages;
}
}
- protected function currency($defaultCurrency = false, $defaultCurrencyId = false) {
- if (($currency = ($this->request->post['currency'] ?? false)) && ! is_array($currency)) {
+ /**
+ * Set the current currency for the session.
+ *
+ * @param string|false $defaultCurrency Default currency code
+ * @param string|false $defaultCurrencyId Default currency ID
+ */
+ protected function currency(string|false $defaultCurrency = false, string|false $defaultCurrencyId = false): void {
+ if (($currency = ($this->request->post['currency'] ?? false)) && !is_array($currency)) {
$currency = filter('/[A-Za-z_-]+/', $currency, 50);
$currencies = Locale::availableCurrencies();
@@ -365,13 +415,13 @@ class Base {
$currency = $this->session->get('currency');
$currency_id = $this->session->get('currency_id');
- if (! $currency || ! $currency_id) {
+ if (!$currency || !$currency_id) {
$currencies = Locale::availableCurrencies();
if ($currencies) {
foreach ($currencies as $code => $c) {
- if ($defaultCurrency && ($defaultCurrency == $c['code']) ||
- ($defaultCurrencyId && ($defaultCurrencyId == $c['currency_id']))) {
+ if (($defaultCurrency && $defaultCurrency === $c['code']) ||
+ ($defaultCurrencyId && $defaultCurrencyId == $c['currency_id'])) {
$currency = $c['code'];
$currency_id = $c['currency_id'];
@@ -380,7 +430,7 @@ class Base {
}
//if no site currency configured set first available currency
- if (! $currency) {
+ if (!$currency) {
$c = reset($currencies);
$currency = $c['code'];
$currency_id = $c['currency_id'];
@@ -395,11 +445,11 @@ class Base {
$this->global['currency_id'] = $currency_id;
}
- function init() {
- //$this->session->delete('csrf');
- //$this->session = Session::getInstance();
- //$this->request = Request::getInstance();
- $view = View :: getInstance();
+ /**
+ * Initialize the controller: session, CSRF, language, currency, permissions, menu, and view.
+ */
+ public function init(): ?string {
+ $view = View::getInstance();
$view->removeVattrs(false);
if (isset($this->request->get['errors']) && $this->request->get['errors']) {
@@ -414,7 +464,7 @@ class Base {
$this->response->addHeader('X-Frame-Options', 'SAMEORIGIN');
$this->response->addHeader('X-Content-Type-Options', 'nosniff');
- if (! $this->session->get('csrf')) {
+ if (!$this->session->get('csrf')) {
$this->session->set('csrf', Str::random());
}
@@ -423,15 +473,15 @@ class Base {
$admin = Admin::current();
- if (! $admin) {
- return $this->requireLogin();
+ if (!$admin) {
+ $this->requireLogin();
}
//$className = get_class($this);
//$errorController = (strncmp($className, 'Vvveb\Controller\Error', 22) === 0);
- if (/*!$errorController && */! $this->checkCsrf()) {
- return;
+ if (/*!$errorController && */ !$this->checkCsrf()) {
+ return null;
}
if (($site_id = ($this->request->post['site'] ?? false)) && is_numeric($site_id)) {
@@ -440,7 +490,7 @@ class Base {
$site_id = $this->session->get('site_id');
- if (! $site_id) {
+ if (!$site_id) {
$site_id = $this->setSite(SITE_ID);
}
@@ -481,8 +531,8 @@ class Base {
//}
//load plugins for active site if safe mode is not selected
- if (! isset($admin['safemode']) || ! $admin['safemode']) {
- Plugins :: loadPlugins($site_id);
+ if (!isset($admin['safemode']) || !$admin['safemode']) {
+ Plugins::loadPlugins($site_id);
}
if ($errors = $this->session->get('errors')) {
@@ -505,14 +555,15 @@ class Base {
//don't initialize menu items for CLI
if (defined('CLI')) {
- return;
+ return null;
}
- $cacheDriver = Cache :: getInstance();
+ $cacheDriver = Cache::getInstance();
$cacheKey = $this->global['admin_id'] . '.' . $this->global['site_id'] . '.' . $this->global['language_id'];
- if ($menu = $cacheDriver->get('admin-menu', $cacheKey)) {
- } else {
+ $menu = $cacheDriver->get('admin-menu', $cacheKey);
+
+ if (!$menu) {
$menu = \Vvveb\config('admin-menu', []);
//custom posts -- add to menu
@@ -524,13 +575,13 @@ class Base {
$products_menu = $this->customProduct();
$menu = arrayInsertArrayAfter('sales', $menu, $products_menu);
- list($menu) = Event::trigger(__CLASS__, __FUNCTION__ . '-menu', $menu);
+ [$menu] = Event::trigger(__CLASS__, __FUNCTION__ . '-menu', $menu);
$urls = [];
$this->getPermissionsFromUrl($menu, $urls);
$permissions = Admin::hasPermission($urls);
//$urls = array_map(fn ($value) => $value ? ($permissions[$value] ?? false) : false, $urls);
- $urls = array_map(function ($value) use ($permissions) { return $value ? ($permissions[$value] ?? false) : false; }, $urls);
+ $urls = array_map(fn ($value) => $value ? ($permissions[$value] ?? false) : false, $urls);
$this->setPermissionsFromUrl($menu, $urls);
$cacheDriver->set('admin-menu', $cacheKey, $menu);
@@ -539,18 +590,29 @@ class Base {
$view->menu = $menu;
$view->global = $this->global;
- //send to view for button visibillity check
- $this->view->actionPermissions = $this->actionPermissions ?? [];
- $this->view->modulePermissions = $this->modulePermissions ?? [];
+ //send to view for button visibility check
+ $this->view->actionPermissions = $this->actionPermissions;
+ $this->view->modulePermissions = $this->modulePermissions;
$view->adminPath = $adminPath;
$view->publicPath = PUBLIC_PATH;
$view->mediaPath = PUBLIC_PATH . 'media';
Event::trigger(__CLASS__, __FUNCTION__);
+
+ return null;
}
- protected function redirect($url = '/', $parameters = [], $stop = true) {
+ /**
+ * Redirect to a URL with optional parameters.
+ *
+ * @param array<string, mixed>|string $url The URL to redirect to
+ * @param array<string, mixed> $parameters Query parameters to append
+ * @param bool $stop Whether to stop execution after redirect
+ *
+ * @return void
+ */
+ protected function redirect(array|string $url = '/', array $parameters = [], bool $stop = true): void {
$redirect = \Vvveb\url($url, $parameters);
if ($redirect) {
@@ -564,15 +626,16 @@ class Base {
FrontController::closeConnections();
PageCache::getInstance()->cleanUp();
- die(0);
+ exit();
}
}
/**
* Call this method if the action requires login, if the user is not logged in, a login form will be shown.
*
+ * @return never
*/
- protected function requireLogin() {
+ protected function requireLogin(): never {
//return \Vvveb\System\Core\FrontController::redirect('user/login');
//$view = view :: getInstance();
$admin_path = \Vvveb\adminPath();
@@ -583,19 +646,19 @@ class Base {
$this->view->render();
- die(0);
+ exit();
}
/**
* Call this method on form posts to protect against csrf attacks.
*
+ * @return bool True if CSRF is valid, false otherwise (will call notFound)
*/
- protected function checkCsrf() {
- if (! defined('CLI') &&
+ protected function checkCsrf(): bool {
+ if (!defined('CLI') &&
(($method = $this->request->getMethod()) == 'post') &&
- (! ($csrf = $this->session->get('csrf')) || ! ($postCsrf = ($this->request->post['csrf'] ?? false)) || ($csrf != $postCsrf))) {
+ (!($csrf = $this->session->get('csrf')) || !($postCsrf = ($this->request->post['csrf'] ?? false)) || ($csrf != $postCsrf))) {
$this->notFound('Invalid csrf!', 403);
- return false;
}
return true;
@@ -604,39 +667,41 @@ class Base {
/**
* Shows a "Not found", "Internal server error" or "Permission denied" page.
*
- * @param unknown_type $code
- * @param mixed $statusCode
- * @param mixed $service
- * @param mixed $message
+ * @param array<string, mixed>|string|false $message Error message to display
+ * @param int $statusCode HTTP status code (404, 500, 403, etc.)
+ * @param mixed $service Service or controller to handle the error
+ *
+ * @return never
*/
- protected function notFound($message = false, $statusCode = 404, $service = false) {
- return FrontController::notFound($service, $message, $statusCode);
+ protected function notFound(string|array|false $message = false, int $statusCode = 404, mixed $service = false): never {
+ FrontController::notFound($service, $message, $statusCode);
}
/**
* Generates the documentation link for current page.
*
- * @param unknown_type $code
- * @param null|mixed $module
- * @param null|mixed $action
+ * @param string|null $module Module name, or null to use request value
+ * @param string|null $action Action name, or null to use request value
+ *
+ * @return string The documentation URL
*/
- protected function getDocUrlForPage($module = null, $action = null) {
- $module = $module ?? $this->request->get['module'] ?? '';
- $action = $action ?? $this->request->get['origaction'] ?? '';
- $type = $type ?? $this->request->get['type'] ?? '';
+ protected function getDocUrlForPage(?string $module = null, ?string $action = null): string {
+ $module ??= $this->request->get['module'] ?? '';
+ $action ??= $this->request->get['origaction'] ?? '';
+ $type = $this->request->get['type'] ?? '';
$action = $action ? '/' . $action : '';
- $url = 'https://docs.vvveb.com/';
+ $url = 'https://www.vvveb.com/docs/';
- if ($type == 'post' || $type == 'page'/* || $type == 'product'*/) {
- $type = $type ? '/' . $type : '';
+ if ($type === 'post' || $type === 'page'/* || $type == 'product'*/) {
+ $type = '/' . $type;
} else {
$type = '';
}
- $documentionList = include DIR_SYSTEM . 'data/documentation-map.php';
+ $documentationList = include DIR_SYSTEM . 'data/documentation-map.php';
- if (isset($documentionList[$module . $action . $type])) {
- $url .= $documentionList[$module . $action . $type];
+ if (isset($documentationList[$module . $action . $type])) {
+ $url .= $documentationList[$module . $action . $type];
} else {
$url .= str_replace('/', '-', $module . $action . $type);
}
@@ -644,9 +709,12 @@ class Base {
return $url;
}
- function goToHelp() {
+ /**
+ * Redirect to the documentation page for the current admin page.
+ */
+ public function goToHelp(): void {
$url = $this->getDocUrlForPage();
- return header("Location: $url");
+ header("Location: $url");
}
}
diff --git a/admin/controller/content/comments.php b/admin/controller/content/comments.php
index 6d5fc5a..14fe0af 100644
--- a/admin/controller/content/comments.php
+++ b/admin/controller/content/comments.php
@@ -26,22 +26,27 @@ use function Vvveb\__;
use Vvveb\Controller\Listing;
use function Vvveb\humanReadable;
use function Vvveb\model;
-use Vvveb\Sql\commentSQL;
+use Vvveb\Sql\CommentSQL;
use Vvveb\System\CacheManager;
use Vvveb\System\Core\View;
use Vvveb\System\Images;
use Vvveb\System\User\Admin;
class Comments extends Listing {
- protected $type = 'comment';
+ protected string $type = 'comment';
- protected $list = 'comment';
+ protected string $list = 'comment';
- protected $module = 'content';
+ protected string $module = 'content';
- protected $listController = 'comments';
+ protected string $listController = 'comments';
- function delete() {
+ /**
+ * Deletes comments, checking user capabilities first.
+ *
+ * @return void
+ */
+ public function delete(): void {
$editCapability = 'edit_other_posts';
if ($this->module == 'product') {
@@ -50,19 +55,23 @@ class Comments extends Listing {
if (Admin::hasCapability($editCapability)) {
$this->userFilter = false;
- } else {
}
parent::delete();
}
- function save() {
+ /**
+ * Changes the status of a comment (approve, spam, trash, etc.).
+ *
+ * @return void
+ */
+ public function save(): void {
$type = $this->type;
- $comment_id = $this->request->get[$type . '_id'] ?? $this->request->post[$type . '_id'] ?? false;
- $status = $this->request->get['newstatus'] ?? $this->request->post['newstatus'] ?? false;
+ $comment_id = $this->request->post[$type . '_id'] ?? false;
+ $status = $this->request->post['newstatus'] ?? false;
if ($comment_id) {
- $data = [$type => ['status' => (int) $status], $type . '_id' => $comment_id];
+ $data = [$type => ['status' => (int)$status], $type . '_id' => $comment_id];
$editCapability = 'edit_other_posts';
@@ -85,16 +94,21 @@ class Comments extends Listing {
}
}
- return $this->index();
+ $this->index();
}
- function index() {
- $view = View :: getInstance();
+ /**
+ * Lists all comments with filtering by status and capability checks.
+ *
+ * @return void
+ */
+ public function index(): void {
+ $view = View::getInstance();
$type = $this->type;
- $controller = $this->controller ?? $type;
- $listController = $this->listController ?? $controller;
+ $controller = $this->controller ?: $type;
+ $listController = $this->listController ?: $controller;
$module = $this->module;
- $list = $this->list ?? $type . 's';
+ $list = $this->list ?: $type . 's';
$status = $this->request->get['status'] ?? '';
$comment_status = [
@@ -106,11 +120,11 @@ class Comments extends Listing {
];
$status = $this->request->get['status'] ?? -1;
- //$comments = new commentSQL();
+ //$comments = new CommentSQL();
$comments = model($type);
$options = [
- 'type' => $type,
+ 'type' => $type,
] + $this->global;
unset($options['user_id']);
@@ -130,11 +144,11 @@ class Comments extends Listing {
}
$results = $comments->getAll($options);
- $results[$type] = $results[$type] ?? [];
+ $results[$type] ??= [];
foreach ($results[$type] as $id => &$comment) {
if (isset($comment['image'])) {
- $comment['image'] = Images::image($type, $comment['image']);
+ $comment['image'] = Images::image($comment['image'], $type);
}
if (isset($comment['avatar'])) {
diff --git a/admin/controller/content/menus.php b/admin/controller/content/menus.php
index d2381ee..7836d76 100644
--- a/admin/controller/content/menus.php
+++ b/admin/controller/content/menus.php
@@ -24,7 +24,7 @@ namespace Vvveb\Controller\Content;
use function Vvveb\__;
use function Vvveb\sanitizeHTML;
-use Vvveb\Sql\menuSQL;
+use Vvveb\Sql\MenuSQL;
use Vvveb\System\Images;
use Vvveb\System\Sites;
use function Vvveb\url;
@@ -32,20 +32,27 @@ use function Vvveb\url;
class Menus extends Categories {
use SitesTrait;
- function duplicate() {
+ /**
+ * Duplicates an existing menu and all its items.
+ *
+ * @return void
+ */
+ public function duplicate(): void {
$menu_id = $this->request->post['menu_id'] ?? false;
if ($menu_id) {
- $this->menus = new menuSQL();
+ $this->menus = new MenuSQL();
$data = $this->menus->get(['menu_id' => $menu_id]);
$old_id = $data['menu_id'];
unset($data['menu_id']);
- $id = rand(1, 1000);
+ $id = random_int(1, 1000000);
$data['name'] .= ' [' . __('duplicate') . ']';
//$data['slug'] .= '-' . __('duplicate') . "-$old_id-$id";
+ $site_id = [];
+
if (isset($data['menu_to_site'])) {
foreach ($data['menu_to_site'] as &$item) {
$site_id[] = $item['site_id'];
@@ -54,29 +61,30 @@ class Menus extends Categories {
if ($data) {
$result = $this->menus->addMenu([
- 'menu' => $data,
- 'site_id' => $site_id,
+ 'menu' => $data,
+ 'site_id' => $site_id,
]);
+ $type = __('menu');
+
if ($result && isset($result['menu'])) {
- $menu_id = $result['menu'];
+ $menu_id = $result['menu'];
$items = $this->menus->getMenuAllLanguages(['menu_id' => $old_id])['categories'] ?? [];
$parentId = [];
foreach ($items as &$item) {
- $old_menu_item_id = $item['menu_item_id'];
- $item['menu_id'] = $menu_id;
- $item['parent_id'] = $parentId[$item['parent_id']] ?? 0;
+ $old_menu_item_id = $item['menu_item_id'];
+ $item['menu_id'] = $menu_id;
+ $item['parent_id'] = $parentId[$item['parent_id']] ?? 0;
$item['menu_item_content'] = json_decode($item['languages'], true);
unset($item['menu_item_id']);
- $res = $this->menus->addMenuItem(['menu_item' => $item]);
- $menu_item_id = $res['menu_item'];
+ $res = $this->menus->addMenuItem(['menu_item' => $item]);
+ $menu_item_id = $res['menu_item'];
$parentId[$old_menu_item_id] = $menu_item_id;
}
$url = url(['module' => 'content/menus', 'action' => 'menu', 'menu_id' => $menu_id]);
- $type = __('menu');
$success = ucfirst($type) . ' ' . __('duplicated') . '!';
$success .= sprintf(' <a href="%s">%s</a>', $url, __('Edit') . ' ' . $type);
$this->view->success['get'] = $success;
@@ -86,13 +94,18 @@ class Menus extends Categories {
}
}
- return $this->index();
+ $this->index();
}
- function deleteMenu() {
+ /**
+ * Deletes an entire menu by ID.
+ *
+ * @return void
+ */
+ public function deleteMenu(): void {
$view = $this->view;
- $menu_id = $this->request->post['menu_id'] ?? $this->request->get['menu_id'] ?? false;
- $menu = new menuSQL();
+ $menu_id = $this->request->post['menu_id'] ?? false;
+ $menu = new MenuSQL();
if (is_numeric($menu_id)) {
$menu_id = [$menu_id];
@@ -113,13 +126,18 @@ class Menus extends Categories {
return;
}
- return $this->index();
+ $this->index();
}
- function delete() {
+ /**
+ * Deletes a single menu item by ID, including recursive deletion.
+ *
+ * @return never
+ */
+ public function delete(): never {
$menu_item_id = $this->request->post['menu_item_id'] ?? false;
$view = $this->view;
- $menus = new menuSQL();
+ $menus = new MenuSQL();
if ($menu_item_id) {
if (is_numeric($menu_item_id)) {
@@ -127,10 +145,10 @@ class Menus extends Categories {
}
try {
- //will fail on mysql 5
+ //will fail on mySQL 5
$result = $menus->deleteMenuItemRecursive(['menu_item_id' => $menu_item_id]);
} catch (\Exception $ex) {
- //older mysql versions don't have recursive CTE
+ //older mySQL versions don't have recursive CTE
$result = $menus->deleteMenuItem(['menu_item_id' => $menu_item_id]);
}
@@ -145,29 +163,37 @@ class Menus extends Categories {
echo __('No id!');
}
- die(0);
-
- return $this->index();
+ exit();
}
- function reorder() {
+ /**
+ * Reorders menu items based on submitted data.
+ *
+ * @return never
+ */
+ public function reorder(): never {
$data = $this->request->post;
- $menus = new menuSQL();
+ $menus = new MenuSQL();
//['menu_items' => $data]
if ($menus->updateMenuItems($data)) {
echo __('Items reordered!');
}
- die(0);
+ exit();
}
- function save() {
+ /**
+ * Saves a new or existing menu item.
+ *
+ * @return void
+ */
+ public function save(): void {
$data = $this->request->post;
- $menus = new menuSQL();
+ $menus = new MenuSQL();
- if (isset($data['item_id']) && ! is_numeric($data['item_id'])) {
+ if (isset($data['item_id']) && !is_numeric($data['item_id'])) {
unset($data['item_id']);
}
@@ -184,13 +210,13 @@ class Menus extends Categories {
if (isset($data['options'])) {
foreach ($data['options'] as $name => $value) {
- if (! $value) {
+ if ($value === '') {
unset($data['options'][$name]);
}
}
if ($data['options']) {
- $data['options'] = json_encode($data['options'], true);
+ $data['options'] = json_encode($data['options'], JSON_UNESCAPED_SLASHES);
} else {
$data['options'] = '';
}
@@ -228,12 +254,17 @@ class Menus extends Categories {
$this->response->output($response);
}
- function menu() {
+ /**
+ * Displays and saves a single menu's items with multilingual support.
+ *
+ * @return void
+ */
+ public function menu(): void {
$menuId = $this->request->get['menu_id'] ?? false;
$menu_data = $this->request->post['menu_data'] ?? false;
$site_id = $this->request->post['site'] ?? []; //[$this->global['site_id']];
$view = $this->view;
- $menus = new menuSQL();
+ $menus = new MenuSQL();
$page = $this->request->get['page'] ?? 1;
$results = [];
@@ -244,7 +275,7 @@ class Menus extends Categories {
'limit' => 100000,
] + $this->global;
- $results = $menus->getMenuAllLanguages($options);
+ $results = $menus->getMenuAllLanguages($options);
$placeholder = Images::image('placeholder.svg', 'menu_item');
foreach ($results['categories'] as &$menu) {
@@ -263,7 +294,7 @@ class Menus extends Categories {
if (isset($menu['options']['img'])) {
$menu['options']['img_url'] = Images::image($menu['options']['img'], 'menu_item');
} else {
- $menu['options']['img_url'] = $menu['options']['img_url'] ?? $placeholder;
+ $menu['options']['img_url'] ??= $placeholder;
}
} else {
$menu['options'] = ['img_url' => $placeholder];
@@ -278,7 +309,7 @@ class Menus extends Categories {
$id = $return['menu'];
$menu_site = $return['menu_to_site'];
- if (! $id && ! $menu_site) {
+ if (!$id && !$menu_site) {
$view->errors = ['No changes!'];
} else {
$view->success[] = __('Menu saved!');
@@ -289,17 +320,17 @@ class Menus extends Categories {
$results['menu_data'] = $menus->get($options);
} else {
if ($menu_data) {
- $menu_data = $menu_data + $this->global;
+ $menu_data += $this->global;
$return = $menus->addMenu(['menu' => $menu_data, 'site_id' => $site_id]);
$id = $return['menu'];
- if (! $id) {
- $view->errors = [$menu->error];
+ if (!$id) {
+ $view->errors = [$menus->error];
} else {
$success = __('Menu saved!');
$view->success[] = $success;
- $this->redirect(['module'=>'content/menus', 'action' => 'menu', 'menu_id' => $id, 'success' => $success]);
+ $this->redirect(['module' => 'content/menus', 'action' => 'menu', 'menu_id' => $id, 'success' => $success]);
$menu_data['menu_id'] = $id;
}
}
@@ -314,7 +345,7 @@ class Menus extends Categories {
if ($sites) {
$sites = array_keys($sites);
} else {
- if (! $menuId) {
+ if (!$menuId) {
$sites[] = $this->global['site_id'];
}
}
@@ -325,13 +356,18 @@ class Menus extends Categories {
$view->scanUrl = "$controllerPath&action=scan";
$view->uploadUrl = "$controllerPath&action=upload";
$view->linkUrl = $admin_path . 'index.php?module=content/post&action=urlAutocomplete';
- $theme = Sites::getTheme($this->global['site_id']) ?? 'default';
+ $theme = Sites::getTheme($this->global['site_id']);
$view->themeCss = PUBLIC_PATH . "themes/$theme/css/admin-post-editor.css";
}
- function index() {
+ /**
+ * Lists all menus with edit/delete URLs and multilingual names.
+ *
+ * @return void
+ */
+ public function index(): void {
$view = $this->view;
- $menus = new menuSQL();
+ $menus = new MenuSQL();
$options = [
'limit' => 10000,
diff --git a/admin/controller/order/order.php b/admin/controller/order/order.php
index 3eb0c06..752fcbc 100755
--- a/admin/controller/order/order.php
+++ b/admin/controller/order/order.php
@@ -26,12 +26,12 @@ use function Vvveb\__;
use Vvveb\Controller\Base;
use Vvveb\Controller\Content\AutocompleteTrait;
use function Vvveb\email;
+use function Vvveb\humanReadable;
use function Vvveb\orderStatusBadgeClass;
use function Vvveb\paymentStatusBadgeClass;
-use function Vvveb\prefixArrayKeys;
use function Vvveb\shippingStatusBadgeClass;
use function Vvveb\siteSettings;
-use Vvveb\Sql\Order_LogSQL;
+use Vvveb\Sql\Order_logSQL;
use Vvveb\Sql\OrderSQL;
use Vvveb\System\Cart\Cart;
use Vvveb\System\Cart\Currency;
@@ -48,20 +48,25 @@ use function Vvveb\url;
class Order extends Base {
use AutocompleteTrait;
- protected $type = 'order';
+ protected string $type = 'order';
- function index() {
- $site = siteSettings($this->global['site_id']);
- $options = array_intersect_key($site,
- array_flip(['weight_type_id', 'length_type_id', 'currency_id', 'country_id']));
+ /**
+ * Display the order edit form or order details.
+ *
+ * @return void
+ */
+ public function index(): void {
+ $site = siteSettings($this->global['site_id']);
+ $options = array_intersect_key(
+ $site,
+ array_flip(['weight_type_id', 'length_type_id', 'currency_id', 'country_id'])
+ );
$cart = Cart::getInstance($options);
$payment = Payment::getInstance();
$shipping = Shipping::getInstance();
$view = $this->view;
-
- $this->view->order_payment = $payment->getMethods([]);
- $this->view->order_shipping = $shipping->getMethods([]);
+ $order = [];
if (isset($this->request->get['order_id'])) {
$options = ['order_id' => (int)$this->request->get['order_id'], 'type' => $this->type] + $this->global;
@@ -95,8 +100,7 @@ class Order extends Base {
}
if (isset($product['image']) && $product['image']) {
- $product['image'] =Images::image($product['image'], 'product');
- //$product['images'][] = ['image' => Images::image($product['image'], 'product')];
+ $product['image'] = Images::image($product['image'], 'product');
}
$product['price_formatted'] = $currency->format($product['price']);
@@ -111,15 +115,34 @@ class Order extends Base {
$order = &$results['order'];
$order['user_url'] = \Vvveb\url(['module' => 'user/user', 'user_id' => $order['user_id']]);
$order['total_formatted'] = $currency->format($order['total']);
- $order['shipping_data'] = json_decode($order['shipping_data'] ?? '', true);
- $order['payment_data'] = json_decode($order['payment_data'] ?? '', true);
+ $shippingData = json_decode($order['shipping_data'] ?? '', true);
+ $paymentData = json_decode($order['payment_data'] ?? '', true);
+
+ if (!is_array($shippingData)) {
+ $shippingData = [];
+ }
+
+ if (!is_array($paymentData)) {
+ $paymentData = [];
+ }
+
+ $order['shipping_data'] = $shippingData;
+ $order['payment_data'] = $paymentData;
+
+ //human readable method titles, falling back to the stored method
+ //key (minus the -index suffix) when the gateway did not record one
+ $shippingMethod = preg_replace('/-\d+$/', '', (string)($order['shipping_method'] ?? ''));
+ $paymentMethod = preg_replace('/-\d+$/', '', (string)($order['payment_method'] ?? ''));
+ $order['shipping_title'] = $shippingData['title'] ?? $shippingData['gateway'] ?? ($shippingMethod ? humanReadable($shippingMethod) : '');
+ $order['payment_title'] = $paymentData['title'] ?? $paymentData['gateway'] ?? ($paymentMethod ? humanReadable($paymentMethod) : '');
+ $order['shipping_description'] = $shippingData['description'] ?? $shippingData['text'] ?? '';
+ $order['payment_description'] = $paymentData['description'] ?? $paymentData['text'] ?? '';
+ //legacy alias, the customer note column is `notes`
+ $order['comment'] = $order['notes'] ?? '';
$order['class'] = orderStatusBadgeClass($order['order_status_id']);
$order['payment_class'] = paymentStatusBadgeClass($order['payment_status_id']);
$order['shipping_class'] = shippingStatusBadgeClass($order['shipping_status_id']);
- $order += prefixArrayKeys('shipping_', $order['shipping_data']) ?? [];
- $order += prefixArrayKeys('payment_', $order['payment_data']) ?? [];
-
$data = $orders->getData($order);
$view->set($data);
@@ -131,8 +154,6 @@ class Order extends Base {
$view->printInvoiceUrl = \Vvveb\url(['action' => 'printInvoice'] + $url);
} else {
$this->notFound(__('Order not found!'));
-
- exit();
}
} else {
//new order
@@ -141,23 +162,232 @@ class Order extends Base {
$view->set($data);
}
- $this->view->order_payment = $payment->getMethods($order);
- $this->view->order_shipping = $shipping->getMethods($order);
+ $this->view->order_payment = $payment->getMethods($order);
+ $this->view->order_shipping = $shipping->getMethods($order);
+ $this->view->transactions = \Vvveb\System\PaymentLedger::forOrder($order['order_id'] ?? 0);
+ $this->view->remaining_capture = $this->remainingAmount((int)($order['order_id'] ?? 0), 'capture', (float)($order['total'] ?? 0));
+ $this->view->remaining_refund = $this->remainingAmount((int)($order['order_id'] ?? 0), 'refund', (float)($order['total'] ?? 0));
+
+ $paymentMethod = $order['payment_method'] ?? false;
+ $instance = $paymentMethod ? $payment->getMethodInstance($paymentMethod) : null;
+ //if payment method configuration has been deleted use payment plugin directly
+ if (!$instance && isset($order['payment_data']['class'])) {
+ $class = $order['payment_data']['class'];
+ $instance = new $class($cart);
+ }
+
+ $this->view->can_capture = (bool)($instance && $instance->supports('capture'));
+ $this->view->can_refund = (bool)($instance && $instance->supports('refund'));
+ $this->view->can_void = (bool)($instance && $instance->supports('void'));
+ }
+
+ /**
+ * Execute a capture, refund or void action on the order's payment method.
+ *
+ * @param string $action Payment method action to invoke (capture/refund/void).
+ * @param string $successMsg Success message shown to the admin.
+ * @param string $errorMsg Error message shown to the admin.
+ *
+ * @return void
+ */
+ private function paymentAction(string $action, string $successMsg, string $errorMsg): void {
+ $order_id = $this->request->post['order_id'] ?? false;
+
+ if (!$order_id) {
+ $this->view->errors[] = __('Order id missing!');
+
+ $this->index();
+
+ return;
+ }
+
+ $orders = new OrderSQL();
+ $results = $orders->get(['order_id' => (int)$order_id, 'type' => $this->type] + $this->global);
+
+ if (!isset($results['order']) || !$results['order']) {
+ $this->view->errors[] = __('Order not found!');
+
+ $this->index();
+
+ return;
+ }
+
+ $order = $results['order'];
+ $method = $order['payment_method'] ?? false;
+ $paymentData = json_decode($order['payment_data'] ?? '', true) ?: [];
+ $payment = Payment::getInstance();
+ $instance = $method ? $payment->getMethodInstance($method) : null;
+
+ if (!$instance || !$instance->supports($action)) {
+ $this->view->errors[] = __('Payment method does not support this action!');
+
+ $this->index();
+
+ return;
+ }
+
+ //optional partial amount, empty means the full remaining total
+ $amount = null;
+ $rawAmount = $this->request->post['amount'] ?? null;
+
+ if ($rawAmount !== null && $rawAmount !== '') {
+ if (!is_numeric($rawAmount) || (float)$rawAmount <= 0) {
+ $this->view->errors[] = __('Amount must be a positive number!');
+
+ $this->index();
+
+ return;
+ }
+
+ $amount = round((float)$rawAmount, 2);
+ }
+
+ if (in_array($action, ['capture', 'refund'], true)) {
+ $remaining = $this->remainingAmount((int)$order_id, $action, (float)($order['total'] ?? 0));
+
+ if ($amount !== null && $amount - $remaining > 0.005) {
+ $this->view->errors[] = sprintf(__('Amount exceeds the remaining %s!'), $remaining);
+
+ $this->index();
+
+ return;
+ }
+ }
+
+ $checkoutInfo = [
+ 'order_id' => (int)$order_id,
+ 'total' => $order['total'] ?? 0,
+ 'currency' => $order['currency'] ?? '',
+ ] + $paymentData;
+
+ if ($amount !== null) {
+ $checkoutInfo['amount'] = $amount;
+ }
+
+ if ($instance->$action($checkoutInfo)) {
+ $this->view->success[] = $successMsg;
+ } else {
+ $this->view->errors[] = $instance->getError() ?: $errorMsg;
+ }
+
+ $this->index();
+ }
+
+ /**
+ * Remaining capturable/refundable total from the money ledger.
+ *
+ * Capture draws on authorized (minus voided and captured) rows, refund on
+ * captured plus purchased (minus refunded) rows. Falls back to the order
+ * total when the ledger has no usable rows yet.
+ *
+ * @param int $orderId Order id.
+ * @param string $action `capture` or `refund`.
+ * @param float $total Order total fallback.
+ *
+ * @return float Remaining amount, never negative.
+ */
+ private function remainingAmount(int $orderId, string $action, float $total): float {
+ try {
+ $rows = \Vvveb\System\PaymentLedger::forOrder($orderId);
+ } catch (\Throwable $e) {
+ return $total;
+ }
+
+ if (!$rows) {
+ return $total;
+ }
+
+ $sum = function(array $kinds) use ($rows): float {
+ $sum = 0.0;
+
+ foreach ($rows as $row) {
+ if (($row['status'] ?? '') === 'succeeded' && in_array($row['kind'] ?? '', $kinds, true)) {
+ $sum += (float)($row['amount'] ?? 0);
+ }
+ }
+
+ return $sum;
+ };
+
+ if ($action === 'capture') {
+ $authorized = $sum(['authorize']) - $sum(['void']);
+
+ if ($authorized <= 0) {
+ return $total;
+ }
+
+ return max(0.0, round($authorized - $sum(['capture']), 2));
+ }
+
+ $captured = $sum(['capture']) + $sum(['purchase']);
+
+ if ($captured <= 0) {
+ return $total;
+ }
+
+ return max(0.0, round($captured - $sum(['refund']), 2));
+ }
+
+ /**
+ * Capture a previously authorized order payment through the payment method.
+ *
+ * @return void
+ */
+ public function capture(): void {
+ $this->paymentAction('capture', __('Payment captured!'), __('Payment capture failed!'));
+ }
+
+ /**
+ * Refund the order payment through the payment method.
+ *
+ * @return void
+ */
+ public function refund(): void {
+ $this->paymentAction('refund', __('Payment refunded!'), __('Payment refund failed!'));
}
- function print() {
- return $this->index();
+ /**
+ * Void/cancel the order payment through the payment method.
+ *
+ * @return void
+ */
+ public function void(): void {
+ $this->paymentAction('void', __('Payment canceled!'), __('Payment cancel failed!'));
}
- function printShipping() {
- return $this->index();
+ /**
+ * Print the order.
+ *
+ * @return void
+ */
+ public function print(): void {
+ $this->index();
+ }
+
+ /**
+ * Print the shipping details.
+ *
+ * @return void
+ */
+ public function printShipping(): void {
+ $this->index();
}
- function printInvoice() {
- return $this->index();
+ /**
+ * Print the invoice.
+ *
+ * @return void
+ */
+ public function printInvoice(): void {
+ $this->index();
}
- function cart() {
+ /**
+ * Add a product to the order cart.
+ *
+ * @return void
+ */
+ public function cart(): void {
$order_id = $this->request->get['order_id'] ?? false;
$product_id = $this->request->post['product_id'] ?? false;
$quantity = $this->request->post['quantity'] ?? 1;
@@ -166,7 +396,7 @@ class Order extends Base {
$price = $this->request->post['price'] ?? 1;
if ($order_id && $product_id) {
- $product = compact('product_id','quantity', 'name', 'price', 'model');
+ $product = compact('product_id', 'quantity', 'name', 'price', 'model');
$site = siteSettings($this->global['site_id']);
$options = $this->global + $site;
@@ -181,9 +411,20 @@ class Order extends Base {
$this->index();
}
- private function sendNotification($order_id, $customer_order_id, $email, $message) {
+ /**
+ * Send an email notification about an order update.
+ *
+ * @param int|string $order_id The internal order ID.
+ * @param string $customer_order_id The customer-facing order ID.
+ * @param string $email The recipient email address.
+ * @param string $message The notification message.
+ *
+ * @return void
+ */
+ private function sendNotification(int|string $order_id, string $customer_order_id, string $email, string $message): void {
+ $error = __('Error sending order confirmation mail!');
+
try {
- $error = __('Error sending order confirmation mail!');
$title = sprintf(__('Order update #%s'), $customer_order_id);
$options = ['order_id' => $order_id] + $this->global;
@@ -191,10 +432,16 @@ class Order extends Base {
$orders = new OrderSQL();
$results = $orders->get($options);
- if (! email([$email], $title, 'order/update', ['message' => $message, 'title' => $title] + $results + $this->global, [], 'app')) {
- $this->session->set('errors', $error);
- $this->view->errors[] = $error;
- }
+ \Vvveb\System\Notifications::trigger('order.status_change', ['message' => $message, 'title' => $title] + ($results ?? []) + $this->global + [
+ 'subject' => $title,
+ ]);
+
+ /*
+ if (! email([$email], $title, 'order/update', ['message' => $message, 'title' => $title] + $results + $this->global, [], 'app')) {
+ $this->session->set('errors', $error);
+ $this->view->errors[] = $error;
+ }
+ */
} catch (\Exception $e) {
if (DEBUG) {
$error .= "\n" . $e->getMessage();
@@ -204,7 +451,12 @@ class Order extends Base {
}
}
- function saveLog() {
+ /**
+ * Save an order log entry and optionally send a notification.
+ *
+ * @return void
+ */
+ public function saveLog(): void {
$order_id = $this->request->get['order_id'] ?? false;
$customer_order_id = $this->request->post['customer_order_id'] ?? false;
$log = $this->request->post['log'] ?? [];
@@ -220,7 +472,7 @@ class Order extends Base {
$result = $order->edit(['order_id' => $order_id, 'order' => ['order_status_id' => $log['order_status_id']]]);
if (isset($result['order'])/* && $result['order']*/) {
- $orderLog = new Order_LogSQL();
+ $orderLog = new Order_logSQL();
$result = $orderLog->add(['order_id' => $order_id, 'order_log' => $log]);
if (isset($result['order_log']) && $result['order_log']) {
@@ -247,13 +499,18 @@ class Order extends Base {
}
}
- function save() {
- $validator = new Validator(['order']);
- $view = view :: getInstance();
+ /**
+ * Save the order from the request data.
+ *
+ * @return void
+ */
+ public function save(): void {
+ $validator = new Validator(['checkout', 'order', 'checkout_shipping', 'checkout_billing']);
+ $view = View::getInstance();
$order_id = $this->request->get['order_id'] ?? false;
$order = $this->request->post ?? [];
- $site = Sites :: getSiteData($this->global['site_id']);
+ $site = Sites::getSiteData($this->global['site_id']);
$order_url = url('user/orders', [
'host' => $site['host'] ?? false,
diff --git a/admin/controller/order/orders.php b/admin/controller/order/orders.php
index 604b64c..8f0048c 100755
--- a/admin/controller/order/orders.php
+++ b/admin/controller/order/orders.php
@@ -32,11 +32,16 @@ use Vvveb\System\Cart\Currency;
use Vvveb\System\Core\View;
class Orders extends Base {
- //check for order save permission
- protected $additionalPermissionCheck = ['order/order/save'];
+ /** @var list<string> Check for order save permission */
+ protected ?array $additionalPermissionCheck = ['order/order/save'];
- function delete() {
- $order_id = $this->request->post['order_id'] ?? $this->request->get['order_id'] ?? false;
+ /**
+ * Delete one or more orders.
+ *
+ * @return void
+ */
+ public function delete(): void {
+ $order_id = $this->request->post['order_id'] ?? false;
if ($order_id) {
if (is_numeric($order_id)) {
@@ -54,11 +59,16 @@ class Orders extends Base {
}
}
- return $this->index();
+ $this->index();
}
- function index() {
- $view = View :: getInstance();
+ /**
+ * Display the orders listing page.
+ *
+ * @return void
+ */
+ public function index(): void {
+ $view = View::getInstance();
$orders = new OrderSQL();
$currency = Currency::getInstance();
$this->filter = $this->request->get['filter'] ?? [];
diff --git a/admin/controller/settings/post-types.php b/admin/controller/settings/post-types.php
old mode 100644
new mode 100755
index 794b85c..84f77b0
--- a/admin/controller/settings/post-types.php
+++ b/admin/controller/settings/post-types.php
@@ -26,16 +26,22 @@ use Vvveb\Controller\Listing;
use function Vvveb\postTypes;
class PostTypes extends Listing {
- protected $type = 'post';
+ /** @var string The entity type identifier */
+ protected string $type = 'post';
- function delete() {
- $userType = $this->request->get['type'] ?? false;
+ /**
+ * Delete one or more post type entries.
+ *
+ * @return void
+ */
+ public function delete(): void {
+ $userType = $this->request->post['type'] ?? false;
if ($userType) {
$userPostTypes = \Vvveb\getSetting($this->type, 'types', []);
if ($userPostTypes) {
- if (! is_array($userType)) {
+ if (!is_array($userType)) {
$userType = [$userType];
}
@@ -48,10 +54,15 @@ class PostTypes extends Listing {
}
}
- return $this->index();
+ $this->index();
}
- function index() {
+ /**
+ * Display the list of post types.
+ *
+ * @return void
+ */
+ public function index(): void {
$types = postTypes($this->type);
$this->view->type = $types;
diff --git a/admin/controller/settings/sites.php b/admin/controller/settings/sites.php
index ec8a64f..f547795 100644
--- a/admin/controller/settings/sites.php
+++ b/admin/controller/settings/sites.php
@@ -30,16 +30,36 @@ use Vvveb\System\Sites as SitesList;
use Vvveb\System\User\Admin;
class Sites extends Base {
- //check for other modules permission like post and editor to enable links like save/delete etc
- protected $additionalPermissionCheck = ['settings/site/add'];
+ /** @var array<int, string> Additional permission URLs required for access */
+ protected ?array $additionalPermissionCheck = ['settings/site/add'];
+
+ /**
+ * Add a new site (empty action, redirects to site form).
+ *
+ * @return void
+ */
+ public function add(): void {}
+
+ /**
+ * Delete one or more sites.
+ *
+ * @return void
+ */
+ public function delete(): void {
+ $site_id = $this->request->post['site_id'] ?? false;
- function add() {
- }
+ if ($site_id) {
+ $edit_other_sites = Admin::hasCapability('edit_other_sites');
- function delete() {
- $site_id = $this->request->post['site_id'] ?? $this->request->get['site_id'] ?? false;
+ if (!$edit_other_sites) {
+ $access = Admin::siteAccess();
+ if (!in_array($site['site_id'], $access)) {
+ $this->view->errors[] = sprintf(__('Error deleting %s!'), __(' site'));
+
+ return;
+ }
+ }
- if ($site_id) {
$active_deleted = false;
$active_site_id = $this->session->get('site_id');
@@ -73,14 +93,19 @@ class Sites extends Base {
$this->setSite();
}
} else {
- $this->view->errors[] = sprintf(__('Error deleting %s!'), __(' site'));
+ $this->view->errors[] = sprintf(__('Error deleting %s!'), __(' site'));
}
}
- return $this->index();
+ $this->index();
}
- function index() {
+ /**
+ * Display the list of all sites with pagination.
+ *
+ * @return void
+ */
+ public function index(): void {
$view = $this->view;
$sites = new SiteSQL();
@@ -97,8 +122,8 @@ class Sites extends Base {
$results = $sites->getAll(
$options + [
- 'start' => ($page - 1) * $limit,
- 'limit' => $limit,
+ 'start' => ($page - 1) * $limit,
+ 'limit' => $limit,
]
);
diff --git a/admin/controller/tools/media-backup.php b/admin/controller/tools/media-backup.php
new file mode 100644
index 0000000..5929d03
--- /dev/null
+++ b/admin/controller/tools/media-backup.php
@@ -0,0 +1,804 @@
+<?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 Vvveb\Controller\Base;
+use function Vvveb\formatBytes;
+use function Vvveb\sanitizeFileName;
+use function Vvveb\url;
+
+class MediaBackup extends Base {
+ /**
+ * Base directory for media backups.
+ *
+ * @var string
+ */
+ private string $backupDir;
+
+ /**
+ * Initialize backup directory.
+ */
+ public function __construct() {
+ $this->backupDir = DIR_BACKUP . 'media' . DS;
+
+ if (!is_dir($this->backupDir)) {
+ @mkdir($this->backupDir, 0755, true);
+ }
+ }
+
+ /**
+ * Generate unique folder name for backup run (Y-m-d-H-i).
+ *
+ * @return string Folder name
+ */
+ private function generateFolderName(): string {
+ $folder = date('Y-m-d-H-i');
+ $folder = sanitizeFileName($folder);
+ $base = $this->backupDir . $folder;
+
+ if (!is_dir($base)) {
+ return $folder;
+ }
+
+ $folderWithSeconds = date('Y-m-d-H-i-s');
+ $folderWithSeconds = sanitizeFileName($folderWithSeconds);
+
+ if (!is_dir($this->backupDir . $folderWithSeconds)) {
+ return $folderWithSeconds;
+ }
+
+ $i = 1;
+ while (is_dir($this->backupDir . $folder . '-' . $i)) {
+ $i++;
+ }
+
+ return $folder . '-' . $i;
+ }
+
+ /**
+ * Get list of all media files relative to DIR_MEDIA.
+ *
+ * @return list<string>
+ */
+ private function getMediaFiles(): array {
+ $files = [];
+ $mediaDir = rtrim(DIR_MEDIA, DS);
+
+ if (!is_dir($mediaDir)) {
+ return $files;
+ }
+
+ $iterator = new \RecursiveIteratorIterator(
+ new \RecursiveDirectoryIterator($mediaDir, \RecursiveDirectoryIterator::SKIP_DOTS),
+ \RecursiveIteratorIterator::SELF_FIRST
+ );
+
+ foreach ($iterator as $file) {
+ $fullPath = $file->getPathname();
+ $relative = substr($fullPath, strlen($mediaDir) + 1);
+ // store relative path, include directories as well to preserve empty dirs
+ $files[] = $relative;
+ }
+
+ sort($files);
+
+ return $files;
+ }
+
+ /**
+ * Process next chunk for media backup with time-limited execution.
+ *
+ * @return void
+ */
+ public function nextBackup(): void {
+ $folder = sanitizeFileName($this->request->get['folder'] ?? '');
+ $position = (int)($this->request->get['position'] ?? 0);
+
+ if (!$folder) {
+ $error = __('Invalid backup folder!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ $folderPath = $this->backupDir . $folder;
+
+ if (!is_dir($folderPath)) {
+ $error = __('Backup folder does not exist!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ if (!class_exists('\ZipArchive')) {
+ $error = __('ZipArchive extension is not available!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ $mediaDir = rtrim(DIR_MEDIA, DS);
+
+ if (!is_dir($mediaDir)) {
+ $error = __('Media folder does not exist!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ $files = $this->getMediaFiles();
+ $count = count($files);
+ $zipPath = $folderPath . DS . 'media.zip';
+
+ // handle empty media folder
+ if ($count === 0) {
+ // create empty zip with just folder
+ $zip = new \ZipArchive();
+ if ($zip->open($zipPath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) === true) {
+ $zip->addEmptyDir('media');
+ $zip->close();
+ }
+ $message = __('Backup finished!');
+ $url = ['module' => 'tools/media-backup', 'success' => $message];
+ if ($this->request->isAjax()) {
+ exit(json_encode($url + ['url' => url($url), 'file' => $folder, 'position' => $count, 'count' => $count, 'success' => $message]));
+ } else {
+ $this->redirect($url);
+ $this->index();
+ }
+
+ return;
+ }
+
+ $start = microtime(true);
+ $elapsed = 0;
+ $current = '';
+
+ $zip = new \ZipArchive();
+ $flags = \ZipArchive::CREATE;
+ if ($position === 0) {
+ $flags |= \ZipArchive::OVERWRITE;
+ }
+ if ($zip->open($zipPath, $flags) !== true) {
+ $error = __('Error creating backup archive!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error, 'file' => $folder, 'position' => $position, 'count' => $count]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ while ($elapsed < 8 && ($position < $count)) {
+ $relative = $files[$position];
+ $current = $relative;
+ $fullPath = $mediaDir . DS . $relative;
+
+ if (is_dir($fullPath)) {
+ $zip->addEmptyDir($relative);
+ } elseif (is_file($fullPath)) {
+ $zip->addFile($fullPath, $relative);
+ }
+
+ $position++;
+ $elapsed = microtime(true) - $start;
+ }
+
+ $zip->close();
+
+ if ($position >= $count) {
+ $message = __('Backup finished!');
+ $url = ['module' => 'tools/media-backup', 'success' => $message];
+
+ if ($this->request->isAjax()) {
+ exit(json_encode($url + ['url' => url($url), 'file' => $folder, 'position' => $position, 'count' => $count, 'success' => $message]));
+ } else {
+ $this->redirect($url);
+ $this->index();
+ }
+ } else {
+ $url = ['module' => 'tools/media-backup', 'action' => 'nextBackup', 'folder' => $folder, 'position' => $position, 'count' => $count];
+
+ if ($this->request->isAjax()) {
+ exit(json_encode($url + ['url' => url($url), 'file' => $folder, 'position' => $position, 'count' => $count]));
+ } else {
+ $this->redirect($url);
+ $this->index();
+ }
+ }
+ }
+
+ /**
+ * Process next chunk for media restore with time-limited execution.
+ *
+ * @return void
+ */
+ public function nextRestore(): void {
+ if ($this->request->getMethod() !== 'post') {
+ $this->notFound(__('Invalid request method!'), 405);
+ }
+
+ $folder = sanitizeFileName($this->request->get['folder'] ?? $this->request->post['folder'] ?? '');
+ $fileParam = sanitizeFileName($this->request->get['file'] ?? $this->request->post['file'] ?? '');
+ $position = (int)($this->request->get['position'] ?? 0);
+
+ if ($fileParam && str_contains($fileParam, DS)) {
+ $parts = explode(DS, $fileParam);
+ if (count($parts) === 2) {
+ $folder = $parts[0] ?: $folder;
+ $fileParam = $parts[1];
+ } else {
+ $folder = $parts[0] ?: $folder;
+ $fileParam = end($parts);
+ }
+ }
+
+ if ($fileParam) {
+ $fileParam = basename($fileParam);
+ }
+
+ if (!$folder) {
+ $error = __('Invalid backup folder!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ $folderPath = $this->backupDir . $folder;
+
+ if (!is_dir($folderPath)) {
+ $error = __('Backup folder does not exist!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ // determine zip to restore: if file param set use it, else media.zip
+ $zipFile = $folderPath . DS . ($fileParam ?: 'media.zip');
+
+ if (!file_exists($zipFile) || !is_file($zipFile)) {
+ // fallback to any zip in folder
+ $zips = glob($folderPath . DS . '*.zip') ?: [];
+ if (!empty($zips)) {
+ $zipFile = $zips[0];
+ $fileParam = basename($zipFile);
+ } else {
+ $error = __('Backup does not exist!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error, 'file' => $folder, 'position' => $position, 'count' => 1]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+ }
+
+ if (!class_exists('\ZipArchive')) {
+ $error = __('ZipArchive extension is not available!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ $zip = new \ZipArchive();
+ if ($zip->open($zipFile) !== true) {
+ $error = __('Error opening backup archive!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ $count = $zip->numFiles;
+ $start = microtime(true);
+ $elapsed = 0;
+ $current = '';
+
+ if ($count === 0) {
+ $zip->close();
+ $message = __('Restore finished!');
+ $url = ['module' => 'tools/media-backup', 'success' => $message];
+ if ($this->request->isAjax()) {
+ exit(json_encode($url + ['url' => url($url), 'file' => $folder, 'position' => $count, 'count' => $count, 'success' => $message]));
+ } else {
+ $this->redirect($url);
+ $this->view->success[] = $message;
+ $this->index();
+ }
+
+ return;
+ }
+
+ // Ensure media dir exists
+ if (!is_dir(DIR_MEDIA)) {
+ @mkdir(DIR_MEDIA, 0755, true);
+ }
+
+ while ($elapsed < 8 && ($position < $count)) {
+ $stat = $zip->statIndex($position);
+ $current = $stat['name'] ?? (string)$position;
+ // extract single file
+ $zip->extractTo(DIR_MEDIA, [$stat['name']]);
+ $position++;
+ $elapsed = microtime(true) - $start;
+ }
+
+ $zip->close();
+
+ if ($position >= $count) {
+ $message = __('Restore finished!');
+ $url = ['module' => 'tools/media-backup', 'success' => $message];
+
+ if ($this->request->isAjax()) {
+ exit(json_encode($url + ['url' => url($url), 'file' => $folder, 'position' => $position, 'count' => $count, 'success' => $message]));
+ } else {
+ $this->redirect($url);
+ $this->view->success[] = $message;
+ $this->index();
+ }
+ } else {
+ $url = ['module' => 'tools/media-backup', 'action' => 'nextRestore', 'folder' => $folder, 'position' => $position, 'count' => $count];
+ if ($fileParam && $fileParam !== 'media.zip') {
+ $url['file'] = $fileParam;
+ }
+
+ if ($this->request->isAjax()) {
+ $jsonExtra = ['url' => url($url), 'file' => $folder, 'position' => $position, 'count' => $count];
+ exit(json_encode($url + $jsonExtra));
+ } else {
+ $this->redirect($url);
+ exit('Processing');
+ }
+ }
+ }
+
+ /**
+ * Delete a media backup folder or single file.
+ *
+ * @return void
+ */
+ public function delete(): void {
+ if ($this->request->getMethod() !== 'post') {
+ $this->notFound(__('Invalid request method!'), 405);
+ }
+
+ $folder = sanitizeFileName($this->request->post['folder'] ?? $this->request->post['file'] ?? '');
+ $file = sanitizeFileName($this->request->post['file'] ?? '');
+
+ if ($file && str_contains($file, DS)) {
+ $parts = explode(DS, $file);
+ $folder = $parts[0];
+ $file = $parts[1] ?? '';
+ if (count($parts) > 2) {
+ $folder = $parts[0];
+ $file = end($parts);
+ }
+ } elseif ($file && !$folder) {
+ if (is_dir($this->backupDir . $file) && !str_contains($file, '.')) {
+ $folder = $file;
+ $file = '';
+ }
+ }
+
+ if ($folder && str_contains($folder, DS)) {
+ $folder = basename($folder);
+ }
+
+ if ($folder && $file) {
+ $path = $this->backupDir . $folder . DS . $file;
+
+ if (file_exists($path) && is_file($path)) {
+ if (unlink($path)) {
+ $remaining = glob($this->backupDir . $folder . DS . '*.zip');
+ if (empty($remaining)) {
+ @rmdir($this->backupDir . $folder);
+ }
+ $this->view->success[] = __('Backup deleted!');
+ } else {
+ $this->view->errors[] = __('Error deleting backup!');
+ }
+ } else {
+ $this->view->errors[] = __('Backup does not exist!');
+ }
+ } elseif ($folder) {
+ $path = $this->backupDir . $folder;
+
+ if (is_dir($path)) {
+ $result = \Vvveb\rrmdir($path);
+ @rmdir($path);
+ if ($result) {
+ $this->view->success[] = __('Backup deleted!');
+ } else {
+ $this->view->errors[] = __('Error deleting backup!');
+ }
+ } elseif (file_exists($path) && is_file($path)) {
+ if (unlink($path)) {
+ $this->view->success[] = __('Backup deleted!');
+ } else {
+ $this->view->errors[] = __('Error deleting backup!');
+ }
+ } else {
+ $this->view->errors[] = __('Backup does not exist!');
+ }
+ } else {
+ $this->view->errors[] = __('Invalid backup!');
+ }
+
+ $this->index();
+ }
+
+ /**
+ * Initiate a media restore from a backup folder or single file.
+ *
+ * @return void
+ */
+ public function restore(): void {
+ if ($this->request->getMethod() !== 'post') {
+ $this->notFound(__('Invalid request method!'), 405);
+ }
+
+ $folder = sanitizeFileName($this->request->post['folder'] ?? $this->request->get['folder'] ?? '');
+ $file = sanitizeFileName($this->request->post['file'] ?? $this->request->get['file'] ?? '');
+
+ if ($file && str_contains($file, DS)) {
+ $parts = explode(DS, $file);
+ if (count($parts) === 2) {
+ $folder = $parts[0] ?: $folder;
+ $file = $parts[1];
+ } else {
+ $folder = $parts[0] ?: $folder;
+ $file = end($parts);
+ }
+ } elseif ($file && !$folder && str_contains($file, '.zip')) {
+ $folder = '';
+ }
+
+ if ($folder && str_contains($folder, DS)) {
+ $folder = basename($folder);
+ }
+ if ($file) {
+ $file = basename($file);
+ }
+
+ if (!$folder && $file && str_contains($this->request->post['file'] ?? '', '/')) {
+ $raw = sanitizeFileName($this->request->post['file'] ?? '', false);
+ $parts = explode('/', $raw);
+ if (count($parts) === 2) {
+ $folder = sanitizeFileName($parts[0]);
+ $file = sanitizeFileName($parts[1]);
+ }
+ }
+
+ if ($folder && str_contains($folder, '.zip') && !$file) {
+ $file = basename($folder);
+ $folder = basename(dirname($this->request->post['file'] ?? $this->request->post['folder'] ?? ''));
+ $folder = sanitizeFileName($folder);
+ }
+
+ if (!$file && $folder && str_contains($this->request->post['file'] ?? '', '.zip')) {
+ $fileCandidate = sanitizeFileName($this->request->post['file'] ?? '');
+ if (str_contains($fileCandidate, '.zip')) {
+ $file = basename($fileCandidate);
+ }
+ }
+
+ if ($file) {
+ $url = ['module' => 'tools/media-backup', 'action' => 'nextRestore', 'folder' => $folder, 'file' => $file];
+ $path = $this->backupDir . $folder . DS . $file;
+ if ($folder && is_dir($this->backupDir . $folder) && file_exists($path)) {
+ if ($this->request->isAjax()) {
+ exit(json_encode($url + ['url' => url($url)]));
+ } else {
+ $this->redirect($url);
+ $this->index();
+ }
+ } else {
+ $error = __('Backup does not exist!');
+ if ($this->request->isAjax()) {
+ exit(json_encode($url + ['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+ }
+ }
+
+ return;
+ }
+
+ $url = ['module' => 'tools/media-backup', 'action' => 'nextRestore', 'folder' => $folder];
+
+ if ($folder && is_dir($this->backupDir . $folder)) {
+ if ($this->request->isAjax()) {
+ exit(json_encode($url + ['url' => url($url)]));
+ } else {
+ $this->redirect($url);
+ $this->index();
+ }
+ } else {
+ $error = __('Backup does not exist!');
+
+ if ($this->request->isAjax()) {
+ exit(json_encode($url + ['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+ }
+ }
+ }
+
+ /**
+ * Download a media backup file or entire backup folder.
+ *
+ * @return void
+ */
+ public function download(): void {
+ $folder = sanitizeFileName($this->request->post['folder'] ?? $this->request->get['folder'] ?? '');
+ $file = sanitizeFileName($this->request->post['file'] ?? $this->request->get['file'] ?? '');
+
+ if ($file && str_contains($file, DS)) {
+ $parts = explode(DS, $file);
+ if (count($parts) === 2) {
+ $folder = $parts[0];
+ $file = $parts[1];
+ } else {
+ $folder = $parts[0];
+ $file = end($parts);
+ }
+ }
+
+ if ($folder && $file) {
+ $path = $this->backupDir . $folder . DS . $file;
+
+ if (file_exists($path) && is_file($path)) {
+ $fp = fopen($path, 'r');
+ header('Content-Type: application/zip');
+ header('Content-Length: ' . filesize($path));
+ header('Content-Disposition: attachment; filename="' . $file . '"');
+ fpassthru($fp);
+ exit();
+ } else {
+ $this->view->errors[] = __('Backup does not exist!');
+ }
+ } elseif ($folder) {
+ $folderPath = $this->backupDir . $folder;
+
+ if (is_dir($folderPath)) {
+ $files = glob($folderPath . DS . '*.zip') ?: [];
+ if (count($files) === 1) {
+ // single media.zip, send directly
+ $path = $files[0];
+ $fp = fopen($path, 'r');
+ header('Content-Type: application/zip');
+ header('Content-Length: ' . filesize($path));
+ header('Content-Disposition: attachment; filename="' . basename($path) . '"');
+ fpassthru($fp);
+ exit();
+ }
+ // fallback: create temp zip of folder
+ $tmpFile = tempnam(sys_get_temp_dir(), 'media_backup_') . '.zip';
+ $zip = new \ZipArchive();
+
+ if ($zip->open($tmpFile, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) === true) {
+ $iterator = new \RecursiveIteratorIterator(
+ new \RecursiveDirectoryIterator($folderPath, \RecursiveDirectoryIterator::SKIP_DOTS),
+ \RecursiveIteratorIterator::LEAVES_ONLY
+ );
+ foreach ($iterator as $f) {
+ $real = $f->getRealPath();
+ $relative = substr($real, strlen($folderPath) + 1);
+ $zip->addFile($real, $relative);
+ }
+ $zip->close();
+ header('Content-Type: application/zip');
+ header('Content-Length: ' . filesize($tmpFile));
+ header('Content-Disposition: attachment; filename="' . $folder . '.zip"');
+ readfile($tmpFile);
+ @unlink($tmpFile);
+ exit();
+ } else {
+ $this->view->errors[] = __('Error creating archive!');
+ }
+ } else {
+ $this->view->errors[] = __('Backup does not exist!');
+ }
+ } else {
+ $this->view->errors[] = __('Invalid backup!');
+ }
+
+ $this->index();
+ }
+
+ /**
+ * Initiate the media backup process.
+ *
+ * @return void
+ */
+ public function save(): void {
+ if (!class_exists('\ZipArchive')) {
+ $error = __('ZipArchive extension is not available!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ if (!is_dir(DIR_MEDIA)) {
+ $error = __('Media folder does not exist!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ $folder = $this->generateFolderName();
+ $folderPath = $this->backupDir . $folder;
+
+ if (!@mkdir($folderPath, 0755, true) && !is_dir($folderPath)) {
+ $error = __('Error creating backup folder!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ $url = ['module' => 'tools/media-backup', 'action' => 'nextBackup', 'folder' => $folder, 'position' => 0, 'count' => 0];
+
+ if ($this->request->isAjax()) {
+ exit(json_encode($url + ['url' => url($url), 'position' => 0, 'count' => 0, 'file' => $folder]));
+ } else {
+ $this->redirect($url);
+ $this->index();
+ }
+ }
+
+ /**
+ * Display the media backup management page.
+ *
+ * @return void
+ */
+ public function index(): void {
+ $view = $this->view;
+
+ // media stats
+ $mediaFiles = $this->getMediaFiles();
+ $view->mediaCount = count($mediaFiles);
+ $mediaSize = 0;
+ foreach ($mediaFiles as $rel) {
+ $full = DIR_MEDIA . $rel;
+ if (is_file($full)) {
+ $mediaSize += filesize($full);
+ }
+ }
+ $view->mediaSize = formatBytes($mediaSize);
+ $view->mediaSizeBytes = $mediaSize;
+
+ // existing backups
+ $backupFolders = glob($this->backupDir . '*', GLOB_ONLYDIR) ?: [];
+ $backups = [];
+
+ foreach ($backupFolders as $index => $folderPath) {
+ $folder = basename($folderPath);
+ $files = glob($folderPath . DS . '*.zip') ?: [];
+ $size = 0;
+
+ foreach ($files as $f) {
+ $size += filesize($f);
+ }
+
+ $backupFiles = [];
+
+ foreach ($files as $f) {
+ $name = basename($f);
+ $backupFiles[] = [
+ 'name' => $name,
+ 'file' => $name,
+ 'slug' => pathinfo($name, PATHINFO_FILENAME),
+ 'folder' => $folder,
+ 'file_path' => $folder . '/' . $name,
+ 'size' => formatBytes(filesize($f)),
+ 'size_bytes' => filesize($f),
+ 'download-url' => url(['module' => 'tools/media-backup', 'action' => 'download']),
+ 'delete-url' => url(['module' => 'tools/media-backup', 'action' => 'delete']),
+ 'restore-url' => url(['module' => 'tools/media-backup', 'action' => 'restore']),
+ ];
+ }
+
+ $backups[] = [
+ 'name' => $folder,
+ 'folder' => $folder,
+ 'file' => $folder,
+ 'key' => $index,
+ 'size_bytes' => $size,
+ 'size' => formatBytes($size),
+ 'created_at' => date('Y/m/d H:i', filemtime($folderPath)),
+ 'count' => count($files),
+ 'files' => $backupFiles,
+ 'restore-url' => url(['module' => 'tools/media-backup', 'action' => 'restore']),
+ 'download-url' => url(['module' => 'tools/media-backup', 'action' => 'download']),
+ 'delete-url' => url(['module' => 'tools/media-backup', 'action' => 'delete']),
+ ];
+ }
+
+ usort($backups, fn ($a, $b) => strcmp($b['name'], $a['name']));
+
+ $view->backups = $backups;
+ $view->backupUrl = url(['module' => 'tools/media-backup', 'action' => 'save']);
+ $view->hasZip = class_exists('\ZipArchive');
+ }
+}
diff --git a/admin/controller/tools/plugins-backup.php b/admin/controller/tools/plugins-backup.php
new file mode 100755
index 0000000..e062a84
--- /dev/null
+++ b/admin/controller/tools/plugins-backup.php
@@ -0,0 +1,907 @@
+<?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 Vvveb\Controller\Base;
+use function Vvveb\formatBytes;
+use function Vvveb\sanitizeFileName;
+use Vvveb\System\Extensions\Plugins;
+use function Vvveb\url;
+
+class PluginsBackup extends Base {
+ /**
+ * Base directory for plugins backups.
+ *
+ * @var string
+ */
+ private string $backupDir;
+
+ /**
+ * Initialize backup directory.
+ */
+ public function __construct() {
+ $this->backupDir = DIR_BACKUP . 'plugins' . DS;
+
+ if (!is_dir($this->backupDir)) {
+ @mkdir($this->backupDir, 0755, true);
+ }
+ }
+
+ /**
+ * Get list of available plugins (slug => info).
+ *
+ * @return array<string, array<string, mixed>>
+ */
+ private function getPluginsList(): array {
+ return Plugins::getList(SITE_ID, false, false);
+ }
+
+ /**
+ * Sanitize plugin name (slug) - allow only alphanum, dash, underscore.
+ *
+ * @param string $name Plugin slug
+ *
+ * @return string Sanitized slug
+ */
+ private function sanitizePluginName(string $name): string {
+ $name = basename(trim($name));
+
+ return preg_replace('/[^a-zA-Z0-9_\-]/', '', $name);
+ }
+
+ /**
+ * Create zip archive for a single plugin.
+ *
+ * @param string $plugin Plugin slug
+ * @param string $destination Full path to zip file
+ *
+ * @return bool True on success
+ */
+ private function zipPlugin(string $plugin, string $destination): bool {
+ $plugin = $this->sanitizePluginName($plugin);
+ $source = DIR_PLUGINS . $plugin;
+
+ if (!$plugin || !is_dir($source)) {
+ return false;
+ }
+
+ if (!class_exists('\ZipArchive')) {
+ return false;
+ }
+
+ $zip = new \ZipArchive();
+
+ if ($zip->open($destination, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) !== true) {
+ return false;
+ }
+
+ $sourceReal = realpath($source);
+
+ if ($sourceReal === false) {
+ $zip->close();
+
+ return false;
+ }
+
+ $iterator = new \RecursiveIteratorIterator(
+ new \RecursiveDirectoryIterator($sourceReal, \RecursiveDirectoryIterator::SKIP_DOTS),
+ \RecursiveIteratorIterator::LEAVES_ONLY
+ );
+
+ foreach ($iterator as $file) {
+ /** @var \SplFileInfo $file */
+ if (!$file->isDir()) {
+ $filePath = $file->getRealPath();
+ $relativePath = $plugin . '/' . substr($filePath, strlen($sourceReal) + 1);
+ $zip->addFile($filePath, $relativePath);
+ }
+ }
+
+ $zip->close();
+
+ return file_exists($destination) && filesize($destination) > 0;
+ }
+
+ /**
+ * Extract a plugin zip archive.
+ *
+ * @param string $zipFile Full path to zip file
+ *
+ * @return bool True on success
+ */
+ private function unzipPlugin(string $zipFile): bool {
+ if (!file_exists($zipFile) || !class_exists('\ZipArchive')) {
+ return false;
+ }
+
+ $zip = new \ZipArchive();
+
+ if ($zip->open($zipFile) !== true) {
+ return false;
+ }
+
+ $result = $zip->extractTo(DIR_PLUGINS);
+ $zip->close();
+
+ return $result;
+ }
+
+ /**
+ * Generate unique folder name for backup run (Y-m-d-H-i).
+ *
+ * @return string Folder name
+ */
+ private function generateFolderName(): string {
+ $folder = date('Y-m-d-H-i');
+ $folder = sanitizeFileName($folder);
+ $base = $this->backupDir . $folder;
+
+ if (!is_dir($base)) {
+ return $folder;
+ }
+
+ //if folder already exists within same minute, add seconds or increment
+ $folderWithSeconds = date('Y-m-d-H-i-s');
+ $folderWithSeconds = sanitizeFileName($folderWithSeconds);
+
+ if (!is_dir($this->backupDir . $folderWithSeconds)) {
+ return $folderWithSeconds;
+ }
+
+ $i = 1;
+ while (is_dir($this->backupDir . $folder . '-' . $i)) {
+ $i++;
+ }
+
+ return $folder . '-' . $i;
+ }
+
+ /**
+ * Process next plugin(s) for backup with time-limited execution.
+ *
+ * @return void
+ */
+ public function nextBackup(): void {
+ $folder = sanitizeFileName($this->request->get['folder'] ?? '');
+ $position = (int)($this->request->get['position'] ?? 0);
+ $pluginsParam = $this->request->get['plugins'] ?? '';
+
+ //plugins can be passed as comma separated string or array
+ if (is_array($pluginsParam)) {
+ $plugins = $pluginsParam;
+ } else {
+ $plugins = $pluginsParam !== '' ? explode(',', (string)$pluginsParam) : [];
+ }
+
+ //also check POST for plugins on first step fallback
+ if (empty($plugins) && isset($this->request->post['plugins'])) {
+ $plugins = (array)$this->request->post['plugins'];
+ }
+
+ // sanitize plugins
+ $plugins = array_values(array_filter(array_map(fn ($p) => $this->sanitizePluginName((string)$p), $plugins)));
+
+ //if no plugins passed, try to read from folder metadata (plugins.json) if exists
+ if (empty($plugins) && $folder && file_exists($this->backupDir . $folder . DS . 'plugins.json')) {
+ $json = file_get_contents($this->backupDir . $folder . DS . 'plugins.json');
+ $plugins = json_decode($json, true) ?? [];
+ $plugins = array_values(array_filter(array_map(fn ($p) => $this->sanitizePluginName((string)$p), (array)$plugins)));
+ }
+
+ if (!$folder) {
+ $error = __('Invalid backup folder!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ $folderPath = $this->backupDir . $folder;
+
+ if (!is_dir($folderPath)) {
+ $error = __('Backup folder does not exist!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ if (empty($plugins)) {
+ $error = __('No plugins selected!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ // validate plugins exist
+ $available = $this->getPluginsList();
+ $availableSlugs = array_keys($available);
+ //also allow plugins that may not be in getList but folder exists (maybe broken)
+ foreach ($plugins as $slug) {
+ if (!in_array($slug, $availableSlugs, true) && !is_dir(DIR_PLUGINS . $slug)) {
+ $error = sprintf(__('Plugin "%s" not found!'), $slug);
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+ }
+
+ $count = count($plugins);
+ $start = microtime(true);
+ $elapsed = 0;
+ $current = '';
+
+ //if takes longer than 8 seconds start a new process to avoid php timeout
+ while ($elapsed < 8 && ($position < $count)) {
+ $plugin = $plugins[$position];
+ $current = $plugin;
+ $destination = $folderPath . DS . $plugin . '.zip';
+
+ $success = $this->zipPlugin($plugin, $destination);
+
+ if (!$success) {
+ $error = sprintf(__('Error backing up plugin "%s"!'), $plugin);
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error, 'file' => $folder, 'position' => $position, 'count' => $count]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ $position++;
+
+ $end = microtime(true);
+ $elapsed = $end - $start;
+ }
+
+ //if all done, remove metadata file if exists
+ if ($position >= $count) {
+ $metaFile = $folderPath . DS . 'plugins.json';
+ if (file_exists($metaFile)) {
+ @unlink($metaFile);
+ }
+
+ $message = __('Backup finished!');
+ $url = ['module' => 'tools/plugins-backup', 'success' => $message];
+
+ if ($this->request->isAjax()) {
+ exit(json_encode($url + ['url' => url($url), 'file' => $folder, 'plugin' => $current, 'position' => $position, 'count' => $count, 'success' => $message]));
+ } else {
+ $this->redirect($url);
+ $this->index();
+ }
+ } else {
+ $pluginName = $plugins[$position] ?? $current;
+ $pluginsEncoded = implode(',', $plugins);
+ $url = ['module' => 'tools/plugins-backup', 'action' => 'nextBackup', 'folder' => $folder, 'plugins' => $pluginsEncoded, 'plugin' => $pluginName, 'position' => $position, 'count' => $count];
+
+ if ($this->request->isAjax()) {
+ exit(json_encode($url + ['url' => url($url), 'file' => $folder, 'plugin' => $pluginName, 'position' => $position, 'count' => $count]));
+ } else {
+ $this->redirect($url);
+ $this->index();
+ }
+ }
+ }
+
+ /**
+ * Process next plugin(s) for restore with time-limited execution.
+ *
+ * @return void
+ */
+ public function nextRestore(): void {
+ if ($this->request->getMethod() !== 'post') {
+ $this->notFound(__('Invalid request method!'), 405);
+ }
+
+ $folder = sanitizeFileName($this->request->get['folder'] ?? $this->request->post['folder'] ?? '');
+ $fileParam = sanitizeFileName($this->request->get['file'] ?? $this->request->post['file'] ?? '');
+ $position = (int)($this->request->get['position'] ?? 0);
+
+ //if file contains path, split
+ if ($fileParam && str_contains($fileParam, DS)) {
+ $parts = explode(DS, $fileParam);
+ if (count($parts) === 2) {
+ $folder = $parts[0] ?: $folder;
+ $fileParam = $parts[1];
+ } else {
+ $folder = $parts[0] ?: $folder;
+ $fileParam = end($parts);
+ }
+ }
+
+ if ($fileParam) {
+ $fileParam = basename($fileParam);
+ }
+
+ if (!$folder) {
+ $error = __('Invalid backup folder!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ $folderPath = $this->backupDir . $folder;
+
+ if (!is_dir($folderPath)) {
+ $error = __('Backup folder does not exist!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ if ($fileParam) {
+ $singlePath = $folderPath . DS . $fileParam;
+ if (!file_exists($singlePath) || !is_file($singlePath)) {
+ $error = __('Backup does not exist!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error, 'file' => $folder, 'position' => $position, 'count' => 1]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+ $files = [$singlePath];
+ } else {
+ $files = glob($folderPath . DS . '*.zip') ?: [];
+ }
+ $count = count($files);
+ $start = microtime(true);
+
+ if ($count === 0) {
+ $error = __('No plugin backups found in folder!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ sort($files);
+ $elapsed = 0;
+ $current = '';
+
+ while ($elapsed < 8 && ($position < $count)) {
+ $file = $files[$position];
+ $current = basename($file);
+
+ $success = $this->unzipPlugin($file);
+
+ if (!$success) {
+ $error = sprintf(__('Error restoring plugin "%s"!'), $current);
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error, 'file' => $folder, 'position' => $position, 'count' => $count]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ $position++;
+ $elapsed = microtime(true) - $start;
+ }
+
+ if ($position >= $count) {
+ $message = __('Restore finished!');
+ $url = ['module' => 'tools/plugins-backup', 'success' => $message];
+
+ if ($this->request->isAjax()) {
+ exit(json_encode($url + ['url' => url($url), 'file' => $folder, 'plugin' => $current, 'position' => $position, 'count' => $count, 'success' => $message]));
+ } else {
+ $this->redirect($url);
+ $this->view->success[] = $message;
+ $this->index();
+ }
+ } else {
+ $nextPlugin = basename($files[$position] ?? $current);
+ $url = ['module' => 'tools/plugins-backup', 'action' => 'nextRestore', 'folder' => $folder, 'plugin' => $nextPlugin, 'position' => $position, 'count' => $count];
+ if ($fileParam) {
+ $url['file'] = $fileParam;
+ }
+
+ if ($this->request->isAjax()) {
+ $jsonExtra = ['url' => url($url), 'file' => $folder, 'plugin' => $nextPlugin, 'position' => $position, 'count' => $count];
+ if ($fileParam) {
+ $jsonExtra['file'] = $folder . '/' . $fileParam;
+ }
+ exit(json_encode($url + $jsonExtra));
+ } else {
+ $this->redirect($url);
+ exit('Processing');
+ }
+ }
+ }
+
+ /**
+ * Delete a plugins backup folder or single plugin zip.
+ *
+ * @return void
+ */
+ public function delete(): void {
+ if ($this->request->getMethod() !== 'post') {
+ $this->notFound(__('Invalid request method!'), 405);
+ }
+
+ $folder = sanitizeFileName($this->request->post['folder'] ?? $this->request->post['file'] ?? '');
+ $file = sanitizeFileName($this->request->post['file'] ?? '');
+
+ //if file contains path separator, split folder and file
+ if ($file && str_contains($file, DS)) {
+ $parts = explode(DS, $file);
+ $folder = $parts[0];
+ $file = $parts[1] ?? '';
+ //if more parts (should not), use last as file and first as folder
+ if (count($parts) > 2) {
+ $folder = $parts[0];
+ $file = end($parts);
+ }
+ } elseif ($file && !$folder) {
+ //if file is actually folder name (legacy), treat as folder
+ if (is_dir($this->backupDir . $file) && !str_contains($file, '.')) {
+ $folder = $file;
+ $file = '';
+ }
+ }
+
+ //also check for folder param with slash
+ if ($folder && str_contains($folder, DS)) {
+ //folder should not contain slash beyond base, sanitize to basename
+ $folder = basename($folder);
+ }
+
+ if ($folder && $file) {
+ //delete single plugin zip
+ $path = $this->backupDir . $folder . DS . $file;
+
+ if (file_exists($path) && is_file($path)) {
+ if (unlink($path)) {
+ //if folder empty after delete, remove folder
+ $remaining = glob($this->backupDir . $folder . DS . '*.zip');
+ if (empty($remaining)) {
+ @rmdir($this->backupDir . $folder);
+ }
+ $this->view->success[] = __('Backup deleted!');
+ } else {
+ $this->view->errors[] = __('Error deleting backup!');
+ }
+ } else {
+ $this->view->errors[] = __('Backup does not exist!');
+ }
+ } elseif ($folder) {
+ $path = $this->backupDir . $folder;
+
+ if (is_dir($path)) {
+ $result = \Vvveb\rrmdir($path);
+ @rmdir($path);
+ if ($result) {
+ $this->view->success[] = __('Backup deleted!');
+ } else {
+ $this->view->errors[] = __('Error deleting backup!');
+ }
+ } elseif (file_exists($path) && is_file($path)) {
+ if (unlink($path)) {
+ $this->view->success[] = __('Backup deleted!');
+ } else {
+ $this->view->errors[] = __('Error deleting backup!');
+ }
+ } else {
+ $this->view->errors[] = __('Backup does not exist!');
+ }
+ } else {
+ $this->view->errors[] = __('Invalid backup!');
+ }
+
+ $this->index();
+ }
+
+ /**
+ * Initiate a plugins restore from a backup folder or single plugin file.
+ *
+ * @return void
+ */
+ public function restore(): void {
+ if ($this->request->getMethod() !== 'post') {
+ $this->notFound(__('Invalid request method!'), 405);
+ }
+
+ $folder = sanitizeFileName($this->request->post['folder'] ?? $this->request->get['folder'] ?? '');
+ $file = sanitizeFileName($this->request->post['file'] ?? $this->request->get['file'] ?? '');
+
+ //if file contains path, split
+ if ($file && str_contains($file, DS)) {
+ $parts = explode(DS, $file);
+ if (count($parts) === 2) {
+ $folder = $parts[0] ?: $folder;
+ $file = $parts[1];
+ } else {
+ $folder = $parts[0] ?: $folder;
+ $file = end($parts);
+ }
+ } elseif ($file && !$folder && str_contains($file, '.zip')) {
+ //file param may be folder/file.zip without separate folder
+ $folder = '';
+ }
+
+ if ($folder && str_contains($folder, DS)) {
+ $folder = basename($folder);
+ }
+ if ($file) {
+ $file = basename($file);
+ }
+
+ //fallback: if folder empty but file contains folder path via post file
+ if (!$folder && $file && str_contains($this->request->post['file'] ?? '', '/')) {
+ $raw = sanitizeFileName($this->request->post['file'] ?? '', false);
+ //sanitize with normalized false to keep slash?
+ $parts = explode('/', $raw);
+ if (count($parts) === 2) {
+ $folder = sanitizeFileName($parts[0]);
+ $file = sanitizeFileName($parts[1]);
+ }
+ }
+
+ //legacy fallback: if folder contains .zip and no separate file
+ if ($folder && str_contains($folder, '.zip') && !$file) {
+ $file = basename($folder);
+ $folder = basename(dirname($this->request->post['file'] ?? $this->request->post['folder'] ?? ''));
+ $folder = sanitizeFileName($folder);
+ }
+
+ //also handle case where folder param actually contains file path (old backup.js pattern)
+ if (!$file && $folder && str_contains($this->request->post['file'] ?? '', '.zip')) {
+ $fileCandidate = sanitizeFileName($this->request->post['file'] ?? '');
+ if (str_contains($fileCandidate, '.zip')) {
+ $file = basename($fileCandidate);
+ }
+ }
+
+ if ($file) {
+ $url = ['module' => 'tools/plugins-backup', 'action' => 'nextRestore', 'folder' => $folder, 'file' => $file];
+ $path = $this->backupDir . $folder . DS . $file;
+ if ($folder && is_dir($this->backupDir . $folder) && file_exists($path)) {
+ if ($this->request->isAjax()) {
+ exit(json_encode($url + ['url' => url($url)]));
+ } else {
+ $this->redirect($url);
+ $this->index();
+ }
+ } else {
+ $error = __('Backup does not exist!');
+ if ($this->request->isAjax()) {
+ exit(json_encode($url + ['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+ }
+ }
+
+ return;
+ }
+
+ $url = ['module' => 'tools/plugins-backup', 'action' => 'nextRestore', 'folder' => $folder];
+
+ if ($folder && is_dir($this->backupDir . $folder)) {
+ if ($this->request->isAjax()) {
+ exit(json_encode($url + ['url' => url($url)]));
+ } else {
+ $this->redirect($url);
+ $this->index();
+ }
+ } else {
+ $error = __('Backup does not exist!');
+
+ if ($this->request->isAjax()) {
+ exit(json_encode($url + ['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+ }
+ }
+ }
+
+ /**
+ * Download a plugin backup file or entire backup folder.
+ *
+ * @return void
+ */
+ public function download(): void {
+ $folder = sanitizeFileName($this->request->post['folder'] ?? $this->request->get['folder'] ?? '');
+ $file = sanitizeFileName($this->request->post['file'] ?? $this->request->get['file'] ?? '');
+
+ //if file contains folder separator, split
+ if ($file && str_contains($file, DS)) {
+ $parts = explode(DS, $file);
+ if (count($parts) === 2) {
+ $folder = $parts[0];
+ $file = $parts[1];
+ } else {
+ $folder = $parts[0];
+ $file = end($parts);
+ }
+ }
+
+ if ($folder && $file) {
+ $path = $this->backupDir . $folder . DS . $file;
+
+ if (file_exists($path) && is_file($path)) {
+ $fp = fopen($path, 'r');
+ header('Content-Type: application/zip');
+ header('Content-Length: ' . filesize($path));
+ header('Content-Disposition: attachment; filename="' . $file . '"');
+ fpassthru($fp);
+ exit();
+ } else {
+ $this->view->errors[] = __('Backup does not exist!');
+ }
+ } elseif ($folder) {
+ $folderPath = $this->backupDir . $folder;
+
+ if (is_dir($folderPath)) {
+ //create temporary zip of folder for download
+ $tmpFile = tempnam(sys_get_temp_dir(), 'plugins_backup_') . '.zip';
+ $zip = new \ZipArchive();
+
+ if ($zip->open($tmpFile, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) === true) {
+ $files = new \RecursiveIteratorIterator(
+ new \RecursiveDirectoryIterator($folderPath, \RecursiveDirectoryIterator::SKIP_DOTS),
+ \RecursiveIteratorIterator::LEAVES_ONLY
+ );
+ foreach ($files as $f) {
+ $real = $f->getRealPath();
+ $relative = substr($real, strlen($folderPath) + 1);
+ $zip->addFile($real, $relative);
+ }
+ $zip->close();
+ header('Content-Type: application/zip');
+ header('Content-Length: ' . filesize($tmpFile));
+ header('Content-Disposition: attachment; filename="' . $folder . '.zip"');
+ readfile($tmpFile);
+ @unlink($tmpFile);
+ exit();
+ } else {
+ $this->view->errors[] = __('Error creating archive!');
+ }
+ } else {
+ $this->view->errors[] = __('Backup does not exist!');
+ }
+ } else {
+ $this->view->errors[] = __('Invalid backup!');
+ }
+
+ $this->index();
+ }
+
+ /**
+ * Initiate the plugins backup process.
+ *
+ * @return void
+ */
+ public function save(): void {
+ $plugins = $this->request->post['plugins'] ?? [];
+
+ if (is_string($plugins)) {
+ $plugins = $plugins !== '' ? explode(',', $plugins) : [];
+ }
+
+ if (!is_array($plugins)) {
+ $plugins = (array)$plugins;
+ }
+
+ $plugins = array_values(array_filter(array_map(fn ($p) => $this->sanitizePluginName((string)$p), $plugins)));
+
+ if (empty($plugins)) {
+ $error = __('No plugins selected!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ //validate plugins exist
+ $available = $this->getPluginsList();
+ $availableSlugs = array_keys($available);
+
+ foreach ($plugins as $slug) {
+ if (!in_array($slug, $availableSlugs, true) && !is_dir(DIR_PLUGINS . $slug)) {
+ $error = sprintf(__('Plugin "%s" not found!'), $slug);
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+ }
+
+ if (!class_exists('\ZipArchive')) {
+ $error = __('ZipArchive extension is not available!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ $folder = $this->generateFolderName();
+ $folderPath = $this->backupDir . $folder;
+
+ if (!@mkdir($folderPath, 0755, true) && !is_dir($folderPath)) {
+ $error = __('Error creating backup folder!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ //store plugins list for next steps (in case url truncated, allow resume)
+ @file_put_contents($folderPath . DS . 'plugins.json', json_encode($plugins));
+
+ $pluginsEncoded = implode(',', $plugins);
+ $url = ['module' => 'tools/plugins-backup', 'action' => 'nextBackup', 'folder' => $folder, 'plugins' => $pluginsEncoded, 'position' => 0, 'count' => count($plugins)];
+
+ if ($this->request->isAjax()) {
+ exit(json_encode($url + ['url' => url($url), 'position' => 0, 'count' => count($plugins), 'plugin' => $plugins[0], 'file' => $folder]));
+ } else {
+ $this->redirect($url);
+ $this->index();
+ }
+ }
+
+ /**
+ * Display the plugins backup management page.
+ *
+ * @return void
+ */
+ public function index(): void {
+ $view = $this->view;
+
+ //available plugins for selection
+ $pluginsList = $this->getPluginsList();
+ $plugins = [];
+
+ foreach ($pluginsList as $slug => $info) {
+ $plugins[] = [
+ 'slug' => $slug,
+ 'name' => $info['name'] ?? $slug,
+ 'description' => $info['description'] ?? '',
+ 'version' => $info['version'] ?? '',
+ 'thumb_url' => $info['thumb_url'] ?? '',
+ 'status' => $info['status'] ?? 'inactive',
+ ];
+ }
+
+ //sort plugins by name
+ usort($plugins, fn ($a, $b) => strcmp($a['name'], $b['name']));
+
+ $view->plugins = $plugins;
+ $view->pluginCount = count($plugins);
+
+ //existing backups
+ $backupFolders = glob($this->backupDir . '*', GLOB_ONLYDIR) ?: [];
+ $backups = [];
+
+ foreach ($backupFolders as $index => $folderPath) {
+ $folder = basename($folderPath);
+ $files = glob($folderPath . DS . '*.zip') ?: [];
+ $size = 0;
+
+ foreach ($files as $f) {
+ $size += filesize($f);
+ }
+
+ //collect plugin files info
+ $pluginFiles = [];
+
+ foreach ($files as $f) {
+ $name = basename($f);
+ $slug = pathinfo($name, PATHINFO_FILENAME);
+ $pluginFiles[] = [
+ 'name' => $name,
+ 'file' => $name,
+ 'slug' => $slug,
+ 'folder' => $folder,
+ 'file_path' => $folder . '/' . $name,
+ 'size' => formatBytes(filesize($f)),
+ 'size_bytes' => filesize($f),
+ 'download-url' => url(['module' => 'tools/plugins-backup', 'action' => 'download']),
+ 'delete-url' => url(['module' => 'tools/plugins-backup', 'action' => 'delete']),
+ 'restore-url' => url(['module' => 'tools/plugins-backup', 'action' => 'restore']),
+ ];
+ }
+
+ $backups[] = [
+ 'name' => $folder,
+ 'folder' => $folder,
+ 'file' => $folder, //for compatibility with backup.js expecting file
+ 'key' => $index,
+ 'size_bytes' => $size,
+ 'size' => formatBytes($size),
+ 'created_at' => date('Y/m/d H:i', filemtime($folderPath)),
+ 'count' => count($files),
+ 'files' => $pluginFiles,
+ 'restore-url' => url(['module' => 'tools/plugins-backup', 'action' => 'restore']),
+ 'download-url' => url(['module' => 'tools/plugins-backup', 'action' => 'download']),
+ 'delete-url' => url(['module' => 'tools/plugins-backup', 'action' => 'delete']),
+ ];
+ }
+
+ //sort backups by date desc (newest first)
+ usort($backups, fn ($a, $b) => strcmp($b['name'], $a['name']));
+
+ $view->backups = $backups;
+ $view->backupUrl = url(['module' => 'tools/plugins-backup', 'action' => 'save']);
+ $view->hasZip = class_exists('\ZipArchive');
+ }
+}
diff --git a/admin/controller/tools/themes-backup.php b/admin/controller/tools/themes-backup.php
new file mode 100755
index 0000000..af78f8e
--- /dev/null
+++ b/admin/controller/tools/themes-backup.php
@@ -0,0 +1,907 @@
+<?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 Vvveb\Controller\Base;
+use function Vvveb\formatBytes;
+use function Vvveb\sanitizeFileName;
+use Vvveb\System\Extensions\Themes;
+use function Vvveb\url;
+
+class ThemesBackup extends Base {
+ /**
+ * Base directory for themes backups.
+ *
+ * @var string
+ */
+ private string $backupDir;
+
+ /**
+ * Initialize backup directory.
+ */
+ public function __construct() {
+ $this->backupDir = DIR_BACKUP . 'themes' . DS;
+
+ if (!is_dir($this->backupDir)) {
+ @mkdir($this->backupDir, 0755, true);
+ }
+ }
+
+ /**
+ * Get list of available themes (slug => info).
+ *
+ * @return array<string, array<string, mixed>>
+ */
+ private function getThemesList(): array {
+ return Themes::getList(SITE_ID, false);
+ }
+
+ /**
+ * Sanitize theme name (slug) - allow only alphanum, dash, underscore.
+ *
+ * @param string $name Theme slug
+ *
+ * @return string Sanitized slug
+ */
+ private function sanitizeThemeName(string $name): string {
+ $name = basename(trim($name));
+
+ return preg_replace('/[^a-zA-Z0-9_\-]/', '', $name);
+ }
+
+ /**
+ * Create zip archive for a single theme.
+ *
+ * @param string $theme Theme slug
+ * @param string $destination Full path to zip file
+ *
+ * @return bool True on success
+ */
+ private function zipTheme(string $theme, string $destination): bool {
+ $theme = $this->sanitizeThemeName($theme);
+ $source = DIR_THEMES . $theme;
+
+ if (!$theme || !is_dir($source)) {
+ return false;
+ }
+
+ if (!class_exists('\ZipArchive')) {
+ return false;
+ }
+
+ $zip = new \ZipArchive();
+
+ if ($zip->open($destination, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) !== true) {
+ return false;
+ }
+
+ $sourceReal = realpath($source);
+
+ if ($sourceReal === false) {
+ $zip->close();
+
+ return false;
+ }
+
+ $iterator = new \RecursiveIteratorIterator(
+ new \RecursiveDirectoryIterator($sourceReal, \RecursiveDirectoryIterator::SKIP_DOTS),
+ \RecursiveIteratorIterator::LEAVES_ONLY
+ );
+
+ foreach ($iterator as $file) {
+ /** @var \SplFileInfo $file */
+ if (!$file->isDir()) {
+ $filePath = $file->getRealPath();
+ $relativePath = $theme . '/' . substr($filePath, strlen($sourceReal) + 1);
+ $zip->addFile($filePath, $relativePath);
+ }
+ }
+
+ $zip->close();
+
+ return file_exists($destination) && filesize($destination) > 0;
+ }
+
+ /**
+ * Extract a theme zip archive.
+ *
+ * @param string $zipFile Full path to zip file
+ *
+ * @return bool True on success
+ */
+ private function unzipTheme(string $zipFile): bool {
+ if (!file_exists($zipFile) || !class_exists('\ZipArchive')) {
+ return false;
+ }
+
+ $zip = new \ZipArchive();
+
+ if ($zip->open($zipFile) !== true) {
+ return false;
+ }
+
+ $result = $zip->extractTo(DIR_THEMES);
+ $zip->close();
+
+ return $result;
+ }
+
+ /**
+ * Generate unique folder name for backup run (Y-m-d-H-i).
+ *
+ * @return string Folder name
+ */
+ private function generateFolderName(): string {
+ $folder = date('Y-m-d-H-i');
+ $folder = sanitizeFileName($folder);
+ $base = $this->backupDir . $folder;
+
+ if (!is_dir($base)) {
+ return $folder;
+ }
+
+ //if folder already exists within same minute, add seconds or increment
+ $folderWithSeconds = date('Y-m-d-H-i-s');
+ $folderWithSeconds = sanitizeFileName($folderWithSeconds);
+
+ if (!is_dir($this->backupDir . $folderWithSeconds)) {
+ return $folderWithSeconds;
+ }
+
+ $i = 1;
+ while (is_dir($this->backupDir . $folder . '-' . $i)) {
+ $i++;
+ }
+
+ return $folder . '-' . $i;
+ }
+
+ /**
+ * Process next theme(s) for backup with time-limited execution.
+ *
+ * @return void
+ */
+ public function nextBackup(): void {
+ $folder = sanitizeFileName($this->request->get['folder'] ?? '');
+ $position = (int)($this->request->get['position'] ?? 0);
+ $themesParam = $this->request->get['themes'] ?? '';
+
+ //themes can be passed as comma separated string or array
+ if (is_array($themesParam)) {
+ $themes = $themesParam;
+ } else {
+ $themes = $themesParam !== '' ? explode(',', (string)$themesParam) : [];
+ }
+
+ //also check POST for themes on first step fallback
+ if (empty($themes) && isset($this->request->post['themes'])) {
+ $themes = (array)$this->request->post['themes'];
+ }
+
+ // sanitize themes
+ $themes = array_values(array_filter(array_map(fn ($p) => $this->sanitizeThemeName((string)$p), $themes)));
+
+ //if no themes passed, try to read from folder metadata (themes.json) if exists
+ if (empty($themes) && $folder && file_exists($this->backupDir . $folder . DS . 'themes.json')) {
+ $json = file_get_contents($this->backupDir . $folder . DS . 'themes.json');
+ $themes = json_decode($json, true) ?? [];
+ $themes = array_values(array_filter(array_map(fn ($p) => $this->sanitizeThemeName((string)$p), (array)$themes)));
+ }
+
+ if (!$folder) {
+ $error = __('Invalid backup folder!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ $folderPath = $this->backupDir . $folder;
+
+ if (!is_dir($folderPath)) {
+ $error = __('Backup folder does not exist!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ if (empty($themes)) {
+ $error = __('No themes selected!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ // validate themes exist
+ $available = $this->getThemesList();
+ $availableSlugs = array_keys($available);
+ //also allow themes that may not be in getList but folder exists (maybe broken)
+ foreach ($themes as $slug) {
+ if (!in_array($slug, $availableSlugs, true) && !is_dir(DIR_THEMES . $slug)) {
+ $error = sprintf(__('Theme "%s" not found!'), $slug);
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+ }
+
+ $count = count($themes);
+ $start = microtime(true);
+ $elapsed = 0;
+ $current = '';
+
+ //if takes longer than 8 seconds start a new process to avoid php timeout
+ while ($elapsed < 8 && ($position < $count)) {
+ $theme = $themes[$position];
+ $current = $theme;
+ $destination = $folderPath . DS . $theme . '.zip';
+
+ $success = $this->zipTheme($theme, $destination);
+
+ if (!$success) {
+ $error = sprintf(__('Error backing up theme "%s"!'), $theme);
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error, 'file' => $folder, 'position' => $position, 'count' => $count]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ $position++;
+
+ $end = microtime(true);
+ $elapsed = $end - $start;
+ }
+
+ //if all done, remove metadata file if exists
+ if ($position >= $count) {
+ $metaFile = $folderPath . DS . 'themes.json';
+ if (file_exists($metaFile)) {
+ @unlink($metaFile);
+ }
+
+ $message = __('Backup finished!');
+ $url = ['module' => 'tools/themes-backup', 'success' => $message];
+
+ if ($this->request->isAjax()) {
+ exit(json_encode($url + ['url' => url($url), 'file' => $folder, 'theme' => $current, 'position' => $position, 'count' => $count, 'success' => $message]));
+ } else {
+ $this->redirect($url);
+ $this->index();
+ }
+ } else {
+ $themeName = $themes[$position] ?? $current;
+ $themesEncoded = implode(',', $themes);
+ $url = ['module' => 'tools/themes-backup', 'action' => 'nextBackup', 'folder' => $folder, 'themes' => $themesEncoded, 'theme' => $themeName, 'position' => $position, 'count' => $count];
+
+ if ($this->request->isAjax()) {
+ exit(json_encode($url + ['url' => url($url), 'file' => $folder, 'theme' => $themeName, 'position' => $position, 'count' => $count]));
+ } else {
+ $this->redirect($url);
+ $this->index();
+ }
+ }
+ }
+
+ /**
+ * Process next theme(s) for restore with time-limited execution.
+ *
+ * @return void
+ */
+ public function nextRestore(): void {
+ if ($this->request->getMethod() !== 'post') {
+ $this->notFound(__('Invalid request method!'), 405);
+ }
+
+ $folder = sanitizeFileName($this->request->get['folder'] ?? $this->request->post['folder'] ?? '');
+ $fileParam = sanitizeFileName($this->request->get['file'] ?? $this->request->post['file'] ?? '');
+ $position = (int)($this->request->get['position'] ?? 0);
+
+ //if file contains path, split
+ if ($fileParam && str_contains($fileParam, DS)) {
+ $parts = explode(DS, $fileParam);
+ if (count($parts) === 2) {
+ $folder = $parts[0] ?: $folder;
+ $fileParam = $parts[1];
+ } else {
+ $folder = $parts[0] ?: $folder;
+ $fileParam = end($parts);
+ }
+ }
+
+ if ($fileParam) {
+ $fileParam = basename($fileParam);
+ }
+
+ if (!$folder) {
+ $error = __('Invalid backup folder!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ $folderPath = $this->backupDir . $folder;
+
+ if (!is_dir($folderPath)) {
+ $error = __('Backup folder does not exist!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ if ($fileParam) {
+ $singlePath = $folderPath . DS . $fileParam;
+ if (!file_exists($singlePath) || !is_file($singlePath)) {
+ $error = __('Backup does not exist!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error, 'file' => $folder, 'position' => $position, 'count' => 1]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+ $files = [$singlePath];
+ } else {
+ $files = glob($folderPath . DS . '*.zip') ?: [];
+ }
+ $count = count($files);
+ $start = microtime(true);
+
+ if ($count === 0) {
+ $error = __('No theme backups found in folder!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ sort($files);
+ $elapsed = 0;
+ $current = '';
+
+ while ($elapsed < 8 && ($position < $count)) {
+ $file = $files[$position];
+ $current = basename($file);
+
+ $success = $this->unzipTheme($file);
+
+ if (!$success) {
+ $error = sprintf(__('Error restoring theme "%s"!'), $current);
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error, 'file' => $folder, 'position' => $position, 'count' => $count]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ $position++;
+ $elapsed = microtime(true) - $start;
+ }
+
+ if ($position >= $count) {
+ $message = __('Restore finished!');
+ $url = ['module' => 'tools/themes-backup', 'success' => $message];
+
+ if ($this->request->isAjax()) {
+ exit(json_encode($url + ['url' => url($url), 'file' => $folder, 'theme' => $current, 'position' => $position, 'count' => $count, 'success' => $message]));
+ } else {
+ $this->redirect($url);
+ $this->view->success[] = $message;
+ $this->index();
+ }
+ } else {
+ $nextTheme = basename($files[$position] ?? $current);
+ $url = ['module' => 'tools/themes-backup', 'action' => 'nextRestore', 'folder' => $folder, 'theme' => $nextTheme, 'position' => $position, 'count' => $count];
+ if ($fileParam) {
+ $url['file'] = $fileParam;
+ }
+
+ if ($this->request->isAjax()) {
+ $jsonExtra = ['url' => url($url), 'file' => $folder, 'theme' => $nextTheme, 'position' => $position, 'count' => $count];
+ if ($fileParam) {
+ $jsonExtra['file'] = $folder . '/' . $fileParam;
+ }
+ exit(json_encode($url + $jsonExtra));
+ } else {
+ $this->redirect($url);
+ exit('Processing');
+ }
+ }
+ }
+
+ /**
+ * Delete a themes backup folder or single theme zip.
+ *
+ * @return void
+ */
+ public function delete(): void {
+ if ($this->request->getMethod() !== 'post') {
+ $this->notFound(__('Invalid request method!'), 405);
+ }
+
+ $folder = sanitizeFileName($this->request->post['folder'] ?? $this->request->post['file'] ?? '');
+ $file = sanitizeFileName($this->request->post['file'] ?? '');
+
+ //if file contains path separator, split folder and file
+ if ($file && str_contains($file, DS)) {
+ $parts = explode(DS, $file);
+ $folder = $parts[0];
+ $file = $parts[1] ?? '';
+ //if more parts (should not), use last as file and first as folder
+ if (count($parts) > 2) {
+ $folder = $parts[0];
+ $file = end($parts);
+ }
+ } elseif ($file && !$folder) {
+ //if file is actually folder name (legacy), treat as folder
+ if (is_dir($this->backupDir . $file) && !str_contains($file, '.')) {
+ $folder = $file;
+ $file = '';
+ }
+ }
+
+ //also check for folder param with slash
+ if ($folder && str_contains($folder, DS)) {
+ //folder should not contain slash beyond base, sanitize to basename
+ $folder = basename($folder);
+ }
+
+ if ($folder && $file) {
+ //delete single theme zip
+ $path = $this->backupDir . $folder . DS . $file;
+
+ if (file_exists($path) && is_file($path)) {
+ if (unlink($path)) {
+ //if folder empty after delete, remove folder
+ $remaining = glob($this->backupDir . $folder . DS . '*.zip');
+ if (empty($remaining)) {
+ @rmdir($this->backupDir . $folder);
+ }
+ $this->view->success[] = __('Backup deleted!');
+ } else {
+ $this->view->errors[] = __('Error deleting backup!');
+ }
+ } else {
+ $this->view->errors[] = __('Backup does not exist!');
+ }
+ } elseif ($folder) {
+ $path = $this->backupDir . $folder;
+
+ if (is_dir($path)) {
+ $result = \Vvveb\rrmdir($path);
+ @rmdir($path);
+ if ($result) {
+ $this->view->success[] = __('Backup deleted!');
+ } else {
+ $this->view->errors[] = __('Error deleting backup!');
+ }
+ } elseif (file_exists($path) && is_file($path)) {
+ if (unlink($path)) {
+ $this->view->success[] = __('Backup deleted!');
+ } else {
+ $this->view->errors[] = __('Error deleting backup!');
+ }
+ } else {
+ $this->view->errors[] = __('Backup does not exist!');
+ }
+ } else {
+ $this->view->errors[] = __('Invalid backup!');
+ }
+
+ $this->index();
+ }
+
+ /**
+ * Initiate a themes restore from a backup folder or single theme file.
+ *
+ * @return void
+ */
+ public function restore(): void {
+ if ($this->request->getMethod() !== 'post') {
+ $this->notFound(__('Invalid request method!'), 405);
+ }
+
+ $folder = sanitizeFileName($this->request->post['folder'] ?? $this->request->get['folder'] ?? '');
+ $file = sanitizeFileName($this->request->post['file'] ?? $this->request->get['file'] ?? '');
+
+ //if file contains path, split
+ if ($file && str_contains($file, DS)) {
+ $parts = explode(DS, $file);
+ if (count($parts) === 2) {
+ $folder = $parts[0] ?: $folder;
+ $file = $parts[1];
+ } else {
+ $folder = $parts[0] ?: $folder;
+ $file = end($parts);
+ }
+ } elseif ($file && !$folder && str_contains($file, '.zip')) {
+ //file param may be folder/file.zip without separate folder
+ $folder = '';
+ }
+
+ if ($folder && str_contains($folder, DS)) {
+ $folder = basename($folder);
+ }
+ if ($file) {
+ $file = basename($file);
+ }
+
+ //fallback: if folder empty but file contains folder path via post file
+ if (!$folder && $file && str_contains($this->request->post['file'] ?? '', '/')) {
+ $raw = sanitizeFileName($this->request->post['file'] ?? '', false);
+ //sanitize with normalized false to keep slash?
+ $parts = explode('/', $raw);
+ if (count($parts) === 2) {
+ $folder = sanitizeFileName($parts[0]);
+ $file = sanitizeFileName($parts[1]);
+ }
+ }
+
+ //legacy fallback: if folder contains .zip and no separate file
+ if ($folder && str_contains($folder, '.zip') && !$file) {
+ $file = basename($folder);
+ $folder = basename(dirname($this->request->post['file'] ?? $this->request->post['folder'] ?? ''));
+ $folder = sanitizeFileName($folder);
+ }
+
+ //also handle case where folder param actually contains file path (old backup.js pattern)
+ if (!$file && $folder && str_contains($this->request->post['file'] ?? '', '.zip')) {
+ $fileCandidate = sanitizeFileName($this->request->post['file'] ?? '');
+ if (str_contains($fileCandidate, '.zip')) {
+ $file = basename($fileCandidate);
+ }
+ }
+
+ if ($file) {
+ $url = ['module' => 'tools/themes-backup', 'action' => 'nextRestore', 'folder' => $folder, 'file' => $file];
+ $path = $this->backupDir . $folder . DS . $file;
+ if ($folder && is_dir($this->backupDir . $folder) && file_exists($path)) {
+ if ($this->request->isAjax()) {
+ exit(json_encode($url + ['url' => url($url)]));
+ } else {
+ $this->redirect($url);
+ $this->index();
+ }
+ } else {
+ $error = __('Backup does not exist!');
+ if ($this->request->isAjax()) {
+ exit(json_encode($url + ['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+ }
+ }
+
+ return;
+ }
+
+ $url = ['module' => 'tools/themes-backup', 'action' => 'nextRestore', 'folder' => $folder];
+
+ if ($folder && is_dir($this->backupDir . $folder)) {
+ if ($this->request->isAjax()) {
+ exit(json_encode($url + ['url' => url($url)]));
+ } else {
+ $this->redirect($url);
+ $this->index();
+ }
+ } else {
+ $error = __('Backup does not exist!');
+
+ if ($this->request->isAjax()) {
+ exit(json_encode($url + ['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+ }
+ }
+ }
+
+ /**
+ * Download a theme backup file or entire backup folder.
+ *
+ * @return void
+ */
+ public function download(): void {
+ $folder = sanitizeFileName($this->request->post['folder'] ?? $this->request->get['folder'] ?? '');
+ $file = sanitizeFileName($this->request->post['file'] ?? $this->request->get['file'] ?? '');
+
+ //if file contains folder separator, split
+ if ($file && str_contains($file, DS)) {
+ $parts = explode(DS, $file);
+ if (count($parts) === 2) {
+ $folder = $parts[0];
+ $file = $parts[1];
+ } else {
+ $folder = $parts[0];
+ $file = end($parts);
+ }
+ }
+
+ if ($folder && $file) {
+ $path = $this->backupDir . $folder . DS . $file;
+
+ if (file_exists($path) && is_file($path)) {
+ $fp = fopen($path, 'r');
+ header('Content-Type: application/zip');
+ header('Content-Length: ' . filesize($path));
+ header('Content-Disposition: attachment; filename="' . $file . '"');
+ fpassthru($fp);
+ exit();
+ } else {
+ $this->view->errors[] = __('Backup does not exist!');
+ }
+ } elseif ($folder) {
+ $folderPath = $this->backupDir . $folder;
+
+ if (is_dir($folderPath)) {
+ //create temporary zip of folder for download
+ $tmpFile = tempnam(sys_get_temp_dir(), 'themes_backup_') . '.zip';
+ $zip = new \ZipArchive();
+
+ if ($zip->open($tmpFile, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) === true) {
+ $files = new \RecursiveIteratorIterator(
+ new \RecursiveDirectoryIterator($folderPath, \RecursiveDirectoryIterator::SKIP_DOTS),
+ \RecursiveIteratorIterator::LEAVES_ONLY
+ );
+ foreach ($files as $f) {
+ $real = $f->getRealPath();
+ $relative = substr($real, strlen($folderPath) + 1);
+ $zip->addFile($real, $relative);
+ }
+ $zip->close();
+ header('Content-Type: application/zip');
+ header('Content-Length: ' . filesize($tmpFile));
+ header('Content-Disposition: attachment; filename="' . $folder . '.zip"');
+ readfile($tmpFile);
+ @unlink($tmpFile);
+ exit();
+ } else {
+ $this->view->errors[] = __('Error creating archive!');
+ }
+ } else {
+ $this->view->errors[] = __('Backup does not exist!');
+ }
+ } else {
+ $this->view->errors[] = __('Invalid backup!');
+ }
+
+ $this->index();
+ }
+
+ /**
+ * Initiate the themes backup process.
+ *
+ * @return void
+ */
+ public function save(): void {
+ $themes = $this->request->post['themes'] ?? [];
+
+ if (is_string($themes)) {
+ $themes = $themes !== '' ? explode(',', $themes) : [];
+ }
+
+ if (!is_array($themes)) {
+ $themes = (array)$themes;
+ }
+
+ $themes = array_values(array_filter(array_map(fn ($p) => $this->sanitizeThemeName((string)$p), $themes)));
+
+ if (empty($themes)) {
+ $error = __('No themes selected!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ //validate themes exist
+ $available = $this->getThemesList();
+ $availableSlugs = array_keys($available);
+
+ foreach ($themes as $slug) {
+ if (!in_array($slug, $availableSlugs, true) && !is_dir(DIR_THEMES . $slug)) {
+ $error = sprintf(__('Theme "%s" not found!'), $slug);
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+ }
+
+ if (!class_exists('\ZipArchive')) {
+ $error = __('ZipArchive extension is not available!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ $folder = $this->generateFolderName();
+ $folderPath = $this->backupDir . $folder;
+
+ if (!@mkdir($folderPath, 0755, true) && !is_dir($folderPath)) {
+ $error = __('Error creating backup folder!');
+ if ($this->request->isAjax()) {
+ exit(json_encode(['error' => $error]));
+ } else {
+ $this->view->errors[] = $error;
+ $this->index();
+
+ return;
+ }
+ }
+
+ //store themes list for next steps (in case url truncated, allow resume)
+ @file_put_contents($folderPath . DS . 'themes.json', json_encode($themes));
+
+ $themesEncoded = implode(',', $themes);
+ $url = ['module' => 'tools/themes-backup', 'action' => 'nextBackup', 'folder' => $folder, 'themes' => $themesEncoded, 'position' => 0, 'count' => count($themes)];
+
+ if ($this->request->isAjax()) {
+ exit(json_encode($url + ['url' => url($url), 'position' => 0, 'count' => count($themes), 'theme' => $themes[0], 'file' => $folder]));
+ } else {
+ $this->redirect($url);
+ $this->index();
+ }
+ }
+
+ /**
+ * Display the themes backup management page.
+ *
+ * @return void
+ */
+ public function index(): void {
+ $view = $this->view;
+
+ //available themes for selection
+ $themesList = $this->getThemesList();
+ $themes = [];
+
+ foreach ($themesList as $slug => $info) {
+ $themes[] = [
+ 'slug' => $slug,
+ 'name' => $info['name'] ?? $slug,
+ 'description' => $info['description'] ?? '',
+ 'version' => $info['version'] ?? '',
+ 'thumb_url' => $info['thumb_url'] ?? '',
+ 'status' => $info['status'] ?? 'inactive',
+ ];
+ }
+
+ //sort themes by name
+ usort($themes, fn ($a, $b) => strcmp($a['name'], $b['name']));
+
+ $view->themes = $themes;
+ $view->themeCount = count($themes);
+
+ //existing backups
+ $backupFolders = glob($this->backupDir . '*', GLOB_ONLYDIR) ?: [];
+ $backups = [];
+
+ foreach ($backupFolders as $index => $folderPath) {
+ $folder = basename($folderPath);
+ $files = glob($folderPath . DS . '*.zip') ?: [];
+ $size = 0;
+
+ foreach ($files as $f) {
+ $size += filesize($f);
+ }
+
+ //collect theme files info
+ $themeFiles = [];
+
+ foreach ($files as $f) {
+ $name = basename($f);
+ $slug = pathinfo($name, PATHINFO_FILENAME);
+ $themeFiles[] = [
+ 'name' => $name,
+ 'file' => $name,
+ 'slug' => $slug,
+ 'folder' => $folder,
+ 'file_path' => $folder . '/' . $name,
+ 'size' => formatBytes(filesize($f)),
+ 'size_bytes' => filesize($f),
+ 'download-url' => url(['module' => 'tools/themes-backup', 'action' => 'download']),
+ 'delete-url' => url(['module' => 'tools/themes-backup', 'action' => 'delete']),
+ 'restore-url' => url(['module' => 'tools/themes-backup', 'action' => 'restore']),
+ ];
+ }
+
+ $backups[] = [
+ 'name' => $folder,
+ 'folder' => $folder,
+ 'file' => $folder, //for compatibility with backup.js expecting file
+ 'key' => $index,
+ 'size_bytes' => $size,
+ 'size' => formatBytes($size),
+ 'created_at' => date('Y/m/d H:i', filemtime($folderPath)),
+ 'count' => count($files),
+ 'files' => $themeFiles,
+ 'restore-url' => url(['module' => 'tools/themes-backup', 'action' => 'restore']),
+ 'download-url' => url(['module' => 'tools/themes-backup', 'action' => 'download']),
+ 'delete-url' => url(['module' => 'tools/themes-backup', 'action' => 'delete']),
+ ];
+ }
+
+ //sort backups by date desc (newest first)
+ usort($backups, fn ($a, $b) => strcmp($b['name'], $a['name']));
+
+ $view->backups = $backups;
+ $view->backupUrl = url(['module' => 'tools/themes-backup', 'action' => 'save']);
+ $view->hasZip = class_exists('\ZipArchive');
+ }
+}
diff --git a/admin/controller/user/users.php b/admin/controller/user/users.php
index 586b5ef..cc26442 100755
--- a/admin/controller/user/users.php
+++ b/admin/controller/user/users.php
@@ -28,13 +28,28 @@ use function Vvveb\model;
use Vvveb\System\Images;
class Users extends Base {
- protected $type = 'user';
-
- protected $module = 'user/users';
-
- function delete() {
+ /**
+ * User type identifier (user or admin).
+ *
+ * @var string
+ */
+ protected string $type = 'user';
+
+ /**
+ * Module path for this controller.
+ *
+ * @var string
+ */
+ protected string $module = 'user/users';
+
+ /**
+ * Delete one or more users by their IDs.
+ *
+ * @return void
+ */
+ public function delete(): void {
$type = $this->type;
- $user_id = $this->request->post["{$type}_id"] ?? $this->request->get["{$type}_id"] ?? false;
+ $user_id = $this->request->post["{$type}_id"] ?? false;
if ($user_id) {
if (is_numeric($user_id)) {
@@ -52,25 +67,34 @@ class Users extends Base {
}
}
- return $this->index();
+ $this->index();
}
- function index($options = []) {
+ /**
+ * Display the list of users with filtering and pagination.
+ *
+ * @param array<string, mixed> $options Additional query options.
+ *
+ * @return void
+ */
+ public function index(array $options = []): void {
$type = $this->type;
$view = $this->view;
$users = model($type);
$this->filter = $this->request->get['filter'] ?? [];
- $options += [
- 'type' => $this->type,
+ $options += [
+ 'type' => $this->type,
] + $this->global + $this->filter;
$results = $users->getAll($options);
if ($results[$type]) {
foreach ($results[$type] as $id => &$user) {
+ unset($user['password']);
+
if (isset($user['avatar'])) {
- $user['avatar']= Images::image($user['avatar'], 'admin');
+ $user['avatar'] = Images::image($user['avatar'], 'admin');
}
$user['status_text'] = $user['status'] == '3' ? __('delete request') : ($user['status'] == '1' ? __('active') : __('inactive'));
diff --git a/public/js/common/router.js b/public/js/common/router.js
index bea4f88..2481158 100755
--- a/public/js/common/router.js
+++ b/public/js/common/router.js
@@ -25,8 +25,9 @@ let Router = {
}
};
- document.addEventListener("click", handleEvent);
- document.querySelectorAll("[data-v-vvveb-action][data-v-vvveb-on]").forEach(e => document.addEventListener(e.dataset.vVvvebOn, handleEvent));
+ //document.addEventListener("click", handleEvent);
+ //document.querySelectorAll("[data-v-vvveb-action][data-v-vvveb-on]").forEach(e => document.addEventListener(e.dataset.vVvvebOn, handleEvent));
+ document.querySelectorAll("[data-v-vvveb-action]").forEach(e => document.addEventListener(e.dataset.vVvvebOn ?? "click", handleEvent));
},
}