Skip to content

armgit / Vvveb

Public Imported from GitHub
0

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

Admin controllers and component refactoring

Givan5d333228e0ef
diff --git a/admin/controller/admin/auth-token.php b/admin/controller/admin/auth-token.php
old mode 100644
new mode 100755
index abfa606..1688298
--- a/admin/controller/admin/auth-token.php
+++ b/admin/controller/admin/auth-token.php
@@ -25,16 +25,11 @@ namespace Vvveb\Controller\Admin;
use function Vvveb\__;
use Vvveb\Controller\Listing;
use function Vvveb\humanReadable;
-use Vvveb\Sql\Admin_Auth_TokenSQL;
+use Vvveb\Sql\Admin_auth_tokenSQL;
+use Vvveb\System\User\Admin;
use function Vvveb\url;
-///use Vvveb\System\Traits\Crud as CrudTrait;
class AuthToken extends Listing {
- /*
- use CrudTrait {
- CrudTrait::delete as get;
- }*/
-
/**
* Auth token type identifier.
*
@@ -68,24 +63,24 @@ class AuthToken extends Listing {
*
* @return void
*/
- function index() : void {
+ public function index(): void {
$this->options['admin_id'] = $this->request->get['admin_id'] ?? false;
$this->options['limit'] = 1000;
- if (! $this->options['admin_id']) {
+ if (!$this->options['admin_id']) {
$this->notFound(__('User not found!'));
+
return;
}
-
if (!Admin::hasCapability('view_other_admin')) {
- if ($this->options['admin_id'] || ($this->options['admin_id'] != $this->global['admin_id'])) {
- $message = __('Permission denied!');
+ if ($this->options['admin_id'] != $this->global['admin_id']) {
+ $message = __('Permission denied!');
$this->view->errors[] = $message;
$this->notFound($message, 403, true);
}
}
-
+
$this->view->user_url = url(['module' => 'admin/user', 'admin_id' => $this->options['admin_id']]);
parent::index();
}
@@ -95,25 +90,26 @@ class AuthToken extends Listing {
*
* @return void
*/
- function save() : void {
+ public function save(): void {
$admin_auth_token = $this->request->post['admin_auth_token'] ?? [];
$admin_id = $this->request->get['admin_id'] ?? false;
$editCapability = 'edit_other_admin';
if (!Admin::hasCapability($editCapability)) {
- if (! $admin_id || $admin_id != $this->global['admin_id']) {
- $view->errors[] = __('Permission denied!');
+ if (!$admin_id || $admin_id != $this->global['admin_id']) {
+ $this->view->errors[] = __('Permission denied!');
+
return;
}
}
-
+
if ($admin_auth_token && $admin_id) {
foreach ($admin_auth_token as $key => $token) {
- if ($key == '#') {
+ if ($key == '#' || $key == '#admin_auth_token') {
unset($admin_auth_token[$key]);
}
- if (! $token['admin_auth_token_id']) {
+ if (!$token['admin_auth_token_id']) {
unset($admin_auth_token[$key]['admin_auth_token_id']);
}
}
@@ -121,7 +117,7 @@ class AuthToken extends Listing {
$adminAuthToken = new Admin_Auth_TokenSQL();
if (($result = $adminAuthToken->update(['admin_auth_token' => $admin_auth_token, 'admin_id' => $admin_id] + $this->global))/* && $result['admin_auth_token']*/) {
- $this->view->success['get'] =humanReadable(__($this->type)) . __(' saved!');
+ $this->view->success['get'] = humanReadable(__($this->type)) . __(' saved!');
} else {
$this->view->errors[] = __('Error saving!');
}
diff --git a/admin/controller/admin/role.php b/admin/controller/admin/role.php
index 2c6b071..cc3d275 100755
--- a/admin/controller/admin/role.php
+++ b/admin/controller/admin/role.php
@@ -29,32 +29,60 @@ use Vvveb\System\Cache;
use Vvveb\System\User\Role as RoleList;
class Role extends Base {
- protected $type = 'role';
-
- protected $app = 'admin';
-
- protected $apps = [
+ /**
+ * Role type identifier.
+ *
+ * @var string
+ */
+ protected string $type = 'role';
+
+ /**
+ * Current application context.
+ *
+ * @var string
+ */
+ protected string $app = 'admin';
+
+ /**
+ * Available applications and their permission methods.
+ *
+ * @var array<string, array{permissions: list<string>}>
+ */
+ protected array $apps = [
'admin' => ['permissions' => ['controllers']],
'rest' => ['permissions' => ['routes', 'controllers']],
'graphql' => ['permissions' => ['controllers', 'models']],
+ 'mcp' => ['permissions' => ['controllers', 'models']],
];
- function init() {
+ /**
+ * Initialize the application context from the request.
+ *
+ * @return string|null
+ */
+ public function init(): ?string {
$this->app = $this->request->get['app'] ?? 'admin';
- if (! isset($this->apps[$this->app])) {
+ if (!isset($this->apps[$this->app])) {
//$this->view->errors[] = __('Invalid app!');
- return $this->notFound(__('Invalid app!'));
+ $this->notFound(__('Invalid app!'));
+
+ return null;
}
- parent::init();
+ return parent::init();
}
- function index() {
+ /**
+ * Display the role edit form with permissions tree and capabilities.
+ *
+ * @return void
+ */
+ public function index(): void {
$role_id = $this->request->get['role_id'] ?? false;
$cache = Cache::getInstance();
- $tree = $cache->cache(APP, $this->app . '-permissions',function () {
+ $tree = $cache->cache(APP, $this->app . '-permissions', function() {
$tree = [];
//$this->view->tree = RoleList::controllers($this->app);
foreach ($this->apps[$this->app]['permissions'] as $method) {
@@ -94,13 +122,18 @@ class Role extends Base {
}
$this->view->role['permissions'] = $permissions;
- $this->view->role['permissions']['deny'] = $this->view->role['permissions']['deny'] ?? [];
- $this->view->role['permissions']['allow'] = $this->view->role['permissions']['allow'] ?? [];
- $this->view->role['permissions']['capabilities'] = $this->view->role['permissions']['capabilities'] ?? [];
+ $this->view->role['permissions']['deny'] ??= [];
+ $this->view->role['permissions']['allow'] ??= [];
+ $this->view->role['permissions']['capabilities'] ??= [];
}
}
- function save() {
+ /**
+ * Save the role with its permissions, handling both create and update.
+ *
+ * @return void
+ */
+ public function save(): void {
$data = $this->request->post['role'] ?? [];
$allow = $this->request->post['allow'] ?? [];
$deny = $this->request->post['deny'] ?? [];
@@ -111,7 +144,7 @@ class Role extends Base {
$role = new RoleSQL();
$this->view->role = $role->get(['role_id' => $role_id]);
- $currentPermissions = json_decode($this->view->role['permissions'], true);
+ $currentPermissions = $this->view->role ? json_decode($this->view->role['permissions'], true) : null;
if ($currentPermissions) {
//backward compatibility
@@ -136,6 +169,6 @@ class Role extends Base {
$this->view->errors[] = __('Error saving!');
}
- return $this->index();
+ $this->index();
}
}
diff --git a/admin/controller/admin/roles.php b/admin/controller/admin/roles.php
index 6265958..75d64d0 100755
--- a/admin/controller/admin/roles.php
+++ b/admin/controller/admin/roles.php
@@ -25,13 +25,38 @@ namespace Vvveb\Controller\Admin;
use Vvveb\Controller\Listing;
class Roles extends Listing {
- protected $type = 'role';
-
- protected $controller = 'role';
-
- protected $listController = 'roles';
-
- protected $list = 'role';
-
- protected $module = 'admin';
+ /**
+ * Role type identifier.
+ *
+ * @var string
+ */
+ protected string $type = 'role';
+
+ /**
+ * Singular controller name for detail views.
+ *
+ * @var string
+ */
+ protected string $controller = 'role';
+
+ /**
+ * Plural controller name for listing views.
+ *
+ * @var string
+ */
+ protected string $listController = 'roles';
+
+ /**
+ * List key used to identify the data collection.
+ *
+ * @var string
+ */
+ protected string $list = 'role';
+
+ /**
+ * Module path this controller belongs to.
+ *
+ * @var string
+ */
+ protected string $module = 'admin';
}
diff --git a/admin/controller/admin/user.php b/admin/controller/admin/user.php
index 8c38571..651b2c7 100755
--- a/admin/controller/admin/user.php
+++ b/admin/controller/admin/user.php
@@ -23,25 +23,36 @@
namespace Vvveb\Controller\Admin;
use Vvveb\Controller\User\User as UserBase;
+use Vvveb\Sql\RoleSQL;
use Vvveb\Sql\SiteSQL;
class User extends UserBase {
- protected $type = 'admin';
+ /**
+ * User type identifier for admin users.
+ *
+ * @var string
+ */
+ protected string $type = 'admin';
- function index() {
+ /**
+ * Display the admin user edit form with roles and site access data.
+ *
+ * @return void
+ */
+ public function index(): void {
parent :: index();
- $roles = new \Vvveb\Sql\RoleSQL();
+ $roleSQL = new RoleSQL();
- $options = [
- 'type' => 'admin', //$this->type,
- 'limit'=> 100,
+ $options = [
+ 'type' => 'admin',
+ 'limit' => 100,
] + $this->global;
- $roles = $roles->getAll($options);
- $sites = new SiteSQL();
+ $roles = $roleSQL->getAll($options);
+ $sites = new SiteSQL();
- if (! isset($this->view->user['site_access'])) {
+ if (!isset($this->view->user['site_access'])) {
//set default site access to current site for new user
$this->view->user['site_access'] = [$this->global['site_id']];
}
diff --git a/admin/controller/admin/users.php b/admin/controller/admin/users.php
index ccfa12b..dad3313 100755
--- a/admin/controller/admin/users.php
+++ b/admin/controller/admin/users.php
@@ -26,11 +26,28 @@ use Vvveb\Controller\User\Users as UsersBase;
use Vvveb\System\User\Admin;
class Users extends UsersBase {
- protected $type = 'admin';
+ /**
+ * User type identifier for admin users.
+ *
+ * @var string
+ */
+ protected string $type = 'admin';
- protected $module = 'admin/users';
+ /**
+ * Module path for this controller.
+ *
+ * @var string
+ */
+ protected string $module = 'admin/users';
- function index($options = []) {
+ /**
+ * Display the list of admin users, filtering by capability.
+ *
+ * @param array<string, mixed> $options Additional query options.
+ *
+ * @return void
+ */
+ public function index(array $options = []): void {
if (Admin::hasCapability('view_other_admin')) {
unset($options['admin_id']);
} else {
diff --git a/admin/controller/content/autocomplete-trait.php b/admin/controller/content/autocomplete-trait.php
old mode 100644
new mode 100755
index 3fd49fe..c3f6843
--- a/admin/controller/content/autocomplete-trait.php
+++ b/admin/controller/content/autocomplete-trait.php
@@ -22,13 +22,18 @@
namespace Vvveb\Controller\Content;
-use \Vvveb\Sql\categorySQL;
use function Vvveb\__;
+use Vvveb\Sql\CategorySQL;
use Vvveb\System\Images;
use function Vvveb\url;
trait AutocompleteTrait {
- function categoriesAutocomplete() {
+ /**
+ * Returns category autocomplete suggestions as JSON.
+ *
+ * @return void
+ */
+ public function categoriesAutocomplete(): void {
$categories = new CategorySQL();
$text = trim($this->request->get['text'] ?? '');
$type = trim($this->request->get['type'] ?? '');
@@ -52,7 +57,12 @@ trait AutocompleteTrait {
$this->response->output($search);
}
- function manufacturersAutocomplete() {
+ /**
+ * Returns manufacturer autocomplete suggestions as JSON.
+ *
+ * @return void
+ */
+ public function manufacturersAutocomplete(): void {
$manufacturers = new \Vvveb\Sql\ManufacturerSQL();
$text = trim($this->request->get['text'] ?? '');
@@ -75,7 +85,12 @@ trait AutocompleteTrait {
$this->response->output($search);
}
- function vendorsAutocomplete() {
+ /**
+ * Returns vendor autocomplete suggestions as JSON.
+ *
+ * @return void
+ */
+ public function vendorsAutocomplete(): void {
$vendors = new \Vvveb\Sql\VendorSQL();
$text = trim($this->request->get['text'] ?? '');
@@ -98,7 +113,12 @@ trait AutocompleteTrait {
$this->response->output($search);
}
- function urlAutocomplete() {
+ /**
+ * Returns URL autocomplete suggestions (products, posts, pages) as JSON.
+ *
+ * @return void
+ */
+ public function urlAutocomplete(): void {
$products = new \Vvveb\Sql\ProductSQL();
$text = trim($this->request->get['text'] ?? '');
$type = $this->request->get['type'] ?? 'card'; //'key-value'
@@ -135,14 +155,14 @@ trait AutocompleteTrait {
if (isset($results['product'])) {
foreach ($results['product'] as $product) {
$product['image'] = Images::image($product['image'], 'product', 'thumb');
- $url = url('product/product/index', ['slug'=> $product['slug'], 'product_id' => $product['product_id']]);
+ $url = url('product/product/index', ['slug' => $product['slug'], 'product_id' => $product['product_id']]);
if ($type == 'card') {
$search[] = [
- 'type' => 'cardimage',
- 'src' => $product['image'],
- 'text' => $product['name'],
- 'value'=> '<a href="' . $url . '">' . $product['name'] . '</a>',
+ 'type' => 'cardimage',
+ 'src' => $product['image'],
+ 'text' => $product['name'],
+ 'value' => '<a href="' . $url . '">' . $product['name'] . '</a>',
];
} else {
$search[$url] = '<img width="32" height="32" src="' . $product['image'] . '"> ' . $product['name'];
@@ -157,14 +177,14 @@ trait AutocompleteTrait {
if (isset($results['post'])) {
foreach ($results['post'] as $post) {
$post['image'] = Images::image($post['image'], 'post', 'thumb');
- $url = url('content/post/index', ['slug'=> $post['slug'], 'post_id' => $post['post_id']]);
+ $url = url('content/post/index', ['slug' => $post['slug'], 'post_id' => $post['post_id']]);
if ($type == 'card') {
$search[] = [
- 'type' => 'cardimage',
- 'src' => $post['image'],
- 'text' => $post['name'],
- 'value'=> '<a href="' . $url . '">' . $post['name'] . '</a>',
+ 'type' => 'cardimage',
+ 'src' => $post['image'],
+ 'text' => $post['name'],
+ 'value' => '<a href="' . $url . '">' . $post['name'] . '</a>',
];
} else {
$search[$url] = '<img width="32" height="32" src="' . $post['image'] . '"> ' . $post['name'];
@@ -177,7 +197,12 @@ trait AutocompleteTrait {
$this->response->output($search);
}
- function productsAutocomplete() {
+ /**
+ * Returns product autocomplete suggestions as JSON.
+ *
+ * @return void
+ */
+ public function productsAutocomplete(): void {
$products = new \Vvveb\Sql\ProductSQL();
$text = trim($this->request->get['text'] ?? '');
@@ -201,7 +226,12 @@ trait AutocompleteTrait {
$this->response->output($search);
}
- function adminsAutocomplete() {
+ /**
+ * Returns admin user autocomplete suggestions as JSON.
+ *
+ * @return void
+ */
+ public function adminsAutocomplete(): void {
$admins = new \Vvveb\Sql\AdminSQL();
$text = trim($this->request->get['text'] ?? '');
@@ -232,7 +262,12 @@ trait AutocompleteTrait {
$this->response->output($search);
}
- function attributesAutocomplete() {
+ /**
+ * Returns attribute autocomplete suggestions as JSON.
+ *
+ * @return void
+ */
+ public function attributesAutocomplete(): void {
$attributes = new \Vvveb\Sql\AttributeSQL();
$text = trim($this->request->get['text'] ?? '');
@@ -246,9 +281,7 @@ trait AutocompleteTrait {
if (isset($results['attribute'])) {
foreach ($results['attribute'] as $attribute) {
- $text = '';
-
- $text .= $attribute['name'] . ' (' . $attribute['group'] . ')';
+ $text = $attribute['name'] . ' (' . $attribute['group'] . ')';
$search[$attribute['attribute_id']] = $text;
}
@@ -258,11 +291,16 @@ trait AutocompleteTrait {
$this->response->output($search);
}
- function optionValuesAutocomplete() {
+ /**
+ * Returns option values autocomplete suggestions as JSON.
+ *
+ * @return void
+ */
+ public function optionValuesAutocomplete(): void {
$values = new \Vvveb\Sql\Option_valueSQL();
$options = [
- 'option_id' => trim($this->request->get['option_id']),
+ 'option_id' => trim($this->request->get['option_id'] ?? ''),
] + $this->global;
$results = $values->getAll($options);
@@ -271,11 +309,7 @@ trait AutocompleteTrait {
if (isset($results['option_value'])) {
foreach ($results['option_value'] as $value) {
- $text = '';
-
- $text .= $value['name'];
-
- $search[$value['option_value_id']] = $text;
+ $search[$value['option_value_id']] = $value['name'];
}
}
@@ -283,7 +317,12 @@ trait AutocompleteTrait {
$this->response->output($search);
}
- function digitalAssetsAutocomplete() {
+ /**
+ * Returns digital asset autocomplete suggestions as JSON.
+ *
+ * @return void
+ */
+ public function digitalAssetsAutocomplete(): void {
$digital_assets = new \Vvveb\Sql\Digital_assetSQL();
$text = trim($this->request->get['text'] ?? '');
@@ -297,9 +336,7 @@ trait AutocompleteTrait {
if (isset($results['digital_asset'])) {
foreach ($results['digital_asset'] as $digital_asset) {
- $text = '';
-
- $text .= $digital_asset['name'] . ' (' . $digital_asset['file'] . ')';
+ $text = $digital_asset['name'] . ' (' . $digital_asset['file'] . ')';
$search[$digital_asset['digital_asset_id']] = $text;
}
diff --git a/admin/controller/content/categories.php b/admin/controller/content/categories.php
index 0a036c3..c16d0ca 100755
--- a/admin/controller/content/categories.php
+++ b/admin/controller/content/categories.php
@@ -22,15 +22,20 @@
namespace Vvveb\Controller\Content;
-use \Vvveb\Sql\categorySQL;
use function Vvveb\__;
use Vvveb\Controller\Base;
+use Vvveb\Sql\CategorySQL;
use Vvveb\System\Images;
class Categories extends Base {
- function delete() {
+ /**
+ * Deletes one or more taxonomy items by ID.
+ *
+ * @return never
+ */
+ public function delete(): never {
$taxonomy_item_id = $this->request->post['taxonomy_item_id'] ?? false;
- $categories = new categorySQL();
+ $categories = new CategorySQL();
if (is_numeric($taxonomy_item_id)) {
$taxonomy_item_id = [$taxonomy_item_id];
@@ -40,28 +45,42 @@ class Categories extends Base {
echo __('Item removed!');
}
- die(0);
+ exit();
}
- function reorder() {
+ /**
+ * Reorders taxonomy items based on submitted data.
+ *
+ * @return never
+ */
+ public function reorder(): never {
$data = $this->request->post;
- $categories = new categorySQL();
+ $categories = new CategorySQL();
//['taxonomy_items' => $data]
if ($categories->updateTaxonomyItems($data)) {
echo __('Items reordered!');
}
- die(0);
+ exit();
}
- function save() {
+ /**
+ * Saves a new or existing taxonomy item.
+ *
+ * @return void
+ */
+ public function save(): void {
$data = $this->request->post;
- $data['taxonomy_id'] = $data['taxonomy_id'] ?? $this->request->get['taxonomy_id'];
+ $data['taxonomy_id'] ??= $this->request->get['taxonomy_id'];
$data['taxonomy_item']['taxonomy_id'] = $data['taxonomy_id'];
- $data['taxonomy_item']['sort_order'] = $data['sort_order'] ?? 0;
+ $data['taxonomy_item']['sort_order'] = $data['sort_order'] ?? 0;
- $categories = new categorySQL();
+ $categories = new CategorySQL();
+ $results = [];
+ $success = false;
+ $message = '';
+ $taxonomy_item_id = false;
$options = [
'taxonomy_item_content' => $data['taxonomy_item_content'],
@@ -71,36 +90,48 @@ class Categories extends Base {
if (isset($data['taxonomy_item_id']) && $data['taxonomy_item_id']) {
$options['taxonomy_item_id'] = $data['taxonomy_item_id'];
$results = $categories->editTaxonomyItem($options);
+ $taxonomy_item_id = $data['taxonomy_item_id'];
if ($results) {
- echo __('Item saved!');
+ $message = __('Item saved!');
+ $success = true;
}
} else {
$results = $categories->addTaxonomyItem($options);
if ($results) {
- echo __('Item added!');
+ $taxonomy_item_id = $results['taxonomy_item'];
+ $message = __('Item added!');
+ $success = true;
}
}
- die(0);
+ $results['message'] = $message;
+ $results['success'] = $success;
+ $results['taxonomy_item_id'] = $taxonomy_item_id;
- return;
+ $this->response->setType('json');
+ $this->response->output($results);
}
- function index() {
+ /**
+ * Lists all categories for a given taxonomy with multilingual support.
+ *
+ * @return void
+ */
+ public function index(): void {
$view = $this->view;
- $categories = new categorySQL();
+ $categories = new CategorySQL();
$page = $this->request->get['page'] ?? 1;
$type = $this->request->get['type'] ?? '';
$taxonomy_id = $this->request->get['taxonomy_id'] ?? false;
$limit = 1000;
- $admin_path = \Vvveb\adminPath();
- $controllerPath = $admin_path . 'index.php?module=media/media';
- $this->view->scanUrl = "$controllerPath&action=scan";
- $this->uploadUrl = "$controllerPath&action=upload";
+ $admin_path = \Vvveb\adminPath();
+ $controllerPath = $admin_path . 'index.php?module=media/media';
+ $this->view->scanUrl = "$controllerPath&action=scan";
+ $this->view->uploadUrl = "$controllerPath&action=upload";
if ($taxonomy_id) {
$options = [
diff --git a/admin/controller/content/comment.php b/admin/controller/content/comment.php
index 10ee72d..ee91ec7 100644
--- a/admin/controller/content/comment.php
+++ b/admin/controller/content/comment.php
@@ -28,9 +28,14 @@ use function Vvveb\model;
use Vvveb\System\User\Admin;
class Comment extends Base {
- protected $type = 'comment';
-
- function save() {
+ protected string $type = 'comment';
+
+ /**
+ * Saves a comment (new or existing) and redirects to the index.
+ *
+ * @return void
+ */
+ public function save(): void {
$type = $this->type;
$comment_id = $this->request->get[$type . '_id'] ?? false;
$comment = $this->request->post[$type] ?? false;
@@ -65,10 +70,15 @@ class Comment extends Base {
}
}
- return $this->index();
+ $this->index();
}
- function index() {
+ /**
+ * Displays a single comment by ID.
+ *
+ * @return void
+ */
+ public function index(): void {
$type = $this->type;
$comments = model($type);
$comment_id = $this->request->get[$type . '_id'] ?? false;
@@ -92,7 +102,7 @@ class Comment extends Base {
$this->view->$type = $comments->get($options);
- if (! $this->view->$type) {
+ if (!$this->view->$type) {
$this->notFound();
}
}
diff --git a/admin/controller/content/edit.php b/admin/controller/content/edit.php
index 7e3d3ee..097e2cc 100644
--- a/admin/controller/content/edit.php
+++ b/admin/controller/content/edit.php
@@ -24,42 +24,44 @@ namespace Vvveb\Controller\Content;
use function Vvveb\__;
use Vvveb\Controller\Base;
-use function Vvveb\getSetting;
use function Vvveb\humanReadable;
-use function Vvveb\model;
-use function Vvveb\sanitizeHTML;
-use function Vvveb\setSetting;
-use function Vvveb\slugify;
-use Vvveb\Sql\CategorySQL;
-use Vvveb\Sql\Field_GroupSQL;
+use Vvveb\Sql\Field_groupSQL;
use Vvveb\Sql\FieldSQL;
use Vvveb\System\Cache;
-use Vvveb\System\CacheManager;
-use Vvveb\System\Core\View;
-use Vvveb\System\Event;
-use Vvveb\System\Images;
use Vvveb\System\Sites;
+use Vvveb\System\Traits\Edit as EditTrait;
use Vvveb\System\Traits\FieldGroup;
use Vvveb\System\User\Admin;
-use Vvveb\System\Validator;
class Edit extends Base {
- protected $type = 'post';
-
- protected $object = 'post';
-
- protected $revisions = true;
-
- use TaxonomiesTrait, AutocompleteTrait, SitesTrait, FieldGroup;
-
- function getThemeFolder() {
- return DIR_THEMES . Sites::getTheme($this->global['site_id']) ?? 'default';
+ use AutocompleteTrait;
+ use EditTrait;
+ use FieldGroup;
+ use SitesTrait;
+ use TaxonomiesTrait;
+ protected string $type = 'post';
+
+ protected string $object = 'post';
+
+ protected bool $revisions = true;
+
+ /**
+ * Returns the theme folder path for the current site.
+ *
+ * @return string Theme folder path.
+ */
+ protected function getThemeFolder(): string {
+ return DIR_THEMES . (Sites::getTheme($this->global['site_id']));
}
- function fields() {
- $field_group_id = 1;
+ /**
+ * Loads custom field groups and renders them for the editor view.
+ *
+ * @return void
+ */
+ protected function fields(): void {
$options = ['type' => $this->object, 'subtype' => $this->type, 'limit' => 1000];
- $fieldGroup = new Field_GroupSQL();
+ $fieldGroup = new Field_groupSQL();
$fieldGroups = $fieldGroup->getAll($options + $this->global)['field_group'] ?? [];
$langsFields = [];
@@ -114,19 +116,21 @@ class Edit extends Base {
$this->view->count = $fields['count'] ?? 0;
}
- function index() {
+ /**
+ * Main index action - loads post data, templates, revisions, taxonomies, and sites for the editor.
+ *
+ * @return void
+ */
+ public function index(): void {
$view = $this->view;
- $admin_path = \Vvveb\adminPath();
- $postOptions = [];
- $post = [];
- $post_id = $this->request->get[$this->object . '_id'] ?? $this->request->post[$this->object . '_id'] ?? false;
+ $admin_path = \Vvveb\adminPath();
$controllerPath = $admin_path . 'index.php?module=media/media';
$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 = '';
if (file_exists(DIR_THEMES . "$theme/css/admin-post-editor.css")) {
@@ -150,138 +154,24 @@ class Edit extends Base {
$viewCapability = 'view_other_products';
}
- if ($post_id) {
- $postOptions[$this->object . '_id'] = (int)$post_id;
- } else {
- if (isset($this->request->get['slug'])) {
- $postOptions['slug'] = $this->request->get['slug'];
- }
- }
+ $postId = $this->request->get[$this->object . '_id'] ?? $this->request->post[$this->object . '_id'] ?? false;
- if (isset($this->request->get['type'])) {
- $this->type = $this->request->get['type'];
- }
-
- if ($postOptions) {
- $posts = model($this->object);
-
- $postOptions['type'] = $this->type;
- $options = $postOptions + $this->global;
-
- if (Admin::hasCapability($viewCapability)) {
- unset($options['admin_id']);
- } else {
- $options['admin_id'] = $this->global['admin_id'];
- }
+ [$post, $postId, $type, $name, $revisionsUrl] = $this->getEditPostData(
+ $this->object,
+ $this->type,
+ $postId,
+ $this->request->get['slug'] ?? false,
+ $this->request->get['type'] ?? null,
+ $this->global,
+ $this->view->languagesList ?? [],
+ Admin::hasCapability($viewCapability)
+ );
- //get all languages
- //unset($options['language_id']);
- $post = $posts->get($options);
-
- if (! $post) {
- $message = sprintf(__('%s not found!'), humanReadable(__($this->type)));
- $this->notFound(['message' => $message, 'title' => $message]);
- }
+ $this->type = $type;
- //featured image
- if (isset($post['image'])) {
- $post['image_url'] = Images::image($post['image'], $this->object);
- }
-
- //gallery
- if (isset($post[$this->object . '_image'])) {
- $post['images'] = Images::images($post[$this->object . '_image'], $this->object);
- }
-
- //$productImages = $posts->getImages($postOptions);
- } else {
- $post['image_url'] = Images::image('',$this->object);
- $post['updated_at'] = date('Y-m-d H:i:s', time());
- }
-
- /*
- if (isset($post['updated_at'])) {
- $post['updated_at'] = str_replace(' ', 'T', $post['updated_at']);
- } else {
- $post['updated_at'] = date("Y-m-d\TH:i:s", isset($post['updated_at']) && $post['updated_at'] ? strtotime($post['updated_at']) : time());
- }*/
-
- $this->type = $post['type'] ?? $this->type;
-
- if ($this->object == 'product') {
- $route = "product/{$this->type}/index";
- $altRoute = "product/{$this->object}/index";
- $controller = 'product';
- } else {
- $route = "content/{$this->type}/index";
- $altRoute = "content/{$this->object}/index";
- $controller = 'content';
- $stickyPosts = getSetting('posts', 'sticky') ?? [];
- //$post['sticky'] = in_array($post['post_id'], $stickyPosts);
- $post['sticky'] = isset($post['post_id']) && isset($stickyPosts[$post['post_id']]);
- }
-
- if ($this->revisions) {
- $revisions = model($this->object . '_content_revision');
- }
-
- //get site host for current selected site to use for absolute url
- $url = ['host' => $this->global['host'], 'path' => $this->global['path'] ? '/' . $this->global['path'] : null];
-
- if ($this->type != $this->object) {
- $url['type'] = $this->type;
- }
-
- $revisionsUrl = \Vvveb\url(['module' => "$controller/revisions", 'object' => $this->object, 'type' => $this->type, $this->object . '_id' => $post_id]);
- $name = '';
-
- if (isset($post[$this->object . '_content'])) {
- foreach ($post[$this->object . '_content'] as &$content) {
- if (! isset($post['url'])) {
- $post['url'] = \Vvveb\url($route, ['slug'=> $content['slug'], $this->object . '_id' => $post_id] + $url);
- $post['relative-url'] = \Vvveb\url($route, ['slug'=> $content['slug'], $this->object . '_id' => $post_id]);
-
- if (! $post['url'] || $post['url'] == '//' . $this->global['site_url']) {
- $post['url'] = \Vvveb\url($altRoute, ['slug'=> $content['slug'], $this->object . '_id' => $post_id] + $url);
- $post['relative-url'] = \Vvveb\url($altRoute, ['slug'=> $content['slug'], $this->object . '_id' => $post_id]);
- }
- }
- $language = [];
-
- if ($content['language_id'] != $this->global['default_language_id']) {
- $code = 'en_US';
-
- foreach ($this->view->languagesList as $code => $lang) {
- if ($lang['language_id'] == $content['language_id']) {
- break;
- }
- }
- $language = ['language' => $code];
- } else {
- $name = $content['name'];
- }
-
- $content['url'] = \Vvveb\url($route, $content + $language + $url);
- $content['revision_count'] = 0;
-
- if (! $content['url'] || $content['url'] == '//' . $this->global['site_url']) {
- $content['url'] = \Vvveb\url($altRoute, $content + $language + $url);
- }
-
- if ($revisions) {
- $revision = $revisions->getAll([$this->object . '_id' => $post_id, 'language_id' => $content['language_id']]);
-
- if ($revision) {
- foreach ($revision[$this->object . '_content_revision'] as &$rev) {
- $rev['preview-url'] = $content['url'] . '?revision=preview&created_at=' . $rev['created_at'] . '&language_id=' . $content['language_id'];
- $rev['compare-url'] = $revisionsUrl . '&created_at=' . $rev['created_at'] . '&language_id=' . $content['language_id'];
- }
-
- $content['revision_count'] = $revision['count'];
- $content['revision'] = $revision[$this->object . '_content_revision'];
- }
- }
- }
+ if (!$post) {
+ $message = sprintf(__('%s not found!'), humanReadable(__($this->type)));
+ $this->notFound(['message' => $message, 'title' => $message]);
}
$type_name = humanReadable(__($this->type));
@@ -293,11 +183,13 @@ class Edit extends Base {
$design_url = '';
if (isset($post['url'])) {
- $design_url = \Vvveb\url(['module' => 'editor/editor', 'name' => urlencode($name), 'url' => $post['relative-url'], 'template' => $template], false);
+ $design_url = \Vvveb\url(['module' => 'editor/page-builder', 'name' => urlencode($name), 'url' => $post['relative-url'], 'template' => $template], false);
$post['design_url'] = $design_url;
}
- if (! file_exists($themeFolder . DS . $template)) {
+ $view->template_missing = '';
+
+ if (!file_exists($themeFolder . DS . $template)) {
if ($template == $defaultTemplate) {
$view->template_missing = sprintf(__('Template missing, choose existing template or %screate global template%s for %s.'), '<a href="' . $design_url . '" target="_blank">', '</a>', $type_name);
} else {
@@ -306,7 +198,7 @@ class Edit extends Base {
}
$view->taxonomies = $this->taxonomies($post[$this->object . '_id'] ?? false);
-
+
if ($this->type == 'page') {
//remove menu type
unset($view->taxonomies[3]);
@@ -317,24 +209,20 @@ class Edit extends Base {
if ($sites) {
$sites = array_keys($sites);
} else {
- if (! $post_id) {
+ if (!$postId) {
$sites[] = $this->global['site_id'];
}
}
$view->sitesList = $this->sites($sites);
- list($post, $post_id, $this->type) = Event :: trigger(__CLASS__,__FUNCTION__, $post, $post_id, $this->type);
-
$object = $this->object;
$view->$object = $post;
$view->status = ['publish' => 'Publish', 'draft' => 'Draft', 'pending' => 'Pending', 'private' => 'Private', 'scheduled' => 'Scheduled'];
- $view->templates = Cache::getInstance()->cache(APP, 'template-list-' . $theme, function () use ($theme) {
- return \Vvveb\getTemplateList($theme, ['email']);
- }, 604800);
+ $view->templates = Cache::getInstance()->cache(APP, 'template-list-' . $theme, fn () => \Vvveb\getTemplateList($theme, ['email']), 604800);
- $view->themeFonts = Cache::getInstance()->cache(APP, 'fonts-list-' . $theme, function () use ($theme) {
+ $view->themeFonts = Cache::getInstance()->cache(APP, 'fonts-list-' . $theme, function() use ($theme) {
$fonts = \Vvveb\System\Media\Font::themeFonts($theme);
$names = [];
@@ -357,220 +245,53 @@ class Edit extends Base {
$view->type_name = $type_name;
$view->posts_list_url = \Vvveb\url(['module' => $this->list, 'type' => $this->type]);
$view->revisions_url = $revisionsUrl;
- $view->oEmbedProxyUrl = $admin_path . 'index.php?module=editor/editor&action=oEmbedProxy';
+ $view->oEmbedProxyUrl = $admin_path . 'index.php?module=editor/page-builder&action=oEmbedProxy';
}
- private function addCategory($taxonomy_id, $name) {
- $categories = new CategorySQL();
- $cat = $categories->addCategory([
- 'taxonomy_item' => $this->global + [
- 'taxonomy_id' => $taxonomy_id,
- ],
- 'taxonomy_item_content' => $this->global + ['slug'=> slugify($name), 'name' => $name, 'content' => ''],
- ] + $this->global);
-
- return $category_id = $cat['taxonomy_item'];
- }
-
- function add() {
+ /**
+ * Alias for save().
+ *
+ * @return void
+ */
+ public function add(): void {
$this->save();
}
- function save() {
- $view = view :: getInstance();
- $post_id = $this->request->get[$this->object . '_id'] ?? $this->request->post[$this->object . '_id'] ?? false;
- $this->{$this->object . '_id'} = $post_id;
- $publicPath = \Vvveb\publicUrlPath();
-
+ /**
+ * Saves post/page content from the request via the Edit trait.
+ *
+ * Maps request input to saveEditData() and its result to view output.
+ *
+ * @return void
+ */
+ public function save(): void {
if (isset($this->request->get['type'])) {
- $this->type = $this->request->get['type'];
+ $this->type = $this->request->get['type'];
}
- $validator = new Validator([$this->object]);
- $validatorContent = new Validator([$this->object . '_content']);
-
- if (
- (($errors = $validator->validate($this->request->post)) === true) &&
- (($errors = $validatorContent->validate(current($this->request->post[$this->object . '_content']))) === true)
- ) {
- $posts = model($this->object);
-
- $post = [];
-
- $post = $this->request->post;
-
- foreach ($post[$this->object . '_content'] as &$content) {
- $content['name'] = strip_tags($content['name']);
- $content['content'] = sanitizeHTML($content['content']);
-
- if (isset($content['excerpt'])) {
- $content['excerpt'] = sanitizeHTML($content['excerpt']);
- }
- }
-
- /*
- if (isset($post['updated_at'])) {
- $post['updated_at'] = str_replace(' ', 'T', $post['updated_at']);
- } else {
- $post['updated_at'] = date("Y-m-d\TH:i:s", time());
- }*/
-
- //process tags
- if (isset($post['tag'])) {
- foreach ($post['tag'] as $listId => $tags) {
- foreach ($tags as $tagId => $tag) {
- //existing tag add to post taxonomy_item list
- if (is_numeric($tagId)) {
- //$post['taxonomy_item_id'][] = $tagId;
- } else {
- //add new taxonomy_item
- $tagId = $this->addCategory($listId, $tag);
- }
- $post['taxonomy_item_id'][] = $tagId;
- }
- }
- }
-
- //process fields
- $post_field_value = [];
-
- if (isset($post['field'])) {
- foreach ($post['field'] as $language_id => $fields) {
- foreach ($fields as $field_id => $value) {
- if (is_array($value)) {
- $value = json_encode($value);
- }
-
- $post_field_value[] = ['field_id' => $field_id, 'language_id' => $language_id, 'value' => $value];
- }
- }
- }
-
- $site_id = $this->request->post['site'] ?? []; //[$this->global['site_id']];
-
- $post = $post + $this->global;
- $new = false;
-
- if ($post_id) {
- $editCapability = 'edit_other_posts';
-
- if ($this->object == 'product') {
- $editCapability = 'edit_other_products';
- }
-
- if (Admin::hasCapability($editCapability)) {
- //unset($data['admin_id']);
- } else {
- //$data['admin_id'] = $this->global['admin_id'];
- $view->errors[] = __('Permission denied!');
- return;
- }
-
- $post[$this->object . '_id'] = (int)$post_id;
- $data = [
- $this->object => $post,
- $this->object . '_id' => $post_id,
- $this->object . '_content' => $post[$this->object . '_content'],
- 'taxonomy_item_id' => $post['taxonomy_item_id'] ?? [],
- 'post_field_value' => $post_field_value,
- 'site_id' => $site_id,
- ] + $this->global;
-
- $result = $posts->edit($data);
-
- if ($result >= 0) {
- $this->view->success['get'] = ucfirst($this->type) . ' ' . __('saved') . '!';
-
- $stickyPosts = getSetting('posts', 'sticky') ?? [];
-
- if (isset($post['sticky']) && ! isset($stickyPosts[$post_id])) {
- $stickyPosts[$post_id] = $post_id;
- setSetting('posts', 'sticky', $stickyPosts);
- }
-
- if (isset($stickyPosts[$post_id]) && ! isset($post['sticky'])) {
- unset($stickyPosts[$post_id]);
- setSetting('posts', 'sticky', $stickyPosts);
- }
-
-
-
- if ($this->revisions) {
- $revisions = model($this->object . '_content_revision');
-
- //foreach ($post[$this->object . '_content'] as &$content) {
- foreach ($this->request->post[$this->object . '_content'] as &$content) {
- if (isset($content['has_changes']) && $content['has_changes'] == 1) {
- $revisions->add(['revision' => [
- $this->object . '_id' => $post_id,
- 'language_id' => $content['language_id'],
- 'content' => $content['content'],
- 'created_at' => date("Y-m-d\TH:i:s", time()),
- ] + $this->global]);
- }
- }
- }
- } else {
- $this->view->errors = [$posts->error];
- }
- } else {
- $post['type'] = $this->type;
- //$post['created_at'] = $post['updated_at'];
- if (isset($post['updated_at']) && ! $post['updated_at']) {
- unset($post['updated_at'], $post[$this->object . '_id']);
- }
-
- $add = [
- $this->object => $post,
- $this->object . '_content' => $post[$this->object . '_content'],
- 'taxonomy_item_id' => $post['taxonomy_item_id'] ?? [],
- 'post_field_value' => $post_field_value,
- 'site_id' => $site_id,
- ] + $this->global;
-
- $return = $posts->add($add);
- $id = $return[$this->object] ?? false;
-
- if (! $id) {
- $view->errors = [$posts->error];
- } else {
- $this->request->get[$this->object . '_id'] = $id;
-
- $post_id = $id;
- $new = true;
+ $post_id = $this->request->get[$this->object . '_id'] ?? $this->request->post[$this->object . '_id'] ?? false;
+ $this->{$this->object . '_id'} = $post_id;
- $message = ucfirst($this->type) . ' ' . __('saved') . '!';
- $view->success['get'] = $message;
+ $editCapability = 'edit_other_posts';
- if (isset($post['sticky'])) {
- $stickyPosts = getSetting('posts', 'sticky');
- $stickyPosts[$post_id] = $post_id;
- setSetting('posts', 'sticky', $stickyPosts);
- }
- }
- }
+ if ($this->object == 'product') {
+ $editCapability = 'edit_other_products';
+ }
- if (isset($post[$this->object . '_image'])) {
- $productImage = $this->object . 'Image';
+ $result = $this->saveEditData($this->object, $this->type, $this->request->post, $this->global, Admin::hasCapability($editCapability), $this->revisions);
- foreach ($post[$this->object . '_image'] as &$image) {
- $image = str_replace($publicPath . 'media/','', $image);
- }
+ if (!$result['ok']) {
+ $this->view->errors = $result['errors'];
- $posts->$productImage([$this->object . '_id' => $post_id ? $post_id : 0, $this->object . '_image' => $post[$this->object . '_image']]);
- }
+ return;
+ }
- list($post, $post_id, $this->type) = Event :: trigger(__CLASS__,__FUNCTION__, $post, $post_id, $this->type);
+ $this->view->success['get'] = $result['message'];
- CacheManager::clearObjectCache('component', $this->object);
- CacheManager::clearObjectCache('component', $this->object . 's');
- CacheManager::clearPageCache();
+ if ($result['new']) {
+ $this->request->get[$this->object . '_id'] = $result['post_id'];
- if ($new) {
- $this->redirect(['module'=>$this->module, $this->object . '_id' => $id, 'type' => $this->type, 'success' => $message], [], false);
- }
- } else {
- $view->errors = $errors;
+ $this->redirect(['module' => $this->module, $this->object . '_id' => $result['post_id'], 'type' => $this->type, 'success' => $result['message']], [], false);
}
}
}
diff --git a/admin/controller/content/post.php b/admin/controller/content/post.php
index 4920a78..be6cf24 100755
--- a/admin/controller/content/post.php
+++ b/admin/controller/content/post.php
@@ -23,17 +23,22 @@
namespace Vvveb\Controller\Content;
class Post extends Edit {
- protected $type = 'post';
+ protected string $type = 'post';
- protected $object = 'post';
+ protected string $object = 'post';
- protected $module = 'content/post';
+ protected string $module = 'content/post';
- protected $list = 'content/posts';
+ protected string $list = 'content/posts';
- function save() {
+ /**
+ * Saves the post and reloads the editor index.
+ *
+ * @return void
+ */
+ public function save(): void {
parent::save();
- return $this->index();
+ $this->index();
}
}
diff --git a/admin/controller/content/posts.php b/admin/controller/content/posts.php
index 0d3ab8f..13bb198 100644
--- a/admin/controller/content/posts.php
+++ b/admin/controller/content/posts.php
@@ -120,7 +120,7 @@ class Posts extends Listing {
$url = url(['module' => 'content/post', 'post_id' => $post_id, 'type' => $this->type]);
$success = ucfirst($this->type) . ' ' . __('duplicated') . '!';
- $success .= sprintf(' <a href="%s">%s</a>', $url, __('Edit') . " {$this->type}");
+ $success .= sprintf(' <a href="%s">%s</a>', $url, __('Edit') . ' ' . $this->type);
$this->view->success['get'] = $success;
//$this->session->set('success', $success);
//$this->redirect(['module' => 'content/posts', 'type' => $this->type], [], false);
diff --git a/admin/controller/content/revisions.php b/admin/controller/content/revisions.php
index 0f96c29..009fc2f 100644
--- a/admin/controller/content/revisions.php
+++ b/admin/controller/content/revisions.php
@@ -73,6 +73,11 @@ class Revisions extends Base {
* @return void
*/
public function delete(): void {
+ //deleting a revision changes data and must not be triggered by a link/image
+ if ($this->request->getMethod() !== 'post') {
+ $this->notFound(__('Method not allowed!'), 405);
+ }
+
$options = $this->options + $this->global;
$editCapability = 'edit_other_posts';
@@ -100,6 +105,10 @@ class Revisions extends Base {
* @return void
*/
public function save(): void {
+ if ($this->request->getMethod() !== 'post') {
+ $this->notFound(__('Method not allowed!'), 405);
+ }
+
$content = $this->request->post['content'] ?? false;
if ($content) {
diff --git a/admin/controller/content/sites-trait.php b/admin/controller/content/sites-trait.php
index a8b2815..11d32dd 100644
--- a/admin/controller/content/sites-trait.php
+++ b/admin/controller/content/sites-trait.php
@@ -26,7 +26,14 @@ use Vvveb\Sql\SiteSQL;
use Vvveb\System\User\Admin;
trait SitesTrait {
- function sites($selectedSites = []) {
+ /**
+ * Returns a list of sites, optionally marking selected ones.
+ *
+ * @param array<int> $selectedSites Array of selected site IDs.
+ *
+ * @return array<int, array<string, mixed>> List of site records.
+ */
+ public function sites(array $selectedSites = []): array {
$sites = new SiteSQL();
$options = [];
@@ -34,13 +41,13 @@ trait SitesTrait {
if (Admin::hasCapability('edit_other_sites')) {
//unset($options['site_id']);
} else {
- $options['site_id'] = Admin :: siteAccess();
+ $options['site_id'] = Admin::siteAccess();
}
$results = $sites->getAll(
$options + [
- 'start' => 0,
- 'limit' => 100,
+ 'start' => 0,
+ 'limit' => 100,
]
)['site'] ?? [];
diff --git a/admin/controller/content/tag.php b/admin/controller/content/tag.php
old mode 100755
new mode 100644
index 040e721..be5093f
--- a/admin/controller/content/tag.php
+++ b/admin/controller/content/tag.php
@@ -24,52 +24,64 @@ namespace Vvveb\Controller\Content;
use function Vvveb\__;
use Vvveb\Controller\Base;
-use Vvveb\Sql\categorySQL;
+use Vvveb\Sql\CategorySQL;
use Vvveb\System\Images;
class Tag extends Base {
- protected $type = 'tag';
-
- function save() {
+ protected string $type = 'tag';
+
+ /**
+ * Saves a new or existing tag.
+ *
+ * @return void
+ */
+ public function save(): void {
$taxonomy_item_id = $this->request->get['taxonomy_item_id'] ?? false;
- $taxonomy_id = $this->request->get['taxonomy_id'];
+ $taxonomy_id = $this->request->get['taxonomy_id'] ?? false;
$post_type = $this->request->get['type'] ?? '';
$tag = $this->request->post['tag'] ?? false;
if ($tag) {
- $tags = new categorySQL();
+ $tags = new CategorySQL();
if ($taxonomy_item_id) {
$result = $tags->editCategory(
['taxonomy_item_content' => [$tag + $this->global],
'taxonomy_item_id' => $taxonomy_item_id,
'taxonomy_item' => ['taxonomy_item_id' => $taxonomy_item_id, 'taxonomy_id' => $taxonomy_id] + $tag,
- ]);
+ ]
+ );
} else {
$result = $tags->addCategory(
['taxonomy_item_content' => $tag + $this->global,
'taxonomy_item' => ['taxonomy_id' => $taxonomy_id] + $tag,
'site_id' => $this->global['site_id'],
- ]);
+ ]
+ );
}
if ($result && isset($result['taxonomy_item_content'])) {
$message = __('Tag saved!');
$this->view->success['get'] = $message;
- if (! $taxonomy_item_id) {
- $this->redirect(['module'=> 'content/tag', 'taxonomy_item_id' => $result['taxonomy_item'], 'taxonomy_id' => $taxonomy_id, 'type' => $post_type, 'success' => $message], [], false);
+ if (!$taxonomy_item_id) {
+ $this->redirect(['module' => 'content/tag', 'taxonomy_item_id' => $result['taxonomy_item'], 'taxonomy_id' => $taxonomy_id, 'type' => $post_type, 'success' => $message], [], false);
}
} else {
$this->view->errors[] = __('Error saving!');
}
}
- return $this->index();
+ $this->index();
}
- function index() {
- $tags = new categorySQL();
+ /**
+ * Displays a single tag for editing.
+ *
+ * @return void
+ */
+ public function index(): void {
+ $tags = new CategorySQL();
$taxonomy_item_id = $this->request->get['taxonomy_item_id'] ?? false;
$taxonomy_id = $this->request->get['taxonomy_id'] ?? false;
$post_type = $this->request->get['type'] ?? '';
diff --git a/admin/controller/content/tags.php b/admin/controller/content/tags.php
old mode 100755
new mode 100644
index ffd1b08..4e8df8b
--- a/admin/controller/content/tags.php
+++ b/admin/controller/content/tags.php
@@ -24,30 +24,40 @@ namespace Vvveb\Controller\Content;
use function Vvveb\__;
use Vvveb\Controller\Base;
-use Vvveb\Sql\categorySQL;
+use Vvveb\Sql\CategorySQL;
use Vvveb\System\Images;
class Tags extends Base {
- function delete() {
+ /**
+ * Deletes one or more tags by taxonomy_item_id.
+ *
+ * @return void
+ */
+ public function delete(): void {
$taxonomy_item_id = $this->request->post['taxonomy_item_id'] ?? false;
- $categories = new categorySQL();
+ $categories = new CategorySQL();
if (is_numeric($taxonomy_item_id)) {
$taxonomy_item_id = [$taxonomy_item_id];
}
if ($taxonomy_item_id && $categories->deleteTaxonomyItem(['taxonomy_item_id' => $taxonomy_item_id])) {
- $this->view->success[] = 'Item removed!';
+ $this->view->success[] = __('Item removed!');
} else {
- $this->view->errors[] = __('Error saving!');
+ $this->view->errors[] = __('Error deleting!');
}
- return $this->index();
+ $this->index();
}
- function index() {
+ /**
+ * Lists all tags with multilingual support and edit/delete URLs.
+ *
+ * @return void
+ */
+ public function index(): void {
$view = $this->view;
- $categories = new categorySQL();
+ $categories = new CategorySQL();
$page = $this->request->get['page'] ?? 1;
$type = $this->request->get['type'] ?? '';
diff --git a/admin/controller/content/taxonomies-trait.php b/admin/controller/content/taxonomies-trait.php
index 4ed5991..bdf9efa 100644
--- a/admin/controller/content/taxonomies-trait.php
+++ b/admin/controller/content/taxonomies-trait.php
@@ -22,25 +22,32 @@
namespace Vvveb\Controller\Content;
-use Vvveb\Sql\categorySQL;
-use Vvveb\Sql\taxonomySQL;
+use Vvveb\Sql\CategorySQL;
+use Vvveb\Sql\TaxonomySQL;
trait TaxonomiesTrait {
- protected function taxonomies($post_id = false) {
+ /**
+ * Retrieves all taxonomies and their items for a given post.
+ *
+ * @param int|false $post_id The post ID to load taxonomy assignments for, or false.
+ *
+ * @return array<int, array<string, mixed>> Array of taxonomy records with nested items.
+ */
+ protected function taxonomies(int|false $post_id = false): array {
//get taxonomies for post type
- $taxonomies = new taxonomySQL();
+ $taxonomies = new TaxonomySQL();
$results = $taxonomies->getAll(
- ['post_type' => $this->type]
+ ['post_type' => $this->type]
);
//get taxonomies content
if ($results) {
- $taxonomy_itemSql = new categorySQL();
+ $taxonomy_itemSQL = new CategorySQL();
$options = [
- 'post_type' => $this->type,
- 'start' => 0,
- 'limit' => 1000,
+ 'post_type' => $this->type,
+ 'start' => 0,
+ 'limit' => 1000,
] + $this->global;
if ($post_id) {
@@ -53,7 +60,14 @@ trait TaxonomiesTrait {
//for tags don't retrive taxonomies if no post id provided
if ($taxonomy_item['type'] != 'tags' || $post_id) {
$options = ['taxonomy_id' => $id, 'type' => $taxonomy_item['type']] + $options;
- $taxonomy_item['taxonomy_item'] = $taxonomy_itemSql->getCategories($options);
+ $taxonomies = $taxonomy_itemSQL->getCategories($options);
+ if (isset($taxonomies['categories'])) {
+ foreach ($taxonomies['categories'] as &$taxonomy) {
+ $taxonomy = ['taxonomy_item_id' => $taxonomy['taxonomy_item_id'], 'taxonomy_id' => $taxonomy['taxonomy_id'], 'name' => $taxonomy['name'], 'parent_id' => $taxonomy['name'], 'checked' => $taxonomy['checked'] ?? false, 'slug' => $taxonomy['slug'], 'language_id' => $taxonomy['language_id'], 'item_id' => $taxonomy['item_id'], 'image' => $taxonomy['image']];
+ }
+ }
+
+ $taxonomy_item['taxonomy_item'] = $taxonomies;
}
}
}
diff --git a/admin/controller/content/taxonomy.php b/admin/controller/content/taxonomy.php
index 9dfe2ce..9681730 100755
--- a/admin/controller/content/taxonomy.php
+++ b/admin/controller/content/taxonomy.php
@@ -25,21 +25,22 @@ namespace Vvveb\Controller\Content;
use Vvveb\Controller\Base;
class Taxonomy extends Base {
- function index() {
+ /**
+ * Displays all taxonomy types in the view.
+ *
+ * @return void
+ */
+ public function index(): void {
$view = $this->view;
- $taxonomies = new \Vvveb\Sql\taxonomySQL();
+ $taxonomies = new \Vvveb\Sql\TaxonomySQL();
$limit = 10000;
$options = [
- 'limit' => $limit,
+ 'limit' => $limit,
] + $this->global;
$results = $taxonomies->getAll($options);
- if ($results) {
- foreach ($results as &$category) {
- }
- }
$view->taxonomies = $results;
}
}
diff --git a/admin/controller/crud.php b/admin/controller/crud.php
old mode 100755
new mode 100644
index 6d4368b..29f739d
--- a/admin/controller/crud.php
+++ b/admin/controller/crud.php
@@ -29,24 +29,42 @@ use Vvveb\System\Traits\Crud as CrudTrait;
class Crud extends Base {
use CrudTrait {
CrudTrait::index as get;
+ CrudTrait::save as set;
+ CrudTrait::delete as del;
}
- function index() {
+ /**
+ * Delete data.
+ */
+ public function delete(): void {
+ $result = $this->del();
+ }
+
+ /**
+ * Save data.
+ */
+ public function save(): void {
+ $result = $this->set();
+ }
+
+ /**
+ * Display the CRUD edit/create page with media scan URL and status options.
+ */
+ public function index(): void {
$result = $this->get();
$this->view->{$this->type} = $this->data;
- $this->type_id = $this->type_id ?? $this->type . '_id';
+ $this->type_id = $this->type_id ?: $this->type . '_id';
- if ($this->data_id && (! $this->data || (! isset($this->data[$this->type_id])))) {
- return $this->notFound(sprintf(__('%s not found!'), humanReadable(__($this->type))));
+ if ($this->data_id && (!$this->data || (!isset($this->data[$this->type_id])))) {
+ $this->notFound(sprintf(__('%s not found!'), humanReadable(__($this->type))));
}
-
- $admin_path = \Vvveb\adminPath();
- $controllerPath = $admin_path . 'index.php?module=media/media';
- $this->view->scanUrl = "$controllerPath&action=scan";
- $this->uploadUrl = "$controllerPath&action=upload";
+ $admin_path = \Vvveb\adminPath();
+ $controllerPath = $admin_path . 'index.php?module=media/media';
+ $this->view->scanUrl = "$controllerPath&action=scan";
+ $this->view->uploadUrl = "$controllerPath&action=upload";
$this->view->status = [0 => __('Inactive'), 1 => __('Active')];
}
diff --git a/admin/controller/error403.php b/admin/controller/error403.php
old mode 100755
new mode 100644
index b1a4fca..d980849
--- a/admin/controller/error403.php
+++ b/admin/controller/error403.php
@@ -23,7 +23,10 @@
namespace Vvveb\Controller;
#[\AllowDynamicProperties]
-class Error403 { /*extends Base*/
- function index() {
- }
+class Error403 {
+ // extends Base
+ /**
+ * Handle 403 Forbidden errors.
+ */
+ public function index(): void {}
}
diff --git a/admin/controller/error404.php b/admin/controller/error404.php
index 92aaee0..881c24a 100755
--- a/admin/controller/error404.php
+++ b/admin/controller/error404.php
@@ -23,8 +23,10 @@
namespace Vvveb\Controller;
#[\AllowDynamicProperties]
-class Error404/* extends Base */
-{
- function index() {
- }
+class Error404 {
+ // extends Base
+ /**
+ * Handle 404 Not Found errors.
+ */
+ public function index(): void {}
}
diff --git a/admin/controller/error500.php b/admin/controller/error500.php
index 324b311..caf3a7a 100755
--- a/admin/controller/error500.php
+++ b/admin/controller/error500.php
@@ -23,8 +23,10 @@
namespace Vvveb\Controller;
#[\AllowDynamicProperties]
-class Error500 /*extends Base */
-{
- function index() {
- }
+class Error500 {
+ // extends Base
+ /**
+ * Handle 500 Internal Server errors.
+ */
+ public function index(): void {}
}
diff --git a/admin/controller/field/field-group.php b/admin/controller/field/field-group.php
index 51e5ece..d9ad218 100755
--- a/admin/controller/field/field-group.php
+++ b/admin/controller/field/field-group.php
@@ -26,24 +26,29 @@ use function Vvveb\__;
use Vvveb\Controller\Crud;
use function Vvveb\fieldTypeClass;
use function Vvveb\getFieldTypes;
-use function Vvveb\importHtml;
use function Vvveb\postTypes;
-use Vvveb\Sql\Field_GroupSQL;
+use Vvveb\Sql\Field_groupSQL;
use Vvveb\Sql\FieldSQL;
-use Vvveb\System\Event;
use Vvveb\System\Field as Fields;
use Vvveb\System\Traits\FieldGroup as FieldGroupTrait;
class FieldGroup extends Crud {
use FieldGroupTrait;
- protected $type = 'field_group';
+ protected string $type = 'field_group';
- protected $controller = 'field-group';
+ protected string $controller = 'field-group';
- protected $module = 'field';
+ protected string $module = 'field';
- function setFieldDefault(&$field) {
+ /**
+ * Sets default values for a field based on its type's value configuration.
+ *
+ * @param array<string, mixed> &$field The field array to modify.
+ *
+ * @return void
+ */
+ public function setFieldDefault(array &$field): void {
$fieldClass = fieldTypeClass($field['type']);
if ($fieldClass && $fieldClass::valueType) {
@@ -57,23 +62,12 @@ class FieldGroup extends Crud {
}
}
- function save() {/*
- $field = $this->request->post['field'] ?? [];
- $field_group_id = $this->request->get['field_group_id'] ?? false;
-
- if ($field_group_id) {
- $fieldGroup = new Field_GroupSQL();
- $result = $fieldGroup->addFields(['field_group_id' => $field_group_id, 'field_to_field_group' => $field]);
-
- if ($result && isset($result['field_to_field_group'])) {
- $successMessage = __('Field saved!');
- $this->view->success[] = $successMessage;
- $this->view->errors = [];
- } else {
- $this->view->errors[] = __('Error saving!');
- }
- }*/
-
+ /**
+ * Saves a field group and its fields (new, edited, and deleted).
+ *
+ * @return void
+ */
+ public function save(): void {
$this->request->post[$this->type]['status'] = 1;
$this->redirect = false;
parent::save();
@@ -86,10 +80,10 @@ class FieldGroup extends Crud {
$field_group_id = $this->field_group_id;
$new = [];
unset($field_group['conditionals']);
- //var_dump($field);
+
foreach ($field as $index => &$attr) {
$attr['field_group_id'] = $field_group_id;
- $attr['sort_order'] = $attr['sort_order'] ?? 0;
+ $attr['sort_order'] ??= 0;
if ($index === '#') {
unset($field[$index]);
@@ -97,15 +91,15 @@ class FieldGroup extends Crud {
continue;
}
- $attr['name'] = $attr['name'] ?? $attr['settings']['name'] ?? '(none)';
- $attr['label'] = $attr['label'] ?? $attr['settings']['label'] ?? '(none)';
- $attr['default'] = $attr['label'] ?? $attr['settings']['default'] ?? '';
+ $attr['name'] ??= $attr['settings']['name'] ?? '(none)';
+ $attr['label'] ??= $attr['settings']['label'] ?? '(none)';
+ $attr['default'] ??= $attr['settings']['default'] ?? '';
$attr['type'] = $attr['settings']['type'] ?? 'text';
$attr['field_id'] = $attr['settings']['field_id'] ?? $attr['field_id'] ?? null;
$attr['sort_order'] = $attr['settings']['sort_order'] ?? $attr['sort_order'] ?? 0;
$attr['row'] = $attr['settings']['row'] ?? $attr['row'] ?? 0;
- if (! $attr['name']) {
+ if (!$attr['name']) {
unset($field[$index]);
continue;
@@ -114,12 +108,12 @@ class FieldGroup extends Crud {
$this->setFieldDefault($attr);
foreach (['settings', 'validation', 'presentation', 'conditionals'] as $section) {
- $attr[$section] = $attr[$section] ?? [];
+ $attr[$section] ??= [];
$attr[$section] = array_filter($attr[$section]);
$attr[$section] = json_encode($attr[$section]);
}
- if (! ($attr['field_id'] ?? false) && $attr['name']) {
+ if (!($attr['field_id'] ?? false) && $attr['name']) {
unset($attr['field_id']);
$new[] = $attr;
unset($field[$index]);
@@ -127,29 +121,29 @@ class FieldGroup extends Crud {
}
if ($field_group_id) {
- $fieldGroup = new Field_GroupSQL();
- $fieldSql = new FieldSQL();
+ $fieldGroup = new Field_groupSQL();
+ $fieldSQL = new FieldSQL();
if ($delete) {
- $fieldSql->delete(['field_id' => $delete] + $this->global);
+ $fieldSQL->delete(['field_id' => $delete] + $this->global);
}
if ($field) {
foreach ($field as $index => &$attr) {
- $fieldSql->edit(['field' => $attr, 'field_id' => $attr['field_id']] + $this->global);
+ $fieldSQL->edit(['field' => $attr, 'field_id' => $attr['field_id']] + $this->global);
}
}
if ($new) {
foreach ($new as $index => &$attr) {
- $fieldSql->add(['field' => $attr] + $this->global);
+ $fieldSQL->add(['field' => $attr] + $this->global);
}
}
$result = $fieldGroup->edit(['field_group_id' => $field_group_id, 'field_group' => $field_group]);
if ($result && isset($result['field_group_content'])) {
- if (! $edit) {
+ if (!$edit) {
$this->redirect(['module' => "{$this->module}/{$this->controller}", 'field_group_id' => $field_group_id]);
}
} else {
@@ -160,29 +154,35 @@ class FieldGroup extends Crud {
$this->index();
}
- function fields() {
+ /**
+ * Returns fields as JSON for API consumption.
+ *
+ * @return void
+ */
+ public function fields(): void {
$fields = [];
- if ($country_id) {
- $field = new FieldSQL();
- $options = $this->global;
- $options['status'] = 1;
- unset($options['limit']);
- $fields = $field->getAll($options)['field'] ?? [];
- }
+ $field = new FieldSQL();
+ $options = $this->global;
+ $options['status'] = 1;
+ unset($options['limit']);
+ $fields = $field->getAll($options)['field'] ?? [];
$this->response->setType('json');
$this->response->output($fields);
- //return [];
}
- function index() {
+ /**
+ * Displays a field group with its fields rendered for editing.
+ *
+ * @return void
+ */
+ public function index(): void {
$field_group_id = $this->request->get['field_group_id'] ?? false;
$this->view->field_group_id = $field_group_id;
parent::index();
- //return;
$field_group_id = $this->request->get['field_group_id'] ?? false;
$fields = [];
@@ -198,8 +198,8 @@ class FieldGroup extends Crud {
$input['presentation'] = json_decode($field['presentation'], true);
$input['cols'] = $input['presentation']['cols'] ?? 'col';
$input['settings']['field_id'] = $field['field_id'];
- $input['settings']['name'] = $input['settings']['name'] ?? '(none)';
- $input['settings']['label'] = $input['settings']['label'] ?? '(none)';
+ $input['settings']['name'] ??= '(none)';
+ $input['settings']['label'] ??= '(none)';
$input['settings']['sort_order'] = $field['sort_order'];
$input['settings']['row'] = $field['row'];
$input['row'] = $input['settings']['row'] ?? 0;
diff --git a/admin/controller/field/field-groups.php b/admin/controller/field/field-groups.php
old mode 100644
new mode 100755
index f3bc8cf..30d15e2
--- a/admin/controller/field/field-groups.php
+++ b/admin/controller/field/field-groups.php
@@ -25,13 +25,13 @@ namespace Vvveb\Controller\Field;
use Vvveb\Controller\Listing;
class FieldGroups extends Listing {
- protected $type = 'field_group';
+ protected string $type = 'field_group';
- protected $controller = 'field-group';
+ protected string $controller = 'field-group';
- protected $listController = 'field-group';
+ protected string $listController = 'field-group';
- protected $list = 'field_group';
+ protected string $list = 'field_group';
- protected $module = 'field';
+ protected string $module = 'field';
}
diff --git a/admin/controller/index.php b/admin/controller/index.php
index c9c0e82..5fbcb39 100755
--- a/admin/controller/index.php
+++ b/admin/controller/index.php
@@ -25,10 +25,9 @@ namespace Vvveb\Controller;
use Vvveb\Sql\StatSQL;
class Index extends Base {
- function index() {
- }
+ public function index(): void {}
- function stats() {
+ public function stats(): void {
$options = [];
$stats = new StatSQL();
@@ -83,7 +82,12 @@ class Index extends Base {
$this->response->output($output);
}
- function heartbeat() {
- die('ok');
+ /**
+ * Simple heartbeat endpoint to verify session is alive.
+ *
+ * @return never
+ */
+ public function heartbeat(): never {
+ exit('ok');
}
}
diff --git a/admin/controller/listing.php b/admin/controller/listing.php
index 673b6ca..670a0be 100755
--- a/admin/controller/listing.php
+++ b/admin/controller/listing.php
@@ -28,28 +28,42 @@ use Vvveb\System\Traits\Listing as ListingTrait;
class Listing extends Base {
use ListingTrait {
ListingTrait::index as get;
+ ListingTrait::delete as del;
}
- function index() {
+ /**
+ * Delete data.
+ */
+ public function delete(): void {
+ $this->del();
+ }
+
+ /**
+ * Display the listing page with row URLs and filter data.
+ */
+ public function index(): void {
$results = $this->get();
$type = $this->type;
if (isset($results[$type])) {
- $controller = $this->controller ?? $type;
- $listController = $this->listController ?? $type;
- $type_id = $this->type_id ?? "{$type}_id";
- $data_id = $this->data_id ?? "{$type}_id";
- $list = $this->list ?? $type;
+ $controller = $this->controller ?: $type;
+ $listController = $this->listController ?: $type;
+ $type_id = $this->type_id ?: "{$type}_id";
+ $data_id = $this->data_id ?: "{$type}_id";
+ $list = $this->list ?: $type;
$module = $this->module;
foreach ($results[$type] as $id => &$row) {
- $params = ['module' => "$module/$controller", $type_id => $row[$type_id]];
- $paramsList = ['module' => "$module/$listController", $type_id => $row[$type_id]];
+ $rowId = $row[$type_id] ?? null;
+ $params = ['module' => "$module/$controller", $type_id => $rowId];
+ $paramsList = ['module' => "$module/$listController", $type_id => $rowId];
$row['url'] = \Vvveb\url($params);
$row['edit-url'] = \Vvveb\url($params);
- $row['delete-url'] = \Vvveb\url($paramsList + ['action' => 'delete', $type_id . '[]' => $row[$type_id]]);
+ $row['delete-url'] = \Vvveb\url($paramsList + ['action' => 'delete', $type_id . '[]' => $rowId]);
}
+
+ unset($row);
}
$this->view->{$this->list} = $results[$this->type] ?? [];
diff --git a/admin/controller/localization/countries.php b/admin/controller/localization/countries.php
old mode 100755
new mode 100644
index e953ed7..25f5946
--- a/admin/controller/localization/countries.php
+++ b/admin/controller/localization/countries.php
@@ -23,26 +23,56 @@
namespace Vvveb\Controller\Localization;
use Vvveb\Controller\Listing;
-use Vvveb\Sql\countrySQL;
+use Vvveb\Sql\CountrySQL;
class Countries extends Listing {
- protected $type = 'country';
+ /**
+ * Entity type identifier for countries.
+ *
+ * @var string
+ */
+ protected string $type = 'country';
- protected $controller = 'country';
+ /**
+ * Singular controller name for detail views.
+ *
+ * @var string
+ */
+ protected string $controller = 'country';
- protected $listController = 'countries';
+ /**
+ * Plural controller name for listing views.
+ *
+ * @var string
+ */
+ protected string $listController = 'countries';
- protected $list = 'country';
+ /**
+ * List key used to identify the data collection.
+ *
+ * @var string
+ */
+ protected string $list = 'country';
- protected $module = 'localization';
+ /**
+ * Module path this controller belongs to.
+ *
+ * @var string
+ */
+ protected string $module = 'localization';
- function countryAutocomplete() {
- $country = new countrySQL();
+ /**
+ * Return matching countries as JSON for autocomplete.
+ *
+ * @return false
+ */
+ public function countryAutocomplete(): false {
+ $country = new CountrySQL();
$options = [
'start' => 0,
'limit' => 10,
- 'search' => trim($this->request->get['text']),
+ 'search' => trim($this->request->get['text'] ?? ''),
] + $this->global;
$results = $country->getAll($options);
@@ -50,11 +80,9 @@ class Countries extends Listing {
$search = [];
foreach ($results['country'] as $country) {
- //$country['image'] = Images::image($country['image'], 'country');
$search[$country['country_id']] = $country['name'];
}
- //echo json_encode($search);
$this->response->setType('json');
$this->response->output($search);
diff --git a/admin/controller/localization/country.php b/admin/controller/localization/country.php
index 0e3624b..eadac32 100755
--- a/admin/controller/localization/country.php
+++ b/admin/controller/localization/country.php
@@ -25,9 +25,24 @@ namespace Vvveb\Controller\Localization;
use Vvveb\Controller\Crud;
class Country extends Crud {
- protected $type = 'country';
+ /**
+ * Entity type identifier for countries.
+ *
+ * @var string
+ */
+ protected string $type = 'country';
- protected $controller = 'country';
+ /**
+ * Singular controller name for detail views.
+ *
+ * @var string
+ */
+ protected string $controller = 'country';
- protected $module = 'localization';
+ /**
+ * Module path this controller belongs to.
+ *
+ * @var string
+ */
+ protected string $module = 'localization';
}
diff --git a/admin/controller/localization/currencies.php b/admin/controller/localization/currencies.php
index 2ed15b1..3a3fea9 100755
--- a/admin/controller/localization/currencies.php
+++ b/admin/controller/localization/currencies.php
@@ -25,11 +25,38 @@ namespace Vvveb\Controller\Localization;
use Vvveb\Controller\Listing;
class Currencies extends Listing {
- protected $type = 'currency';
+ /**
+ * Entity type identifier for currencies.
+ *
+ * @var string
+ */
+ protected string $type = 'currency';
- protected $list = 'currency';
+ /**
+ * Singular controller name for detail views.
+ *
+ * @var string
+ */
+ protected string $controller = 'currency';
- protected $listController = 'currencies';
+ /**
+ * List key used to identify the data collection.
+ *
+ * @var string
+ */
+ protected string $list = 'currency';
- protected $module = 'localization';
+ /**
+ * Plural controller name for listing views.
+ *
+ * @var string
+ */
+ protected string $listController = 'currencies';
+
+ /**
+ * Module path this controller belongs to.
+ *
+ * @var string
+ */
+ protected string $module = 'localization';
}
diff --git a/admin/controller/localization/currency.php b/admin/controller/localization/currency.php
index b889fab..bf2749d 100755
--- a/admin/controller/localization/currency.php
+++ b/admin/controller/localization/currency.php
@@ -25,7 +25,24 @@ namespace Vvveb\Controller\Localization;
use Vvveb\Controller\Crud;
class Currency extends Crud {
- protected $type = 'currency';
+ /**
+ * Entity type identifier for currencies.
+ *
+ * @var string
+ */
+ protected string $type = 'currency';
- protected $module = 'localization';
+ /**
+ * Singular controller name for detail views.
+ *
+ * @var string
+ */
+ protected string $controller = 'currency';
+
+ /**
+ * Module path this controller belongs to.
+ *
+ * @var string
+ */
+ protected string $module = 'localization';
}
diff --git a/admin/controller/localization/language.php b/admin/controller/localization/language.php
old mode 100644
new mode 100755
index 64e35e8..18f9348
--- a/admin/controller/localization/language.php
+++ b/admin/controller/localization/language.php
@@ -31,18 +31,54 @@ use Vvveb\System\CacheManager;
use Vvveb\System\Locale;
class Language extends Crud {
- protected $type = 'language';
-
- protected $module = 'localization';
-
- protected $installUrl = 'https://raw.githubusercontent.com/Vvveb/{code}/master/LC_MESSAGES/';
-
- protected $files = ['vvveb.po'];
-
- protected $listUrl = 'https://www.vvveb.com/page/contribute#language';
-
- function save() {
- //$this->redirect = false;
+ /**
+ * Entity type identifier for languages.
+ *
+ * @var string
+ */
+ protected string $type = 'language';
+
+ /**
+ * Singular controller name for detail views.
+ *
+ * @var string
+ */
+ protected string $controller = 'language';
+
+ /**
+ * Module path this controller belongs to.
+ *
+ * @var string
+ */
+ protected string $module = 'localization';
+
+ /**
+ * URL template for downloading language packs from GitHub.
+ *
+ * @var string
+ */
+ protected string $installUrl = 'https://raw.githubusercontent.com/Vvveb/{code}/master/LC_MESSAGES/';
+
+ /**
+ * List of translation files to download for a language pack.
+ *
+ * @var list<string>
+ */
+ protected array $files = ['vvveb.po'];
+
+ /**
+ * URL to the translations contribution page.
+ *
+ * @var string
+ */
+ protected string $listUrl = 'https://www.vvveb.com/page/contribute#language';
+
+ /**
+ * Save language data, handling default language logic and cache clearing.
+ *
+ * @return void
+ */
+ public function save(): void {
$this->model = model('language');
//check if a default language is set
$default = $this->model->get(['default' => 1]);
@@ -52,17 +88,22 @@ class Language extends Crud {
$this->model->edit(['language' => ['default' => 0]]);
} else {
//if no default language set then set this language as default
- if (! $default) {
+ if (!$default) {
$this->request->post['language']['default'] = 1;
}
}
- parent::save();
CacheManager::clearObjectCache(APP, 'languages');
+ parent::save();
$this->index();
}
- function install() {
+ /**
+ * Download and install a language pack from the remote repository.
+ *
+ * @return void
+ */
+ public function install(): void {
$code = filter('/[-\w]+/', $this->request->post['code']);
$url = str_replace('{code}', $code, $this->installUrl);
$available = false;
@@ -96,18 +137,23 @@ class Language extends Crud {
}
}
- if (! $available) {
+ if (!$available) {
$this->view->errors[] = __('Language pack not available!');
$this->view->info[] = sprintf(__('Check available translations at %s'), '<a href="' . $this->listUrl . '" target="_blank">' . $this->listUrl . '</a>');
}
- return $this->index();
+ $this->index();
}
- function index() {
+ /**
+ * Display the languages management page with installed and available languages.
+ *
+ * @return void
+ */
+ public function index(): void {
parent::index();
$languageList = include DIR_SYSTEM . 'data' . DS . 'languages-list.php';
- $installed = Locale :: installedLanguages();
+ $installed = Locale::installedLanguages();
foreach ($installed as $l) {
$languageList[$l]['installed'] = true;
diff --git a/admin/controller/localization/languages.php b/admin/controller/localization/languages.php
index 5ae787f..c551a36 100755
--- a/admin/controller/localization/languages.php
+++ b/admin/controller/localization/languages.php
@@ -25,9 +25,38 @@ namespace Vvveb\Controller\Localization;
use Vvveb\Controller\Listing;
class Languages extends Listing {
- protected $type = 'language';
+ /**
+ * Entity type identifier for languages.
+ *
+ * @var string
+ */
+ protected string $type = 'language';
- protected $list = 'language';
+ /**
+ * Singular controller name for detail views.
+ *
+ * @var string
+ */
+ protected string $controller = 'language';
- protected $module = 'localization';
+ /**
+ * List key used to identify the data collection.
+ *
+ * @var string
+ */
+ protected string $list = 'language';
+
+ /**
+ * Plural controller name for listing views.
+ *
+ * @var string
+ */
+ protected string $listController = 'languages';
+
+ /**
+ * Module path this controller belongs to.
+ *
+ * @var string
+ */
+ protected string $module = 'localization';
}
diff --git a/admin/controller/localization/region-group.php b/admin/controller/localization/region-group.php
index 8004dd4..0c5da8a 100755
--- a/admin/controller/localization/region-group.php
+++ b/admin/controller/localization/region-group.php
@@ -25,37 +25,73 @@ namespace Vvveb\Controller\Localization;
use function Vvveb\__;
use Vvveb\Controller\Crud;
use Vvveb\Sql\CountrySQL;
-use Vvveb\Sql\Region_GroupSQL;
-use Vvveb\Sql\regionSQL;
+use Vvveb\Sql\Region_groupSQL;
+use Vvveb\Sql\RegionSQL;
+use Vvveb\System\Cart\Tax;
class RegionGroup extends Crud {
- protected $type = 'region_group';
-
- protected $controller = 'region-group';
-
- protected $module = 'localization';
-
- function save() {
+ /**
+ * Entity type identifier for region groups.
+ *
+ * @var string
+ */
+ protected string $type = 'region_group';
+
+ /**
+ * Singular controller name for detail views.
+ *
+ * @var string
+ */
+ protected string $controller = 'region-group';
+
+ /**
+ * Module path this controller belongs to.
+ *
+ * @var string
+ */
+ protected string $module = 'localization';
+
+ /**
+ * Save region group with associated regions.
+ *
+ * @return void
+ */
+ public function save(): void {
$region = $this->request->post['region'] ?? [];
$region_group_id = $this->request->get['region_group_id'] ?? false;
if ($region_group_id) {
- $regionGroup = new Region_GroupSQL();
+ $regionGroup = new Region_groupSQL();
$result = $regionGroup->addRegions(['region_group_id' => $region_group_id, 'region_to_region_group' => $region]);
if ($result && isset($result['region_to_region_group'])) {
- //$successMessage = __('Region saved!');
- //$this->view->success[] = $successMessage;
- $this->view->errors = [];
+ $successMessage = __('Region saved!');
+ $this->view->success[] = $successMessage;
} else {
$this->view->errors[] = __('Error saving!');
}
}
parent::save();
+ Tax::clearRulesCache();
+ }
+
+ /**
+ * Delete region groups and drop the cached region rules.
+ *
+ * @return void
+ */
+ public function delete(): void {
+ parent::delete();
+ Tax::clearRulesCache();
}
- function regions() {
+ /**
+ * Return regions for a given country as JSON.
+ *
+ * @return void
+ */
+ public function regions(): void {
$country_id = $this->request->get['country_id'] ?? false;
$regions = [];
@@ -70,17 +106,21 @@ class RegionGroup extends Crud {
$this->response->setType('json');
$this->response->output($regions);
- //return [];
}
- function index() {
+ /**
+ * Display the region group edit form with associated regions and countries.
+ *
+ * @return void
+ */
+ public function index(): void {
parent::index();
$region_group_id = $this->request->get['region_group_id'] ?? false;
$regions = [];
if ($region_group_id) {
- $regionGroup = new Region_GroupSQL();
+ $regionGroup = new Region_groupSQL();
$regions = $regionGroup->getRegions(['region_group_id' => $region_group_id])['regions'] ?? [];
}
$this->view->regions = $regions;
diff --git a/admin/controller/localization/region-groups.php b/admin/controller/localization/region-groups.php
index 9c5da54..eea1a1e 100755
--- a/admin/controller/localization/region-groups.php
+++ b/admin/controller/localization/region-groups.php
@@ -25,13 +25,38 @@ namespace Vvveb\Controller\Localization;
use Vvveb\Controller\Listing;
class RegionGroups extends Listing {
- protected $type = 'region_group';
-
- protected $controller = 'region-group';
-
- protected $listController = 'region-groups';
-
- protected $list = 'region_group';
-
- protected $module = 'localization';
+ /**
+ * Entity type identifier for region groups.
+ *
+ * @var string
+ */
+ protected string $type = 'region_group';
+
+ /**
+ * Singular controller name for detail views.
+ *
+ * @var string
+ */
+ protected string $controller = 'region-group';
+
+ /**
+ * Plural controller name for listing views.
+ *
+ * @var string
+ */
+ protected string $listController = 'region-groups';
+
+ /**
+ * List key used to identify the data collection.
+ *
+ * @var string
+ */
+ protected string $list = 'region_group';
+
+ /**
+ * Module path this controller belongs to.
+ *
+ * @var string
+ */
+ protected string $module = 'localization';
}
diff --git a/admin/controller/localization/region.php b/admin/controller/localization/region.php
index 7004b5d..45aaf00 100755
--- a/admin/controller/localization/region.php
+++ b/admin/controller/localization/region.php
@@ -27,13 +27,33 @@ use Vvveb\Controller\Crud;
use Vvveb\Sql\CountrySQL;
class Region extends Crud {
- protected $type = 'region';
+ /**
+ * Entity type identifier for regions.
+ *
+ * @var string
+ */
+ protected string $type = 'region';
- protected $controller = 'region';
+ /**
+ * Singular controller name for detail views.
+ *
+ * @var string
+ */
+ protected string $controller = 'region';
- protected $module = 'localization';
+ /**
+ * Module path this controller belongs to.
+ *
+ * @var string
+ */
+ protected string $module = 'localization';
- function index() {
+ /**
+ * Display the region edit form with available countries.
+ *
+ * @return void
+ */
+ public function index(): void {
parent::index();
$countryModel = new CountrySQL();
diff --git a/admin/controller/localization/regions.php b/admin/controller/localization/regions.php
old mode 100644
new mode 100755
index dc202e8..fb79a1b
--- a/admin/controller/localization/regions.php
+++ b/admin/controller/localization/regions.php
@@ -28,19 +28,51 @@ use function Vvveb\humanReadable;
use function Vvveb\model;
class Regions extends Listing {
- protected $type = 'region';
-
- protected $controller = 'region';
-
- protected $listController = 'regions';
-
- protected $list = 'region';
-
- protected $module = 'localization';
-
- private function setStatus($status) {
+ /**
+ * Entity type identifier for regions.
+ *
+ * @var string
+ */
+ protected string $type = 'region';
+
+ /**
+ * Singular controller name for detail views.
+ *
+ * @var string
+ */
+ protected string $controller = 'region';
+
+ /**
+ * Plural controller name for listing views.
+ *
+ * @var string
+ */
+ protected string $listController = 'regions';
+
+ /**
+ * List key used to identify the data collection.
+ *
+ * @var string
+ */
+ protected string $list = 'region';
+
+ /**
+ * Module path this controller belongs to.
+ *
+ * @var string
+ */
+ protected string $module = 'localization';
+
+ /**
+ * Set the status for one or more regions.
+ *
+ * @param int $status The new status value (1 = active, 0 = inactive).
+ *
+ * @return void
+ */
+ private function setStatus(int $status): void {
$type = $this->type;
- $type_id = $this->type_id ?? "{$type}_id";
+ $type_id = $this->type_id ?: "{$type}_id";
if (APP == 'admin') {
$data_id = $this->request->post[$type_id];
@@ -53,12 +85,11 @@ class Regions extends Listing {
$data_id = [$data_id];
}
- if (! isset($this->modelName)) {
+ if (empty($this->modelName)) {
$this->modelName = $type;
}
$model = model($this->modelName);
- //$options = [$type_id => $data_id] + $this->global;
$result = $model->multiEdit([$type => ['status' => $status], $type_id => $data_id]);
$name = ucfirst(__($type));
@@ -69,19 +100,30 @@ class Regions extends Listing {
$this->view->info[] = sprintf(__('No rows affected!'), humanReadable($name));
}
} else {
- $this->view->errors[] = sprintf(__('Error %s!'), humanReadable($name));
+ $this->view->errors[] = sprintf(__('Error changing %s status!'), humanReadable($name));
}
}
unset($this->request->get[$type_id]);
- return $this->index();
+ $this->index();
}
- function enable() {
+
+ /**
+ * Enable regions by setting status to active.
+ *
+ * @return void
+ */
+ public function enable(): void {
$this->setStatus(1);
}
- function disable() {
+ /**
+ * Disable regions by setting status to inactive.
+ *
+ * @return void
+ */
+ public function disable(): void {
$this->setStatus(0);
}
}
diff --git a/admin/controller/localization/translations.php b/admin/controller/localization/translations.php
old mode 100755
new mode 100644
index b378c14..4eaa5d8
--- a/admin/controller/localization/translations.php
+++ b/admin/controller/localization/translations.php
@@ -29,14 +29,20 @@ use function Vvveb\url;
require_once DIR_SYSTEM . 'functions' . DS . 'php-mo.php';
class Translations extends Base {
- function domains() {
+ /**
+ * Display the list of translation domains for a given language.
+ *
+ * @return void
+ */
+ public function domains(): void {
$lang = $this->request->get['lang'] ?? false;
if ($lang) {
$folder = DIR_ROOT . 'locale' . DS . $lang . DS . 'LC_MESSAGES' . DS;
$files = glob($folder . '*.po');
- $url = ['module' => 'localization/translations', 'action' => 'domain', 'lang' => $lang];
+ $url = ['module' => 'localization/translations', 'action' => 'domain', 'lang' => $lang];
+ $domains = [];
//add user if does not exist yet
$domains['user'] = url($url + ['domain' => 'user']);
@@ -52,7 +58,12 @@ class Translations extends Base {
}
}
- private function compile() {
+ /**
+ * Compile all translation domain PO files into a single MO file.
+ *
+ * @return string Status message indicating compilation result.
+ */
+ private function compile(): string {
//add default translations first to be overriden by all others
$domains = ['vvveb'];
$message = '';
@@ -74,13 +85,13 @@ class Translations extends Base {
foreach ($domains as $domain) {
$poFile = $folder . $domain . '.po';
- if (file_exists($poFile) && ($translations = phpmo_parse_po_file($poFile) ?: []) && is_array($translations)) {
+ if (file_exists($poFile) && ($translations = phpmo_parse_po_file($poFile) ?: [])) {
$view->translations = array_merge($view->translations, $translations);
}
}
//compile
if (phpmo_write_mo_file($view->translations, $folder . 'vvveb-new.mo')) {
- if (rename($folder . 'vvveb-new.mo', $folder . 'vvveb.mo')) {
+ if (rename($folder . 'vvveb-new.mo', $folder . 'vvveb.mo')) {
clearstatcache();
$message .= "\n" . __('Compiled!');
}
@@ -91,7 +102,12 @@ class Translations extends Base {
return $message;
}
- function save() {
+ /**
+ * Save translation edits to PO file and recompile the MO file.
+ *
+ * @return void
+ */
+ public function save(): void {
$view = $this->view;
$translations = $this->request->post['translations'] ?? [];
$this->response->setType('json');
@@ -103,7 +119,7 @@ class Translations extends Base {
$this->domain();
$folder = DIR_ROOT . 'locale' . DS . $view->lang . DS . 'LC_MESSAGES' . DS;
- if (! file_exists($folder)) {
+ if (!file_exists($folder)) {
mkdir($folder, 0777, true);
}
@@ -123,7 +139,12 @@ class Translations extends Base {
$this->response->output($result);
}
- function domain() {
+ /**
+ * Display a translation domain's PO file for editing.
+ *
+ * @return void
+ */
+ public function domain(): void {
$view = $this->view;
$view->lang = $lang = $this->request->get['lang'] ?? false;
$view->domain = $domain = $this->request->get['domain'] ?? false;
@@ -138,7 +159,7 @@ class Translations extends Base {
if (file_exists($poFile)) {
$view->translations = phpmo_parse_po_file($poFile);
- if (! is_writeable($poFile)) {
+ if (!is_writable($poFile)) {
$view->info = [__('Po file not writable, saving will not work!')];
}
} else {
diff --git a/admin/controller/media/media.php b/admin/controller/media/media.php
index 6b04fe6..1009bb3 100755
--- a/admin/controller/media/media.php
+++ b/admin/controller/media/media.php
@@ -25,15 +25,26 @@ namespace Vvveb\Controller\Media;
use function Vvveb\__;
use Vvveb\Controller\Base;
use function Vvveb\sanitizeFileName;
-use Vvveb\Sql\media_ContentSQL;
+use Vvveb\Sql\Media_contentSQL;
use Vvveb\System\Traits\Media as MediaTrait;
+/**
+ * Handles media file management: listing, scanning, uploading, and media content editing.
+ */
class Media extends Base {
use MediaTrait;
- protected $dirMedia = DIR_MEDIA;
+ /**
+ * @var string Base directory for media files.
+ */
+ protected string $dirMedia = DIR_MEDIA;
- function index() {
+ /**
+ * Sets up the media manager view with scan/upload endpoints.
+ *
+ * @return void
+ */
+ public function index(): void {
$adminPath = \Vvveb\adminPath();
$controllerPath = $adminPath . 'index.php?module=media/media';
$this->setMediaEndpoints($controllerPath);
@@ -41,13 +52,18 @@ class Media extends Base {
$this->view->mediaContentUrl = "$controllerPath&action=mediaContent";
}
- function mediaContentSave() {
+ /**
+ * Saves media file content (metadata) to the database.
+ *
+ * @return void
+ */
+ public function mediaContentSave(): void {
$file = sanitizeFileName($this->request->post['file']);
$content = ($this->request->post['media_content'] ?? []);
$result = false;
if ($file && $content) {
- $mediaContent = new media_ContentSQL();
+ $mediaContent = new Media_contentSQL();
$media = $mediaContent->get(['file' => $file] + $this->global);
if ($media) {
@@ -67,11 +83,15 @@ class Media extends Base {
$this->response->output($message);
}
- function mediaContent() {
+ /**
+ * Returns media file content (metadata) as JSON.
+ *
+ * @return void
+ */
+ public function mediaContent(): void {
$file = sanitizeFileName($this->request->get['file']);
- $themeFolder = DIR_MEDIA;
- $mediaContent = new media_ContentSQL();
+ $mediaContent = new Media_contentSQL();
$result = $mediaContent->getContent(['file' => $file] + $this->global);
$this->response->setType('json');
diff --git a/admin/controller/order/coupon.php b/admin/controller/order/coupon.php
index 981157a..8f9a643 100755
--- a/admin/controller/order/coupon.php
+++ b/admin/controller/order/coupon.php
@@ -27,13 +27,18 @@ use Vvveb\Controller\Crud;
use Vvveb\Sql\CouponSQL;
class Coupon extends Crud {
- protected $type = 'coupon';
+ protected string $type = 'coupon';
- protected $controller = 'coupon';
+ protected string $controller = 'coupon';
- protected $module = 'order';
+ protected string $module = 'order';
- function save() {
+ /**
+ * Save the coupon and its associated products and taxonomies.
+ *
+ * @return void
+ */
+ public function save(): void {
parent::save();
$post = &$this->request->post;
@@ -52,10 +57,15 @@ class Coupon extends Crud {
$couponSQL->setTaxonomies(['coupon_taxonomy' => $taxonomy, 'coupon_id' => $coupon_id]);
}
- return $this->index();
+ $this->index();
}
- function index() {
+ /**
+ * Display the coupon edit form with associated products and taxonomies.
+ *
+ * @return void
+ */
+ public function index(): void {
parent::index();
$get = &$this->request->get;
$coupon_id = $get['coupon_id'] ?? false;
diff --git a/admin/controller/order/coupons.php b/admin/controller/order/coupons.php
index 3869ebb..4080284 100755
--- a/admin/controller/order/coupons.php
+++ b/admin/controller/order/coupons.php
@@ -25,13 +25,13 @@ namespace Vvveb\Controller\Order;
use Vvveb\Controller\Listing;
class Coupons extends Listing {
- protected $type = 'coupon';
+ protected string $type = 'coupon';
- protected $controller = 'coupon';
+ protected string $controller = 'coupon';
- protected $listController = 'coupons';
+ protected string $listController = 'coupons';
- protected $list = 'coupon';
+ protected string $list = 'coupon';
- protected $module = 'order';
+ protected string $module = 'order';
}
diff --git a/admin/controller/order/return-order.php b/admin/controller/order/return-order.php
old mode 100644
new mode 100755
index 6207be2..aecca9d
--- a/admin/controller/order/return-order.php
+++ b/admin/controller/order/return-order.php
@@ -23,24 +23,29 @@
namespace Vvveb\Controller\Order;
use Vvveb\Controller\Crud;
-use Vvveb\Sql\Return_ReasonSQL;
-use Vvveb\Sql\Return_ResolutionSQL;
-use Vvveb\Sql\Return_StatusSQL;
+use Vvveb\Sql\Return_reasonSQL;
+use Vvveb\Sql\Return_resolutionSQL;
+use Vvveb\Sql\Return_statusSQL;
//Return is a reserved keyword using ReturnOrder and return-order instead
class ReturnOrder extends Crud {
- protected $type = 'return';
+ protected string $type = 'return';
- protected $controller = 'return-order';
+ protected string $controller = 'return-order';
- protected $module = 'order';
+ protected string $module = 'order';
- function index() {
- parent :: index();
+ /**
+ * Display the return order edit form with resolution, reason, and status data.
+ *
+ * @return void
+ */
+ public function index(): void {
+ parent::index();
- $resolution = new Return_ResolutionSQL();
- $reason = new Return_ReasonSQL();
- $status = new Return_StatusSQL();
+ $resolution = new Return_resolutionSQL();
+ $reason = new Return_reasonSQL();
+ $status = new Return_statusSQL();
$resolutions = $resolution->getAll($this->global)['return_resolution'] ?? [];
$reasons = $reason->getAll($this->global)['return_reason'] ?? [];
diff --git a/admin/controller/order/returns.php b/admin/controller/order/returns.php
index 2b88236..a1ce478 100755
--- a/admin/controller/order/returns.php
+++ b/admin/controller/order/returns.php
@@ -25,15 +25,16 @@ namespace Vvveb\Controller\Order;
use Vvveb\Controller\Listing;
class Returns extends Listing {
- protected $additionalPermissionCheck = ['order/return-order/save'];
+ /** @var list<string> */
+ protected ?array $additionalPermissionCheck = ['order/return-order/save'];
- protected $type = 'return';
+ protected string $type = 'return';
- protected $controller = 'return-order';
+ protected string $controller = 'return-order';
- protected $listController = 'returns';
+ protected string $listController = 'returns';
- protected $list = 'return';
+ protected string $list = 'return';
- protected $module = 'order';
+ protected string $module = 'order';
}
diff --git a/admin/controller/order/voucher.php b/admin/controller/order/voucher.php
index 3729b93..3cb3885 100755
--- a/admin/controller/order/voucher.php
+++ b/admin/controller/order/voucher.php
@@ -25,9 +25,9 @@ namespace Vvveb\Controller\Order;
use Vvveb\Controller\Crud;
class Voucher extends Crud {
- protected $type = 'voucher';
+ protected string $type = 'voucher';
- protected $controller = 'voucher';
+ protected string $controller = 'voucher';
- protected $module = 'order';
+ protected string $module = 'order';
}
diff --git a/admin/controller/order/vouchers.php b/admin/controller/order/vouchers.php
index 33b10d6..b8c8573 100755
--- a/admin/controller/order/vouchers.php
+++ b/admin/controller/order/vouchers.php
@@ -25,13 +25,13 @@ namespace Vvveb\Controller\Order;
use Vvveb\Controller\Listing;
class Vouchers extends Listing {
- protected $type = 'voucher';
+ protected string $type = 'voucher';
- protected $controller = 'voucher';
+ protected string $controller = 'voucher';
- protected $listController = 'vouchers';
+ protected string $listController = 'vouchers';
- protected $list = 'voucher';
+ protected string $list = 'voucher';
- protected $module = 'order';
+ protected string $module = 'order';
}
diff --git a/admin/controller/plugin/market.php b/admin/controller/plugin/market.php
index 5c869ac..50d51be 100755
--- a/admin/controller/plugin/market.php
+++ b/admin/controller/plugin/market.php
@@ -25,37 +25,42 @@ namespace Vvveb\Controller\Plugin;
use function Vvveb\__;
use Vvveb\Controller\Base;
use Vvveb\System\CacheManager;
-use Vvveb\System\Core\View;
use Vvveb\System\Extensions\Plugins;
use Vvveb\System\Validator;
class Market extends Base {
- function install() {
+ /**
+ * Install a plugin from the marketplace by slug.
+ *
+ * @return void
+ */
+ public function install(): void {
$slug = $this->request->post['slug'] ?? false;
try {
if ($slug) {
- $plugin = Plugins :: getMarketList(['slug' => $slug])['plugins'];
+ $plugin = Plugins::getMarketList(['slug' => $slug])['plugins'];
if ($plugin && isset($plugin[0])) {
- $pluginInfo = $plugin[0];
- extract($pluginInfo);
- $url = Plugins :: marketUrl();
- $downloadLink = "$url$download_link";
+ $pluginInfo = $plugin[0];
+ $download_link = $pluginInfo['download_link'] ?? '';
+ $name = $pluginInfo['name'] ?? '';
+ $url = Plugins::marketUrl();
+ $downloadLink = "$url$download_link";
$this->view->log[] = sprintf(__('Installing "%s"'), $name);
$this->view->log[] = sprintf(__('Downloading "%s"'), $downloadLink);
- if ($tempFile = Plugins :: download($downloadLink)) {
+ if ($tempFile = Plugins::download($downloadLink)) {
$this->view->log[] = sprintf(__('Unpacking "%s"'), $tempFile);
- if (Plugins :: install($tempFile, $slug)) {
+ if (Plugins::install($tempFile, $slug)) {
CacheManager::clearObjectCache('vvveb', 'plugins_list_' . $this->global['site_id']);
$pluginName = \Vvveb\humanReadable($slug);
$pluginName = "<b>$pluginName</b>";
- $pluginActivateUrl = \Vvveb\url(['module' => 'plugin/plugins', 'action'=> 'activate', 'plugin' => $slug]);
+ $pluginActivateUrl = \Vvveb\url(['module' => 'plugin/plugins', 'action' => 'activate', 'plugin' => $slug]);
- $successMessage = sprintf(__('Plugin %s was successfully installed!'), $pluginName, $pluginActivateUrl);
+ $successMessage = sprintf(__('Plugin %s was successfully installed!'), $pluginName);
$this->view->log[] = $successMessage;
$successMessage .= "<button class='btn btn-primary btn-sm btn-icon m-2' formaction='$pluginActivateUrl' name='plugin' value='$slug'>" . __('Activate plugin') . '</button>';
@@ -84,28 +89,36 @@ class Market extends Base {
}
}
- function download() {
- $slug = $this->request->get['slug'];
-
- if ($slug) {
- }
+ /**
+ * Download a plugin by slug (placeholder).
+ *
+ * @return void
+ */
+ public function download(): void {
+ $slug = $this->request->get['slug'] ?? '';
}
- function index() {
- $view = View :: getInstance();
+ /**
+ * Display the plugin marketplace with categories and installed status.
+ *
+ * @return void
+ */
+ public function index(): void {
+ $view = $this->view;
$validator = new Validator(['plugins']);
//allow only fields that are in the validator list and remove the rest
- $request = array_filter($validator->filter($this->request->get));
- $plugins = [];
+ $request = array_filter($validator->filter($this->request->get));
+ $plugins = [];
+ $categories = [];
$request['limit'] = $this->view->limit = 8;
try {
- $plugins = Plugins :: getMarketList($request);
- $categories = Plugins :: getMarketCategories(['limit' => 100] + $request, 'categories');
- $installed = Plugins :: getList($this->global['site_id']);
+ $plugins = Plugins::getMarketList($request);
+ $categories = Plugins::getMarketCategories(['limit' => 100] + $request, 'categories');
+ $installed = Plugins::getList($this->global['site_id']);
foreach ($plugins['plugins'] as &$plugin) {
$plugin['installed'] = isset($installed[$plugin['slug']]);
@@ -118,8 +131,7 @@ class Market extends Base {
}
}
- $admin_path = \Vvveb\adminPath();
- $view->installUrl = $admin_path . 'index.php?module=plugin/market&action=install&json';
+ $view->installUrl = \Vvveb\adminPath() . 'index.php?module=plugin/market&action=install&json';
$view->categories = $categories['categories'];
$view->set($request);
$view->set($plugins);
diff --git a/admin/controller/plugin/plugins.php b/admin/controller/plugin/plugins.php
index 338de78..98454ea 100755
--- a/admin/controller/plugin/plugins.php
+++ b/admin/controller/plugin/plugins.php
@@ -25,22 +25,45 @@ namespace Vvveb\Controller\Plugin;
use function Vvveb\__;
use Vvveb\Controller\Base;
use function Vvveb\fileUploadErrMessage;
+use function Vvveb\sanitizeFileName;
use function Vvveb\slugify;
use Vvveb\System\CacheManager;
use function Vvveb\System\Core\exceptionToArray;
use Vvveb\System\Core\FrontController;
-use Vvveb\System\Core\View;
use Vvveb\System\Extensions\Plugins as PluginsList;
use Vvveb\System\User\Admin;
class Plugins extends Base {
- function init() {
+ /**
+ * Initialize plugin from request data.
+ *
+ * @return string|null
+ */
+ public function init(): ?string {
parent::init();
- $this->plugin = $this->request->post['plugin'] ?? null;
+ $plugin = $this->request->post['plugin'] ?? null;
+
+ //plugin slugs are folder names, sanitize to prevent path traversal on file operations
+ if (is_array($plugin)) {
+ $this->plugin = array_map(fn ($p) => sanitizeFileName(basename((string)$p)), $plugin);
+ } elseif ($plugin !== null) {
+ $this->plugin = sanitizeFileName(basename((string)$plugin));
+ } else {
+ $this->plugin = null;
+ }
+
+ $this->view->checkPluginUrl = '';
+
+ return null;
}
- function update() {
+ /**
+ * Update an installed plugin from the marketplace.
+ *
+ * @return void
+ */
+ public function update(): void {
$slug = $this->request->post['plugin'] ?? false;
try {
@@ -48,10 +71,11 @@ class Plugins extends Base {
$plugin = PluginsList :: getMarketList(['slug' => $slug])['plugins'];
if ($plugin && isset($plugin[0])) {
- $pluginInfo = $plugin[0];
- extract($pluginInfo);
- $url = PluginsList :: marketUrl();
- $downloadLink = "$url$download_link";
+ $pluginInfo = $plugin[0];
+ $download_link = $pluginInfo['download_link'] ?? '';
+ $name = $pluginInfo['name'] ?? '';
+ $url = PluginsList :: marketUrl();
+ $downloadLink = "$url$download_link";
$this->view->log[] = sprintf(__('Installing "%s"'), $name);
$this->view->log[] = sprintf(__('Downloading "%s"'), $downloadLink);
@@ -59,7 +83,7 @@ class Plugins extends Base {
if ($tempFile = PluginsList :: download($downloadLink)) {
$this->view->log[] = sprintf(__('Unpacking "%s"'), $tempFile);
- if (! is_writable(DIR_PLUGINS . $slug) && ! @chmod($path, 0750)) {
+ if (!is_writable(DIR_PLUGINS . $slug) && !@chmod(DIR_PLUGINS . $slug, 0750)) {
$this->view->errors[] = sprintf(__('"%s" is not writable'), DIR_PLUGINS . $slug);
}
@@ -67,9 +91,9 @@ class Plugins extends Base {
CacheManager::clearObjectCache('vvveb', 'plugins_list_' . $this->global['site_id']);
$pluginName = \Vvveb\humanReadable($slug);
$pluginName = "<b>$pluginName</b>";
- $pluginActivateUrl = \Vvveb\url(['module' => 'plugin/plugins', 'action'=> 'activate', 'plugin' => $slug]);
+ $pluginActivateUrl = \Vvveb\url(['module' => 'plugin/plugins', 'action' => 'activate', 'plugin' => $slug]);
- $successMessage = sprintf(__('Plugin %s was successfully updated!'), $pluginName, $pluginActivateUrl);
+ $successMessage = sprintf(__('Plugin %s was successfully updated!'), $pluginName);
$this->view->log[] = $successMessage;
$this->view->success[] = $successMessage;
@@ -97,7 +121,12 @@ class Plugins extends Base {
}
}
- function deactivate() {
+ /**
+ * Deactivate the current plugin and clear caches.
+ *
+ * @return void
+ */
+ public function deactivate(): void {
if (PluginsList::deactivate($this->plugin, $this->global['site_id'])) {
$this->view->success[] = sprintf(__('Plugin `%s` deactivated!'), '<b>' . \Vvveb\humanReadable($this->plugin) . '</b>');
CacheManager::clearObjectCache('admin-menu');
@@ -107,10 +136,15 @@ class Plugins extends Base {
$this->view->errors[] = sprintf(__('Error deactivating plugin `%s`!'), '<b>' . \Vvveb\humanReadable($this->plugin) . '</b>');
}
- return $this->index();
+ $this->index();
}
- function checkPluginAndActivate() {
+ /**
+ * Check CSRF and prepare for plugin activation via GET parameter.
+ *
+ * @return void
+ */
+ public function checkPluginAndActivate(): void {
//allow plugin activation through get parameter if csrf is provided
if (($csrf = $this->request->get['csrf'] ?? false) &&
($plugin = $this->request->get['plugin'] ?? null) &&
@@ -119,26 +153,34 @@ class Plugins extends Base {
}
$this->category = $this->request->get['category'] ?? false;
- $this->pluginCheckUrl = \Vvveb\url(['module' => 'plugin/plugins', 'action'=> 'activate', 'plugin' => $this->plugin, 'category' => $this->category, 'csrf' => $this->session->get('csrf')]);
- $this->view->checkPluginUrl = $this->pluginCheckUrl;
+ $this->view->checkPluginUrl = \Vvveb\url(['module' => 'plugin/plugins', 'action' => 'activate', 'plugin' => $this->plugin, 'category' => $this->category, 'csrf' => $this->session->get('csrf')]);
$this->view->info[] = sprintf(__('Activating %s plugin ...'), '<b>' . \Vvveb\humanReadable($this->plugin) . '</b> <span class="spinner-border spinner-border-sm align-middle" role="status" aria-hidden="true"></span>');
- return $this->index();
+ $this->index();
}
- function index() {
- $view = View :: getInstance();
- $view->category = $this->request->get['category'] ?? false;
- $cache = (bool)($this->request->get['cache'] ?? true);
- $view->plugins = PluginsList :: getList($this->global['site_id'], $view->category, $cache);
- $view->categories = PluginsList :: getCategories($this->global['site_id']);
- $view->safemode = ($admin = Admin::current()) && isset($admin['safemode']) && $admin['safemode'];
+ /**
+ * Display the installed plugins management page.
+ *
+ * @return void
+ */
+ public function index(): void {
+ $this->view->category = $this->request->get['category'] ?? false;
+ $cache = (bool)($this->request->get['cache'] ?? true);
+ $this->view->plugins = PluginsList :: getList($this->global['site_id'], $this->view->category, $cache);
+ $this->view->categories = PluginsList :: getCategories($this->global['site_id']);
+ $this->view->safemode = ($admin = Admin::current()) && isset($admin['safemode']) && $admin['safemode'];
}
- function delete() {
+ /**
+ * Delete one or more installed plugins.
+ *
+ * @return void
+ */
+ public function delete(): void {
if ($this->plugin) {
- if (! is_array($this->plugin)) {
- $this->plugin[] = $this->plugin;
+ if (!is_array($this->plugin)) {
+ $this->plugin = [$this->plugin];
}
foreach ($this->plugin as $plugin) {
@@ -154,10 +196,15 @@ class Plugins extends Base {
}
}
- return $this->index();
+ $this->index();
}
- function upload() {
+ /**
+ * Handle plugin file upload and installation.
+ *
+ * @return void
+ */
+ public function upload(): void {
$files = $this->request->files;
$error = false;
@@ -173,26 +220,31 @@ class Plugins extends Base {
} else {
$error = true;
$this->view->errors[] = sprintf(__('Error uploading %s!'), $file['name']);
- $this->view->warning[] = sprintf(fileUploadErrMessage($file['error']));
+ $this->view->warning[] = fileUploadErrMessage($file['error']);
}
- if (! $error) {
+ if (!$error) {
if ($this->pluginSlug) {
$this->pluginName = \Vvveb\humanReadable($this->pluginSlug);
$successMessage = sprintf(__('Plugin %s was successfully installed!'), '<b>' . $this->pluginName . '</b>');
- $successMessage .= '<button type="submit" name="plugin" value="' . $this->pluginSlug . '" class="btn btn-primary btn-sm btn-icon ms-2" onclick="document.getElementById(\'action\').value=\'checkPluginAndActivate\';">' . __('Activate plugin') . '</button>';
+ $successMessage .= '<button type="submit" name="plugin" value="' . $this->pluginSlug . '" class="btn btn-primary btn-sm btn-icon ms-2" onclick="document.getElementById(\'action\').value=\'checkPluginAndActivate\';">' . __('Activate plugin') . '</button>';
$this->view->success[] = $successMessage;
} else {
- $errorMessage = sprintf(__('Failed to install %s plugin!'), $this->pluginName);
- $this->view->error[] = $errorMessage;
+ $errorMessage = sprintf(__('Failed to install %s plugin!'), $file['name']);
+ $this->view->errors[] = $errorMessage;
}
}
}
- return $this->index();
+ $this->index();
}
- function activate() {
+ /**
+ * Activate a plugin, loading it and registering it for the current site.
+ *
+ * @return false Always returns false after process completion.
+ */
+ public function activate(): false {
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
@@ -201,8 +253,8 @@ class Plugins extends Base {
$csrf = $this->request->post['csrf'] ?? $this->request->get['csrf'] ?? false;
$message = '';
- if (! defined('CLI') && $csrf != $this->session->get('csrf')) {
- die('Invalid csrf!');
+ if (!defined('CLI') && $csrf != $this->session->get('csrf')) {
+ exit('Invalid csrf!');
}
$active = false;
@@ -229,8 +281,6 @@ class Plugins extends Base {
$error['minimal'] = true;
$error['title'] = sprintf(__('Error activating plugin `%s`!'), $this->plugin);
FrontController::notFound(false, $error, 500);
-
- die();
}
if ($active) {
@@ -243,7 +293,7 @@ class Plugins extends Base {
}
$this->session->set('success', $success);
- ignore_user_abort(1);
+ ignore_user_abort(true);
clearstatcache(true);
CacheManager::clearObjectCache('admin-menu');
@@ -267,16 +317,16 @@ class Plugins extends Base {
</body>
</html>";
- die($response);
+ exit($response);
}
} else {
$message .= sprintf(__('Error activating plugin `%s`!'), $this->plugin);
-
+
if (!is_writable(DIR_CONFIG . 'plugins.php')) {
- $message . '<br/>' . __('Check config file permissions!');
+ $message .= '<br/>' . __('Check config file permissions!');
}
-
- die($message);
+
+ exit($message);
}
return false;
diff --git a/admin/controller/product/attribute-group.php b/admin/controller/product/attribute-group.php
old mode 100644
new mode 100755
index 250cd14..b3c8469
--- a/admin/controller/product/attribute-group.php
+++ b/admin/controller/product/attribute-group.php
@@ -24,32 +24,37 @@ namespace Vvveb\Controller\Product;
use function Vvveb\__;
use Vvveb\Controller\Crud;
-use Vvveb\Sql\Attribute_GroupSQL;
+use Vvveb\Sql\Attribute_groupSQL;
use Vvveb\Sql\AttributeSQL;
class AttributeGroup extends Crud {
- protected $type = 'attribute_group';
+ protected string $type = 'attribute_group';
- protected $controller = 'attribute-group';
+ protected string $controller = 'attribute-group';
- protected $module = 'product';
+ protected string $module = 'product';
- function save() {
+ /**
+ * Save the attribute group and its associated attributes.
+ *
+ * @return void
+ */
+ public function save(): void {
$this->redirect = false;
parent::save();
- $delete = $this->request->post['delete']['attribute_id'] ?? [];
- $attribute = $this->request->post['attribute'] ?? [];
- $attribute_group = $this->request->post['attribute_group'] ?? [];
- $edit = $this->request->get['attribute_group_id'] ?? false;
- $attribute_group_id = $this->attribute_group_id;
- $new = [];
+ $delete = $this->request->post['delete']['attribute_id'] ?? [];
+ $attribute = $this->request->post['attribute'] ?? [];
+ $attribute_group = $this->request->post['attribute_group'] ?? [];
+ $edit = $this->request->get['attribute_group_id'] ?? false;
+ $attribute_group_id = $this->attribute_group_id;
+ $new = [];
foreach ($attribute as $index => &$attr) {
$attr['attribute_group_id'] = $attribute_group_id;
- $attr['sort_order'] = $attr['sort_order'] ?? 0;
+ $attr['sort_order'] ??= 0;
- if (! $attr['attribute_id'] && $attr['name']) {
+ if (!$attr['attribute_id'] && $attr['name']) {
unset($attr['attribute_id']);
$new[] = $attr;
unset($attribute[$index]);
@@ -57,43 +62,48 @@ class AttributeGroup extends Crud {
}
if ($attribute_group_id) {
- $attributeGroup = new Attribute_GroupSQL();
- $attributeSql = new AttributeSQL();
+ $attributeGroup = new Attribute_groupSQL();
+ $attributeSQL = new AttributeSQL();
if ($delete) {
- $attributeSql->delete(['attribute_id' => $delete] + $this->global);
+ $attributeSQL->delete(['attribute_id' => $delete] + $this->global);
}
if ($attribute) {
foreach ($attribute as $index => &$attr) {
- $attributeSql->edit(['attribute' => $attr, 'attribute_id' => $attr['attribute_id']] + $this->global);
+ $attributeSQL->edit(['attribute' => $attr, 'attribute_id' => $attr['attribute_id']] + $this->global);
}
}
if ($new) {
foreach ($new as $index => &$attr) {
- $attributeSql->add(['attribute' => $attr] + $this->global);
+ $attributeSQL->add(['attribute' => $attr] + $this->global);
}
}
- $result = $attributeGroup->edit(['attribute_group_id' => $attribute_group_id, 'attribute_group' => $attribute_group]);
+ $result = $attributeGroup->edit(['attribute_group_id' => $attribute_group_id, 'attribute_group' => $attribute_group]);
if ($result && isset($result['attribute_group_content'])) {
- if (! $edit) {
+ if (!$edit) {
$this->redirect(['module' => "{$this->module}/{$this->controller}", 'attribute_group_id' => $attribute_group_id]);
}
- $successMessage = __('Saved!');
+ $successMessage = __('Saved!');
$this->view->success['get'] = $successMessage;
} else {
$this->view->errors[] = __('Error saving!');
}
}
- return $this->index();
+ $this->index();
}
- function index() {
+ /**
+ * Display the attribute group edit form with associated attributes.
+ *
+ * @return void
+ */
+ public function index(): void {
parent::index();
$attribute_group_id = $this->request->get['attribute_group_id'] ?? false;
diff --git a/admin/controller/product/attribute-groups.php b/admin/controller/product/attribute-groups.php
index a70f86f..2a87ede 100644
--- a/admin/controller/product/attribute-groups.php
+++ b/admin/controller/product/attribute-groups.php
@@ -25,15 +25,16 @@ namespace Vvveb\Controller\Product;
use Vvveb\Controller\Listing;
class AttributeGroups extends Listing {
- protected $additionalPermissionCheck = ['product/attribute-group/save'];
+ /** @var list<string> */
+ protected ?array $additionalPermissionCheck = ['product/attribute-group/save'];
- protected $type = 'attribute_group';
+ protected string $type = 'attribute_group';
- protected $controller = 'attribute-group';
+ protected string $controller = 'attribute-group';
- protected $listController = 'attribute-groups';
+ protected string $listController = 'attribute-groups';
- protected $list = 'attribute_group';
+ protected string $list = 'attribute_group';
- protected $module = 'product';
+ protected string $module = 'product';
}
diff --git a/admin/controller/product/attribute.php b/admin/controller/product/attribute.php
old mode 100644
new mode 100755
index 7c625b3..a98a04c
--- a/admin/controller/product/attribute.php
+++ b/admin/controller/product/attribute.php
@@ -25,9 +25,9 @@ namespace Vvveb\Controller\Product;
use Vvveb\Controller\Crud;
class Attribute extends Crud {
- protected $type = 'attribute';
+ protected string $type = 'attribute';
- protected $controller = 'attribute';
+ protected string $controller = 'attribute';
- protected $module = 'product';
+ protected string $module = 'product';
}
diff --git a/admin/controller/product/attributes.php b/admin/controller/product/attributes.php
old mode 100755
new mode 100644
index 45b28c7..00c3741
--- a/admin/controller/product/attributes.php
+++ b/admin/controller/product/attributes.php
@@ -25,15 +25,16 @@ namespace Vvveb\Controller\Product;
use Vvveb\Controller\Listing;
class Attributes extends Listing {
- protected $additionalPermissionCheck = ['product/attribute/save'];
+ /** @var list<string> */
+ protected ?array $additionalPermissionCheck = ['product/attribute/save'];
- protected $type = 'attribute';
+ protected string $type = 'attribute';
- protected $controller = 'attribute';
+ protected string $controller = 'attribute';
- protected $listController = 'attributes';
+ protected string $listController = 'attributes';
- protected $list = 'attribute';
+ protected string $list = 'attribute';
- protected $module = 'product';
+ protected string $module = 'product';
}
diff --git a/admin/controller/product/categories.php b/admin/controller/product/categories.php
index 10f2c7e..e6f3f7d 100755
--- a/admin/controller/product/categories.php
+++ b/admin/controller/product/categories.php
@@ -24,5 +24,4 @@ namespace Vvveb\Controller\Product;
use Vvveb\Controller\Content\Categories as ContentCategories;
-class Categories extends ContentCategories {
-}
+class Categories extends ContentCategories {}
diff --git a/admin/controller/product/digital-asset.php b/admin/controller/product/digital-asset.php
index 82b05cc..a9a37e6 100644
--- a/admin/controller/product/digital-asset.php
+++ b/admin/controller/product/digital-asset.php
@@ -22,13 +22,13 @@
namespace Vvveb\Controller\Product;
+use function Vvveb\__;
use Vvveb\Controller\Crud;
+use function Vvveb\model;
+use function Vvveb\sanitizeFileName;
use Vvveb\System\Images;
use Vvveb\System\Traits\Media as MediaTrait;
use Vvveb\System\User\Admin;
-use function Vvveb\__;
-use function Vvveb\model;
-use function Vvveb\sanitizeFileName;
class DigitalAsset extends Crud {
use MediaTrait {
@@ -94,28 +94,25 @@ class DigitalAsset extends Crud {
* vendor's asset. The digital_asset rows (each with the author's admin_id)
* are used to decide which files the current user owns.
*
- * @return array<string, true> Owned file names indexed by name.
+ * @param array<string> $files File names to look up (already sanitized basenames).
+ *
+ * @return array<string, true> Owned file names, a subset of $files.
*/
- private function ownedFiles(): array {
- static $owned = null;
-
- if ($owned !== null) {
- return $owned;
- }
-
+ private function ownedFiles(array $files): array {
$owned = [];
- if (! empty($this->global['admin_id'])) {
+ if (!empty($this->global['admin_id']) && $files) {
$results = model($this->type)->getAll([
'admin_id' => $this->global['admin_id'],
+ 'file' => array_values($files),
'language_id' => $this->global['language_id'] ?? 0,
'start' => 0,
- 'limit' => 99999999,
+ 'limit' => count($files),
]);
- foreach ((array) ($results[$this->type] ?? []) as $asset) {
- if (! empty($asset['file'])) {
- $owned[basename((string) $asset['file'])] = true;
+ foreach ((array)($results[$this->type] ?? []) as $asset) {
+ if (!empty($asset['file'])) {
+ $owned[basename((string)$asset['file'])] = true;
}
}
}
@@ -130,7 +127,7 @@ class DigitalAsset extends Crud {
* to them. Digital assets live at the root of the store, so any name with
* a directory separator (vendor created subdirectories) is rejected.
*
- * @param array<string> $files File names to check.
+ * @param array<string> $files File names to check.
* @param bool $mustExist Whether the names must already belong to the user (rename/delete) or just must not conflict with other users' files (upload).
*
* @return bool True when all the files are allowed.
@@ -141,25 +138,35 @@ class DigitalAsset extends Crud {
return true;
}
- $owned = $this->ownedFiles();
+ $names = [];
foreach ($files as $file) {
- $file = sanitizeFileName((string) $file);
+ $file = sanitizeFileName((string)$file);
- if (! $file || strpbrk($file, '/\\') !== false) {
+ if (!$file || strpbrk($file, '/\\') !== false) {
return false;
}
- $file = basename($file);
- $isMine = isset($owned[$file]);
+ $names[] = basename($file);
+ }
- if ($mustExist && ! $isMine) {
- return false;
+ if ($mustExist) {
+ $owned = $this->ownedFiles($names);
+
+ //every requested file must belong to the current user
+ foreach ($names as $name) {
+ if (!isset($owned[$name])) {
+ return false;
+ }
}
+ } else {
+ //files may only overwrite files owned by the current user
+ $owned = $this->ownedFiles($names);
- //don't allow overwriting files that are not owned by the current user
- if (! $mustExist && ! $isMine && file_exists($this->dirMedia . DS . $file)) {
- return false;
+ foreach ($names as $name) {
+ if (file_exists($this->dirMedia . DS . $name) && !isset($owned[$name])) {
+ return false;
+ }
}
}
@@ -183,7 +190,7 @@ class DigitalAsset extends Crud {
*/
public function upload(): void {
//vendors can only upload assets at the root of the asset store
- if (((string) ($this->request->post['mediaPath'] ?? '') !== '') && ! Admin::hasCapability('edit_other_products')) {
+ if (((string)($this->request->post['mediaPath'] ?? '') !== '') && !Admin::hasCapability('edit_other_products')) {
$this->denyAccess();
return;
@@ -195,12 +202,12 @@ class DigitalAsset extends Crud {
if (is_array($files)) {
$fileNames = $files['name'] ?? [];
- if (! is_array($fileNames)) {
+ if (!is_array($fileNames)) {
$fileNames = [$fileNames];
}
foreach ($fileNames as $name) {
- $name = sanitizeFileName((string) $name);
+ $name = sanitizeFileName((string)$name);
if ($name) {
$names[] = $name;
@@ -208,7 +215,7 @@ class DigitalAsset extends Crud {
}
}
- if (! $this->canManageFiles($names, false)) {
+ if (!$this->canManageFiles($names, false)) {
$this->denyAccess();
return;
@@ -227,7 +234,7 @@ class DigitalAsset extends Crud {
$file = $this->request->post['file'] ?? [];
$files = is_array($file) ? array_values($file) : [$file];
- if (! $this->canManageFiles($files)) {
+ if (!$this->canManageFiles($files)) {
$this->denyAccess();
return;
@@ -242,12 +249,12 @@ class DigitalAsset extends Crud {
* @return void
*/
public function rename(): void {
- $file = (string) ($this->request->post['file'] ?? '');
- $newfile = (string) ($this->request->post['newfile'] ?? '');
- $newname = (string) ($this->request->post['newname'] ?? '');
+ $file = (string)($this->request->post['file'] ?? '');
+ $newfile = (string)($this->request->post['newfile'] ?? '');
+ $newname = (string)($this->request->post['newname'] ?? '');
//the source file must belong to the current user
- if (! $this->canManageFiles([$file])) {
+ if (!$this->canManageFiles([$file])) {
$this->denyAccess();
return;
@@ -256,14 +263,14 @@ class DigitalAsset extends Crud {
//the target must not overwrite a file that belongs to another user
$target = $newname ?: $newfile;
- if ($target && ! Admin::hasCapability('edit_other_products')) {
+ if ($target && !Admin::hasCapability('edit_other_products')) {
$target = basename(sanitizeFileName($target));
- $isMine = isset($this->ownedFiles()[$target]);
+ $isMine = ($this->ownedFiles([$target])[$target] ?? false);
$targetExists = file_exists($this->dirMedia . DS . $target);
- $duplicate = (bool) ($this->request->post['duplicate'] ?? false);
+ $duplicate = (bool)($this->request->post['duplicate'] ?? false);
- if ($targetExists && ! $isMine) {
- if (! $duplicate) {
+ if ($targetExists && !$isMine) {
+ if (!$duplicate) {
$this->denyAccess();
return;
@@ -292,7 +299,7 @@ class DigitalAsset extends Crud {
* @return void
*/
public function newFolder(): void {
- if (! Admin::hasCapability('edit_other_products')) {
+ if (!Admin::hasCapability('edit_other_products')) {
$this->denyAccess();
return;
diff --git a/admin/controller/product/digital-assets.php b/admin/controller/product/digital-assets.php
index e9bc589..1f09716 100644
--- a/admin/controller/product/digital-assets.php
+++ b/admin/controller/product/digital-assets.php
@@ -26,37 +26,46 @@ use Vvveb\Controller\Listing;
use Vvveb\System\User\Admin;
class DigitalAssets extends Listing {
- protected $additionalPermissionCheck = ['product/digital-asset/save'];
+ /** @var list<string> */
+ protected ?array $additionalPermissionCheck = ['product/digital-asset/save'];
- protected $type = 'digital_asset';
+ protected string $type = 'digital_asset';
- protected $controller = 'digital-asset';
+ protected string $controller = 'digital-asset';
- protected $listController = 'digital-assets';
+ protected string $listController = 'digital-assets';
- protected $list = 'digital_asset';
+ protected string $list = 'digital_asset';
- protected $module = 'product';
+ protected string $module = 'product';
- function delete() {
+ /**
+ * Delete digital assets, checking edit capabilities first.
+ *
+ * @return void
+ */
+ public function delete(): void {
$editCapability = 'edit_other_products';
if (Admin::hasCapability($editCapability)) {
$this->adminFilter = false;
- } else {
}
parent::delete();
}
- function index() {
+ /**
+ * Display the digital assets listing, checking view capabilities first.
+ *
+ * @return void
+ */
+ public function index(): void {
$editCapability = 'view_other_products';
if (Admin::hasCapability($editCapability)) {
$this->adminFilter = false;
- } else {
}
- $this->adminFilter = false;
+
parent::index();
}
}
diff --git a/admin/controller/product/manufacturer.php b/admin/controller/product/manufacturer.php
index 7256eb2..4debe24 100755
--- a/admin/controller/product/manufacturer.php
+++ b/admin/controller/product/manufacturer.php
@@ -25,7 +25,7 @@ namespace Vvveb\Controller\Product;
use Vvveb\Controller\Crud;
class Manufacturer extends Crud {
- protected $type = 'manufacturer';
+ protected string $type = 'manufacturer';
- protected $module = 'product';
+ protected string $module = 'product';
}
diff --git a/admin/controller/product/manufacturers.php b/admin/controller/product/manufacturers.php
index 6908da7..7e1eba8 100755
--- a/admin/controller/product/manufacturers.php
+++ b/admin/controller/product/manufacturers.php
@@ -25,9 +25,11 @@ namespace Vvveb\Controller\Product;
use Vvveb\Controller\Listing;
class Manufacturers extends Listing {
- protected $type = 'manufacturer';
+ protected string $type = 'manufacturer';
- protected $list = 'manufacturer';
+ protected string $listController = 'manufacturers';
- protected $module = 'product';
+ protected string $list = 'manufacturer';
+
+ protected string $module = 'product';
}
diff --git a/admin/controller/product/option.php b/admin/controller/product/option.php
old mode 100755
new mode 100644
index c1b4e57..9072c2a
--- a/admin/controller/product/option.php
+++ b/admin/controller/product/option.php
@@ -24,21 +24,26 @@ namespace Vvveb\Controller\Product;
use function Vvveb\__;
use Vvveb\Controller\Crud;
-use Vvveb\Sql\Option_ValueSQL;
+use Vvveb\Sql\Option_valueSQL;
use Vvveb\Sql\OptionSQL;
use Vvveb\System\Images;
class Option extends Crud {
- protected $type = 'option';
+ protected string $type = 'option';
- protected $controller = 'option';
+ protected string $controller = 'option';
- protected $module = 'product';
+ protected string $module = 'product';
- function save() {
+ /**
+ * Save the option and its associated option values.
+ *
+ * @return void
+ */
+ public function save(): void {
$this->redirect = false;
parent::save();
-
+
$delete = $this->request->post['delete']['option_value_id'] ?? [];
$option_value = $this->request->post['option_value'] ?? [];
$option = $this->request->post['option'] ?? [];
@@ -48,9 +53,9 @@ class Option extends Crud {
foreach ($option_value as $index => &$attr) {
$attr['option_id'] = $option_id;
- $attr['sort_order'] = $attr['sort_order'] ?? 0;
+ $attr['sort_order'] ??= 0;
- if (! $attr['option_value_id'] && $attr['name']) {
+ if (!$attr['option_value_id'] && $attr['name']) {
unset($attr['option_value_id']);
$new[] = $attr;
unset($option_value[$index]);
@@ -58,28 +63,31 @@ class Option extends Crud {
}
if ($option_id) {
- $optionSql = new OptionSQL();
- $option_valueSql = new Option_ValueSQL();
+ $optionSQL = new OptionSQL();
+ $option_valueSQL = new Option_valueSQL();
if ($delete) {
- $option_valueSql->delete(['option_value_id' => $delete] + $this->global);
+ $option_valueSQL->delete(['option_value_id' => $delete] + $this->global);
}
if ($option_value) {
foreach ($option_value as $index => &$attr) {
- $option_valueSql->edit(['option_value' => $attr, 'option_value_id' => $attr['option_value_id']] + $this->global);
+ $option_valueSQL->edit(['option_value' => $attr, 'option_value_id' => $attr['option_value_id']] + $this->global);
}
}
if ($new) {
foreach ($new as $index => &$attr) {
- $option_valueSql->add(['option_value' => $attr] + $this->global);
+ $option_valueSQL->add(['option_value' => $attr] + $this->global);
}
}
- $result = $optionSql->edit(['option_id' => $option_id, 'option' => $option]);
+ $result = $optionSQL->edit(['option_id' => $option_id, 'option' => $option]);
if ($result && isset($result['option_content'])) {
+ $successMessage = __('Saved!');
+ $this->view->success[] = $successMessage;
+
if (!$edit) {
$this->redirect(['module' => "{$this->module}/{$this->controller}", 'option_id' => $option_id]);
}
@@ -88,17 +96,22 @@ class Option extends Crud {
}
}
- return $this->index();
+ $this->index();
}
- function index() {
+ /**
+ * Display the option edit form with associated option values.
+ *
+ * @return void
+ */
+ public function index(): void {
parent::index();
$option_id = $this->request->get['option_id'] ?? false;
$option_values = [];
if ($option_id) {
- $option_valueGroup = new Option_ValueSQL();
+ $option_valueGroup = new Option_valueSQL();
$option_values = $option_valueGroup->getAll(['option_id' => $option_id, 'limit' => 1000] + $this->global)['option_value'] ?? [];
foreach ($option_values as &$value) {
@@ -107,19 +120,18 @@ class Option extends Crud {
}
$this->view->type = [
- 'text' => 'Text',
- 'number' => 'Number',
- 'textarea'=> 'Textarea',
- 'email' => 'Email',
- 'select' => 'Select',
- 'radio' => 'Radio',
- 'checkbox'=> 'Checkbox',
- 'select' => 'Select',
- 'image' => 'Image',
- 'date' => 'Date',
- 'time' => 'Time',
- 'datetime'=> 'Date time',
- 'file' => 'File',
+ 'text' => __('Text'),
+ 'number' => __('Number'),
+ 'textarea' => __('Textarea'),
+ 'email' => __('Email'),
+ 'select' => __('Select'),
+ 'radio' => __('Radio'),
+ 'checkbox' => __('Checkbox'),
+ 'image' => __('Image'),
+ 'date' => __('Date'),
+ 'time' => __('Time'),
+ 'datetime' => __('Date time'),
+ 'file' => __('File'),
];
$this->view->option_values = $option_values;
diff --git a/admin/controller/product/options.php b/admin/controller/product/options.php
old mode 100755
new mode 100644
index a06999e..e30f99d
--- a/admin/controller/product/options.php
+++ b/admin/controller/product/options.php
@@ -24,56 +24,62 @@ namespace Vvveb\Controller\Product;
use function Vvveb\__;
use Vvveb\Controller\Listing;
-use Vvveb\Sql\Option_ValueSQL;
+use Vvveb\Sql\Option_valueSQL;
use Vvveb\Sql\OptionSQL;
use function Vvveb\url;
class Options extends Listing {
- protected $additionalPermissionCheck = ['product/option/save'];
+ /** @var list<string> */
+ protected ?array $additionalPermissionCheck = ['product/option/save'];
- protected $type = 'option';
+ protected string $type = 'option';
- protected $controller = 'option';
+ protected string $controller = 'option';
- protected $listController = 'options';
+ protected string $listController = 'options';
- protected $list = 'option';
+ protected string $list = 'option';
- protected $module = 'product';
+ protected string $module = 'product';
- function duplicate() {
+ /**
+ * Duplicate an option and its values.
+ *
+ * @return void
+ */
+ public function duplicate(): void {
$option_id = $this->request->post['option_id'] ?? false;
$option_values = [];
if ($option_id) {
$new_option_id = 1;
- $optionSql = new OptionSQL();
- $option = $optionSql->get(['option_id' => $option_id] + $this->global) ?? [];
+ $optionSQL = new OptionSQL();
+ $option = $optionSQL->get(['option_id' => $option_id] + $this->global) ?? [];
$option['name'] .= ' [' . __('duplicate') . ']';
unset($option['option_id'], $option['language_id']);
- $new_option_id = $optionSql->add(['option' => $option] + $this->global)['option'] ?? null;
+ $new_option_id = $optionSQL->add(['option' => $option] + $this->global)['option'] ?? null;
if ($new_option_id) {
- $option_valueSql = new Option_ValueSQL();
- $option_values = $option_valueSql->getAll(['option_id' => $option_id, 'limit' => 1000] + $this->global)['option_value'] ?? [];
+ $option_valueSQL = new Option_valueSQL();
+ $option_values = $option_valueSQL->getAll(['option_id' => $option_id, 'limit' => 1000] + $this->global)['option_value'] ?? [];
foreach ($option_values as $index => &$attr) {
unset($attr['option_value_id']);
$attr['option_id'] = $new_option_id;
- $option_valueSql->add(['option_value' => $attr] + $this->global);
+ $option_valueSQL->add(['option_value' => $attr] + $this->global);
}
$url = url(['module' => 'product/option', 'option_id' => $new_option_id]);
$success = ucfirst($this->type) . ' ' . __('duplicated') . '!';
- $success .= sprintf(' <a href="%s">%s</a>', $url, __('Edit') . " {$this->type}");
+ $success .= sprintf(' <a href="%s">%s</a>', $url, __('Edit') . ' ' . $this->type);
$this->view->success[] = $success;
} else {
- $this->view->errors[] = sprintf(__('Error duplicating %s!'), $this->type);
+ $this->view->errors[] = sprintf(__('Error duplicating %s!'), $this->type);
}
}
- return $this->index();
+ $this->index();
}
}
diff --git a/admin/controller/product/product-question.php b/admin/controller/product/product-question.php
index 14ea8af..0b1d5f2 100755
--- a/admin/controller/product/product-question.php
+++ b/admin/controller/product/product-question.php
@@ -24,12 +24,12 @@ namespace Vvveb\Controller\Product;
use Vvveb\Controller\Content\Comment;
-class Productquestion extends Comment {
- protected $type = 'product_question';
+class ProductQuestion extends Comment {
+ protected string $type = 'product_question';
- protected $list = 'product_question';
+ protected string $list = 'product_question';
- protected $module = 'product';
+ protected string $module = 'product';
- protected $controller = 'product-question';
+ protected string $controller = 'product-question';
}
diff --git a/admin/controller/product/product-questions.php b/admin/controller/product/product-questions.php
index b15d4d3..2e45d78 100755
--- a/admin/controller/product/product-questions.php
+++ b/admin/controller/product/product-questions.php
@@ -25,13 +25,13 @@ namespace Vvveb\Controller\Product;
use Vvveb\Controller\Content\Comments;
class ProductQuestions extends Comments {
- protected $type = 'product_question';
+ protected string $type = 'product_question';
- protected $list = 'product_question';
+ protected string $list = 'product_question';
- protected $listController = 'product-questions';
+ protected string $listController = 'product-questions';
- protected $module = 'product';
+ protected string $module = 'product';
- protected $controller = 'product-question';
+ protected string $controller = 'product-question';
}
diff --git a/admin/controller/product/product-review.php b/admin/controller/product/product-review.php
index f3d57a1..3823d24 100755
--- a/admin/controller/product/product-review.php
+++ b/admin/controller/product/product-review.php
@@ -25,11 +25,11 @@ namespace Vvveb\Controller\Product;
use Vvveb\Controller\Content\Comment;
class ProductReview extends Comment {
- protected $type = 'product_review';
+ protected string $type = 'product_review';
- protected $list = 'product_review';
+ protected string $list = 'product_review';
- protected $module = 'product';
+ protected string $module = 'product';
- protected $controller = 'product-review';
+ protected string $controller = 'product-review';
}
diff --git a/admin/controller/product/product-reviews.php b/admin/controller/product/product-reviews.php
index 5c7acbf..cb2be25 100755
--- a/admin/controller/product/product-reviews.php
+++ b/admin/controller/product/product-reviews.php
@@ -25,13 +25,13 @@ namespace Vvveb\Controller\Product;
use Vvveb\Controller\Content\Comments;
class ProductReviews extends Comments {
- protected $type = 'product_review';
+ protected string $type = 'product_review';
- protected $list = 'product_review';
+ protected string $list = 'product_review';
- protected $module = 'product';
+ protected string $module = 'product';
- protected $controller = 'product-review';
+ protected string $controller = 'product-review';
- protected $listController = 'product-reviews';
+ protected string $listController = 'product-reviews';
}
diff --git a/admin/controller/product/product.php b/admin/controller/product/product.php
index 5f59070..95e0cdb 100755
--- a/admin/controller/product/product.php
+++ b/admin/controller/product/product.php
@@ -25,45 +25,50 @@ namespace Vvveb\Controller\Product;
use function Vvveb\__;
use Vvveb\Controller\Content\Edit;
use function Vvveb\dashesToCamelCase;
-use Vvveb\Sql\Product_Option_ValueSQL;
-use Vvveb\Sql\Product_OptionSQL;
-use Vvveb\Sql\Product_VariantSQL;
+use Vvveb\Sql\Product_option_valueSQL;
+use Vvveb\Sql\Product_optionSQL;
+use Vvveb\Sql\Product_variantSQL;
use Vvveb\Sql\ProductSQL;
class Product extends Edit {
- protected $type = 'product';
+ protected string $type = 'product';
- protected $object = 'product';
+ protected string $object = 'product';
- protected $module = 'product/product';
+ protected string $module = 'product/product';
- protected $list = 'product/products';
+ protected string $list = 'product/products';
- protected $revisions = true;
+ protected bool $revisions = true;
- function saveVariants() {
+ /**
+ * Save product variants from the request post data.
+ *
+ * @return void
+ */
+ public function saveVariants(): void {
$post = &$this->request->post;
- $post['product_variant'] = $post['product_variant'] ?? [];
+ $post['product_variant'] ??= [];
if ($post['product_variant']) {
$deleteVariant = $this->request->post['delete']['product_variant_id'] ?? [];
- $variantSql = new Product_VariantSQL();
+ $variantSQL = new Product_variantSQL();
- unset($post['product_variant']['#'], $post['product_variant']['0']);
+ unset($post['product_variant']['#'], $post['product_variant']['#product_variant#'], $post['product_variant']['0']);
foreach ($post['product_variant'] as $i => $opt) {
$opt['product_id'] = $this->product_id;
if ($opt['product_variant_id']) {
//existing variant
- $variantSql->edit([
+ $variantSQL->edit([
'product_variant' => $opt,
'product_variant_id' => $opt['product_variant_id'],
] + $this->global);
} else {
// new variant
unset($opt['product_variant_id']);
- $result = $variantSql->add(['product_variant' => $opt] + $this->global);
+ $result = $variantSQL->add(['product_variant' => $opt] + $this->global);
if ($result && $result['product_variant']) {
//set new id to use for variant values
@@ -73,21 +78,26 @@ class Product extends Edit {
}
if ($deleteVariant) {
- $variantSql->delete(['product_variant_id' => $deleteVariant] + $this->global);
+ $variantSQL->delete(['product_variant_id' => $deleteVariant] + $this->global);
}
}
}
- function saveOptions() {
+ /**
+ * Save product options and option values from the request post data.
+ *
+ * @return void
+ */
+ public function saveOptions(): void {
$post = &$this->request->post;
- $post['product_option'] = $post['product_option'] ?? [];
+ $post['product_option'] ??= [];
if ($post['product_option']) {
- $deleteOption = $this->request->post['delete']['product_option_id'] ?? [];
- $deleteOptionValue = $this->request->post['delete']['product_option_value_id'] ?? [];
+ $deleteOption = $this->request->post['delete']['product_option_id'] ?? [];
+ $deleteOptionValue = $this->request->post['delete']['product_option_value_id'] ?? [];
- $optionSql = new Product_OptionSQL();
- $productOptionValueSql = new Product_Option_ValueSQL();
+ $optionSQL = new Product_optionSQL();
+ $productoptionvalueSQL = new Product_option_valueSQL();
unset($post['product_option']['#'], $post['product_option']['0']);
@@ -96,14 +106,14 @@ class Product extends Edit {
if ($opt['product_option_id']) {
//existing option
- $optionSql->edit([
- 'product_option' => $opt,
- 'product_option_id' => $opt['product_option_id'],
+ $optionSQL->edit([
+ 'product_option' => $opt,
+ 'product_option_id' => $opt['product_option_id'],
] + $this->global);
} else {
// new option
unset($opt['product_option_id']);
- $result = $optionSql->add(['product_option' => $opt] + $this->global);
+ $result = $optionSQL->add(['product_option' => $opt] + $this->global);
if ($result && $result['product_option']) {
//set new id to use for option values
@@ -112,7 +122,7 @@ class Product extends Edit {
}
if (isset($opt['product_option_value'])) {
- unset($opt['product_option_value']['#']);
+ unset($opt['product_option_value']['#'], $opt['product_option_value']['#product_option_value#']);
foreach ($opt['product_option_value'] as $j => $value) {
//set parent option id
@@ -122,29 +132,33 @@ class Product extends Edit {
if ($value['product_option_value_id']) {
//existing option value
- $productOptionValueSql->edit([
- 'product_option_value' => $value,
- 'product_option_value_id' => $value['product_option_value_id'],
+ $productoptionvalueSQL->edit([
+ 'product_option_value' => $value,
+ 'product_option_value_id' => $value['product_option_value_id'],
] + $this->global);
} else {
unset($value['product_option_value_id']);
- $result = $productOptionValueSql->add(['product_option_value' => $value] + $this->global);
+ $result = $productoptionvalueSQL->add(['product_option_value' => $value] + $this->global);
}
}
}
}
if ($deleteOptionValue) {
- $productOptionValueSql->delete(['product_option_value_id' => $deleteOptionValue] + $this->global);
+ $productoptionvalueSQL->delete(['product_option_value_id' => $deleteOptionValue] + $this->global);
}
if ($deleteOption) {
- $optionSql->delete(['product_option_id' => $deleteOption] + $this->global);
+ $optionSQL->delete(['product_option_id' => $deleteOption] + $this->global);
}
}
}
- function save() {
+ /**
+ * Save the product and related data (options, variants, features).
+ *
+ */
+ public function save(): void {
$post = &$this->request->post;
$post['requires_shipping'] = isset($post['requires_shipping']) ? 1 : 0;
@@ -156,6 +170,17 @@ class Product extends Edit {
$this->product_id = $this->request->get[$this->object . '_id'] ?? $post[$this->object . '_id'] ?? false;
+ if ($this->product_id && isset($post['quantity'])) {
+ try {
+ \Vvveb\System\Notifications::checkLowStock([
+ 'product_id' => $this->product_id,
+ 'name' => $post['name'] ?? '',
+ 'quantity' => (int)$post['quantity'],
+ ]);
+ } catch (\Throwable $e) {
+ }
+ }
+
if ($this->product_id) {
$this->saveOptions();
$this->saveVariants();
@@ -170,20 +195,28 @@ class Product extends Edit {
if ($data) {
$fn = lcfirst(dashesToCamelCase($feature, '_')); //eg: $product->productRelated()
unset($data['#']);
+ unset($data['#' . $feature . '#']);
$product->$fn([$this->object . '_id' => $this->product_id, $feature => array_unique($data, SORT_REGULAR)]);
}
}
}
- return $this->index();
+ $this->index();
}
- private function optionCombinations($arr) {
+ /**
+ * Generate all combinations of option values.
+ *
+ * @param array<string, array<int, string>> $arr Option values keyed by option ID.
+ *
+ * @return array{0: list<string>, 1: list<string>} Names and value keys for each combination.
+ */
+ private function optionCombinations(array $arr): array {
$names = [];
$values = [];
foreach ($arr as $optionId => $set) {
- if (! $names) {
+ if (!$names) {
foreach ($set as $i => $val) {
$names[] = $val;
$values[] = $optionId . ':' . $i;
@@ -210,12 +243,18 @@ class Product extends Edit {
return [$names, $values];
}
- function index() {
+ /**
+ * Display the product edit form with all related data.
+ *
+ * @return void
+ */
+ public function index(): void {
parent::index();
$view = $this->view;
$product = new ProductSQL();
$options = (isset($view->product['product_id']) ? $view->product : $this->global);
+
$data = $product->getData($options);
if (isset($data['option'])) {
@@ -225,6 +264,7 @@ class Product extends Edit {
} else {
$data['option'] = [];
}
+
$optionIds = [];
if (isset($view->product['product_option'])) {
@@ -260,7 +300,7 @@ class Product extends Edit {
$view->combinations = [];
- if ($optionIds && $view->product['product_variant']) {
+ if ($optionIds && isset($view->product['product_variant'])) {
foreach ($view->product['product_variant'] as $opts => &$variant) {
$keys = explode(',', $opts);
$name = '';
@@ -284,7 +324,7 @@ class Product extends Edit {
$view->product['manufacturer_id'] = (($view->product['manufacturer_id'] ?? 0) ? $view->product['manufacturer_id'] : '');
$view->product['vendor_id'] = (($view->product['vendor_id'] ?? 0) ? $view->product['vendor_id'] : '');
- $view->product['status'] = $view->product['status'] ?? 1;
+ $view->product['status'] ??= 1;
$data['subtract_stock'] = [1 => __('Yes'), 0 => __('No')]; //Subtract stock options
$data['status'] = [0 => __('Disabled'), 1 => __('Enabled')];
$view->set($data);
diff --git a/admin/controller/product/products.php b/admin/controller/product/products.php
index 8d921a9..cabe19b 100644
--- a/admin/controller/product/products.php
+++ b/admin/controller/product/products.php
@@ -196,7 +196,7 @@ class Products extends Listing {
$url = url(['module' => 'product/product', 'product_id' => $product_id, 'type' => $this->type]);
$success = ucfirst($this->type) . ' ' . __('duplicated') . '!';
- $success .= sprintf(' <a href="%s">%s</a>', $url, __('Edit') . " {$this->type}");
+ $success .= sprintf(' <a href="%s">%s</a>', $url, __('Edit') . ' ' . $this->type);
$this->view->success[] = $success;
$this->session->set('success', $success);
$this->redirect(['module' => 'product/products'], [], false);
diff --git a/admin/controller/product/revisions.php b/admin/controller/product/revisions.php
index a8e208f..e7ab7d4 100644
--- a/admin/controller/product/revisions.php
+++ b/admin/controller/product/revisions.php
@@ -25,9 +25,10 @@ namespace Vvveb\Controller\Product;
use Vvveb\Controller\Content\Revisions as RevisionsBase;
class Revisions extends RevisionsBase {
- protected $type = 'product';
-
- protected $object = 'product';
+ protected string $type = 'product';
- protected $additionalPermissionCheck = ['product/revisions/save'];
+ protected string $object = 'product';
+
+ /** @var list<string> */
+ protected ?array $additionalPermissionCheck = ['product/revisions/save'];
}
diff --git a/admin/controller/product/vendor.php b/admin/controller/product/vendor.php
index 53bd665..19733d1 100755
--- a/admin/controller/product/vendor.php
+++ b/admin/controller/product/vendor.php
@@ -25,7 +25,7 @@ namespace Vvveb\Controller\Product;
use Vvveb\Controller\Crud;
class Vendor extends Crud {
- protected $type = 'vendor';
+ protected string $type = 'vendor';
- protected $module = 'product';
+ protected string $module = 'product';
}
diff --git a/admin/controller/product/vendors.php b/admin/controller/product/vendors.php
index 6e66b4c..5a54aca 100755
--- a/admin/controller/product/vendors.php
+++ b/admin/controller/product/vendors.php
@@ -25,9 +25,11 @@ namespace Vvveb\Controller\Product;
use Vvveb\Controller\Listing;
class Vendors extends Listing {
- protected $type = 'vendor';
+ protected string $type = 'vendor';
- protected $list = 'vendor';
+ protected string $listController = 'vendors';
- protected $module = 'product';
+ protected string $list = 'vendor';
+
+ protected string $module = 'product';
}
diff --git a/admin/controller/settings/checkout.php b/admin/controller/settings/checkout.php
index da8533b..f3f23ef 100755
--- a/admin/controller/settings/checkout.php
+++ b/admin/controller/settings/checkout.php
@@ -27,11 +27,21 @@ use Vvveb\Controller\Base;
use Vvveb\System\Validator;
class Checkout extends Base {
- function save() {
+ /**
+ * Save checkout settings.
+ *
+ * @return void
+ */
+ public function save(): void {
$this->index();
}
- function index() {
+ /**
+ * Display and validate checkout settings.
+ *
+ * @return void
+ */
+ public function index(): void {
$validator = new Validator(['settings']);
$settings = $this->request->post['settings'] ?? false;
$errors = [];
@@ -39,7 +49,7 @@ class Checkout extends Base {
if ($settings &&
($errors = $validator->validate($settings)) === true) {
$settings = $validator->filter($settings);
- $results = \Vvveb\setMultiSetting('checkout',$settings);
+ $results = \Vvveb\setMultiSetting('checkout', $settings);
$this->view->success[] = __('Settings saved!');
} else {
$this->view->errors = $errors;
diff --git a/admin/controller/settings/discount.php b/admin/controller/settings/discount.php
index ca243f4..08bb13a 100755
--- a/admin/controller/settings/discount.php
+++ b/admin/controller/settings/discount.php
@@ -27,11 +27,21 @@ use Vvveb\Controller\Base;
use Vvveb\System\Validator;
class Discount extends Base {
- function save() {
+ /**
+ * Save discount settings.
+ *
+ * @return void
+ */
+ public function save(): void {
$this->index();
}
- function index() {
+ /**
+ * Display and validate discount settings.
+ *
+ * @return void
+ */
+ public function index(): void {
$validator = new Validator(['settings']);
$settings = $this->request->post['settings'] ?? false;
$errors = [];
@@ -39,7 +49,7 @@ class Discount extends Base {
if ($settings &&
($errors = $validator->validate($settings)) === true) {
$settings = $validator->filter($settings);
- $results = \Vvveb\setMultiSetting('discount',$settings);
+ $results = \Vvveb\setMultiSetting('discount', $settings);
$this->view->success[] = __('Settings saved!');
} else {
$this->view->errors = $errors;
diff --git a/admin/controller/settings/email.php b/admin/controller/settings/email.php
index c53a5b2..398b6c8 100755
--- a/admin/controller/settings/email.php
+++ b/admin/controller/settings/email.php
@@ -27,21 +27,23 @@ use function Vvveb\config;
use Vvveb\Controller\Base;
use function Vvveb\email;
use function Vvveb\setConfig;
-use Vvveb\System\Config;
use Vvveb\System\Event;
-use Vvveb\System\Validator;
class Email extends Base {
- function test() {
+ /**
+ * Send a test email to verify mail configuration.
+ *
+ * @return void
+ */
+ public function test(): void {
$to = $this->request->post['to'] ?? false;
if ($to) {
$message = __('This is a test email to confirm that email is properly configured!');
+ $error = __('Error sending mail!');
try {
- $error = __('Error sending mail!');
-
- if (email($to, __('Test email'), ['html'=> $message, 'txt' => $message])) {
+ if (email($to, __('Test email'), ['html' => $message, 'txt' => $message], [], [], null, SITE_ID, ['debug' => true])) {
$this->view->success[] = sprintf(__('Email sent to %s!'), $to);
} else {
//$this->session->set('errors', $error);
@@ -54,19 +56,29 @@ class Email extends Base {
}
}
- return $this->index();
+ $this->index();
}
- function save() {
- $validator = new Validator(['settings']);
- $settings = $this->request->post['settings'] ?? false;
- $errors = [];
+ /**
+ * Save email settings.
+ *
+ * @return void
+ */
+ public function save(): void {
+ $settings = $this->request->post['settings'] ?? false;
- if ($settings /*&&
- ($errors = $validator->validate($settings)) === true*/) {
- //$settings = $validator->filter($settings);
- //$results = \Vvveb\setMultiSetting('mail',$settings);
- $results = setConfig('mail',$settings);
+ if ($settings) {
+ $settings = self::normalizeSmtpSettings($settings);
+ $errors = self::validateSmtpSettings($settings);
+
+ if ($errors !== []) {
+ $this->view->errors = $errors;
+ $this->index($settings);
+
+ return;
+ }
+
+ $results = setConfig('mail', $settings);
if ($results) {
$this->view->success[] = __('Settings saved!');
@@ -74,19 +86,161 @@ class Email extends Base {
$this->view->errors[] = __('Error saving!');
}
} else {
- $this->view->errors = $errors;
+ $this->view->errors[] = __('No settings received!');
}
$this->index();
}
- function index() {
- $settings = config('mail', []);
+ /**
+ * Display email settings and available mail drivers.
+ *
+ * @param array<string, mixed>|null $settings Pre-filled settings to display
+ * instead of the stored config, used to
+ * redisplay submitted values after a
+ * validation error.
+ *
+ * @return void
+ */
+ public function index(?array $settings = null): void {
+ $settings ??= config('mail', []);
+ $settings = self::splitLegacySmtpScheme($settings);
$drivers = ['mail' => 'Mail', 'smtp' => 'Smtp'];
- list($drivers) = Event::trigger(__CLASS__, __FUNCTION__, $drivers);
+ [$drivers] = Event::trigger(__CLASS__, __FUNCTION__, $drivers);
+
+ $this->view->email = $settings;
+ $this->view->drivers = $drivers;
+ $this->view->smtp_encryption_options = self::encryptionOptions();
+ }
+
+ /**
+ * Encryption modes for the SMTP encryption dropdown.
+ *
+ * @return array<string, string> Value => label pairs.
+ */
+ public static function encryptionOptions(): array {
+ return [
+ '' => __('None'),
+ 'tls' => __('TLS (STARTTLS)'),
+ 'ssl' => __('SSL (SMTPS)'),
+ ];
+ }
+
+ /**
+ * Normalize submitted SMTP settings: strip any URL scheme pasted into
+ * the hostname into the encryption field so only a clean hostname is
+ * stored. A pasted tls:///ssl:// scheme fills an empty dropdown, an
+ * explicit dropdown choice wins otherwise.
+ *
+ * @param array<string, mixed> $settings Submitted mail settings.
+ *
+ * @return array<string, mixed> Normalized mail settings.
+ */
+ public static function normalizeSmtpSettings(array $settings): array {
+ if (!isset($settings['smtp']) || !is_array($settings['smtp'])) {
+ $settings['smtp'] = [];
+ }
+
+ $smtp = $settings['smtp'];
+ $host = trim((string)($smtp['host'] ?? ''));
+ $encryption = strtolower(trim((string)($smtp['encryption'] ?? '')));
+ $scheme = '';
+
+ if (preg_match('#^([a-z][a-z0-9+.-]*)://#i', $host, $m)) {
+ $scheme = strtolower($m[1]);
+ }
+
+ if (in_array($scheme, ['tls', 'ssl'], true)) {
+ if ($encryption !== 'tls' && $encryption !== 'ssl') {
+ $encryption = $scheme;
+ }
+
+ $host = (string)preg_replace('#^[a-z][a-z0-9+.-]*://#i', '', $host);
+ }
+
+ if (!in_array($encryption, ['tls', 'ssl'], true)) {
+ $encryption = '';
+ }
+
+ $smtp['host'] = trim($host, " \t\n\r\0\x0B/");
+ $smtp['encryption'] = $encryption;
+
+ if (isset($smtp['port'])) {
+ $smtp['port'] = trim((string)$smtp['port']);
+ }
+
+ if (isset($smtp['timeout'])) {
+ $smtp['timeout'] = trim((string)$smtp['timeout']);
+ }
+
+ $settings['smtp'] = $smtp;
+
+ return $settings;
+ }
+
+ /**
+ * Validate SMTP settings when the smtp driver is selected.
+ *
+ * @param array<string, mixed> $settings Normalized mail settings.
+ *
+ * @return list<string> Error messages, empty when valid.
+ */
+ public static function validateSmtpSettings(array $settings): array {
+ $errors = [];
+
+ if (($settings['driver'] ?? 'mail') !== 'smtp') {
+ return $errors;
+ }
+
+ $smtp = (isset($settings['smtp']) && is_array($settings['smtp'])) ? $settings['smtp'] : [];
+ $host = (string)($smtp['host'] ?? '');
+
+ if ($host === '') {
+ $errors[] = __('SMTP hostname is required!');
+ } elseif (!preg_match('/^(?=.{1,253}$)([a-z0-9]([a-z0-9.-]*[a-z0-9])?|\[[0-9a-f:.]+\])$/i', $host)) {
+ $errors[] = __('SMTP hostname is invalid! Use a plain hostname such as mail.example.com.');
+ }
+
+ $port = (string)($smtp['port'] ?? '');
+
+ if ($port === '' || !ctype_digit($port) || (int)$port < 1 || (int)$port > 65535) {
+ $errors[] = __('SMTP port must be a number between 1 and 65535!');
+ }
+
+ $timeout = (string)($smtp['timeout'] ?? '');
+
+ if ($timeout !== '' && (!is_numeric($timeout) || (float)$timeout <= 0)) {
+ $errors[] = __('SMTP timeout must be a positive number!');
+ }
+
+ return $errors;
+ }
+
+ /**
+ * Split a legacy scheme-prefixed smtp host (tls:///ssl://) from stored
+ * config into the encryption field for display. Idempotent: stored
+ * settings are only cleaned on the next save.
+ *
+ * @param array<string, mixed> $settings Stored mail settings.
+ *
+ * @return array<string, mixed> Display mail settings.
+ */
+ public static function splitLegacySmtpScheme(array $settings): array {
+ if (!isset($settings['smtp']) || !is_array($settings['smtp'])) {
+ $settings['smtp'] = [];
+ }
+
+ $encryption = (string)($settings['smtp']['encryption'] ?? '');
+ $host = (string)($settings['smtp']['host'] ?? '');
+
+ if ($encryption === '' && preg_match('#^(tls|ssl)://#i', $host, $m)) {
+ $settings['smtp']['encryption'] = strtolower($m[1]);
+ $settings['smtp']['host'] = trim((string)preg_replace('#^[a-z][a-z0-9+.-]*://#i', '', $host), " \t\n\r\0\x0B/");
+ }
+
+ $settings['smtp']['encryption'] ??= '';
- $this->view->email = $settings;
- $this->view->drivers = $drivers;
+ return $settings;
}
}
diff --git a/admin/controller/settings/length-type.php b/admin/controller/settings/length-type.php
index b6b48f7..901eda3 100755
--- a/admin/controller/settings/length-type.php
+++ b/admin/controller/settings/length-type.php
@@ -25,9 +25,12 @@ namespace Vvveb\Controller\Settings;
use Vvveb\Controller\Crud;
class LengthType extends Crud {
- protected $type = 'length_type';
+ /** @var string The entity type identifier */
+ protected string $type = 'length_type';
- protected $controller = 'length-type';
+ /** @var string The controller route slug */
+ protected string $controller = 'length-type';
- protected $module = 'settings';
+ /** @var string The module namespace */
+ protected string $module = 'settings';
}
diff --git a/admin/controller/settings/length-types.php b/admin/controller/settings/length-types.php
index 5844aab..ddea6f6 100755
--- a/admin/controller/settings/length-types.php
+++ b/admin/controller/settings/length-types.php
@@ -25,13 +25,18 @@ namespace Vvveb\Controller\Settings;
use Vvveb\Controller\Listing;
class LengthTypes extends Listing {
- protected $type = 'length_type';
+ /** @var string The entity type identifier */
+ protected string $type = 'length_type';
- protected $controller = 'length-type';
+ /** @var string The single-item controller route slug */
+ protected string $controller = 'length-type';
- protected $listController = 'length-types';
+ /** @var string The list controller route slug */
+ protected string $listController = 'length-types';
- protected $list = 'length_type';
+ /** @var string The list property name on the view */
+ protected string $list = 'length_type';
- protected $module = 'settings';
+ /** @var string The module namespace */
+ protected string $module = 'settings';
}
diff --git a/admin/controller/settings/notifications.php b/admin/controller/settings/notifications.php
index 9d3c092..e51f439 100755
--- a/admin/controller/settings/notifications.php
+++ b/admin/controller/settings/notifications.php
@@ -23,26 +23,157 @@
namespace Vvveb\Controller\Settings;
use function Vvveb\__;
+use function Vvveb\config;
use Vvveb\Controller\Base;
-use Vvveb\System\Validator;
+use function Vvveb\setConfig;
class Notifications extends Base {
- function save() {
- $this->index();
+ /**
+ * Display notification settings (events table + provider config tabs).
+ *
+ * @return void
+ */
+ public function index(): void {
+ // Ensure all default events are registered
+ \Vvveb\System\Notifications::registerDefaults();
+
+ $config = config('notifications', []);
+ $events = $config['events'] ?? [];
+
+ // Build a list of all available provider slugs for the table columns
+ $providerClasses = \Vvveb\System\Notifications::getProviderClasses();
+ $providerSlugs = array_keys($providerClasses);
+
+ // Build named webhooks list for extra columns
+ $namedWebhooks = $config['providers']['webhooks']['webhooks'] ?? [];
+ $webhookNames = array_map(fn ($wh) => $wh['name'] ?? '', $namedWebhooks);
+ $webhookNames = array_filter($webhookNames);
+
+ // Get events grouped by category
+ $groupedEvents = \Vvveb\System\Notifications::getEventsGrouped();
+
+ // Provider settings fields for the config tabs
+ $providerFields = [];
+
+ foreach ($providerClasses as $slug => $class) {
+ $providerFields[$slug] = $class::settingsFields();
+ }
+
+ $this->view->events = $events;
+ $this->view->providerSlugs = $providerSlugs;
+ $this->view->webhookNames = $webhookNames;
+ $this->view->groupedEvents = $groupedEvents;
+ $this->view->providerFields = $providerFields;
+ $this->view->config = $config;
+ $this->view->providers = $config['providers'] ?? [];
+ $this->view->lowStockThreshold = $config['low_stock_threshold'] ?? 5;
+
+ // Category labels for display
+ $this->view->categories = [
+ 'content' => __('Content'),
+ 'users' => __('Users'),
+ 'commerce' => __('Commerce'),
+ 'engagement' => __('Engagement'),
+ 'media' => __('Media'),
+ 'system' => __('System'),
+ 'other' => __('Other'),
+ ];
}
- function index() {
- $validator = new Validator(['settings']);
- $settings = $this->request->post['settings'] ?? false;
- $errors = [];
+ /**
+ * Save notification settings.
+ *
+ * @return void
+ */
+ public function save(): void {
+ if ($this->checkCsrf() === false) {
+ return;
+ }
+
+ $settings = $this->request->post['settings'] ?? null;
+
+ if ($settings && is_array($settings)) {
+ // Sanitize: ensure events is an array
+ if (isset($settings['events']) && is_array($settings['events'])) {
+ foreach ($settings['events'] as &$eventConfig) {
+ $eventConfig['providers'] = array_values((array)($eventConfig['providers'] ?? []));
+ $eventConfig['recipients'] = array_values((array)($eventConfig['recipients'] ?? ['site_admin']));
+ $eventConfig['additional_emails'] = array_filter(array_map('trim', (array)($eventConfig['additional_emails'] ?? [])));
+ $eventConfig['additional_phones'] = array_filter(array_map('trim', (array)($eventConfig['additional_phones'] ?? [])));
+ $eventConfig['additional_webhooks'] ??= [];
+ }
+ unset($eventConfig);
+ }
+
+ // Sanitize: ensure providers has required structure
+ if (isset($settings['providers']) && is_array($settings['providers'])) {
+ foreach ($settings['providers'] as $slug => &$providerConfig) {
+ if (!is_array($providerConfig)) {
+ $providerConfig = ['enabled' => false];
+ }
+ $providerConfig['enabled'] = !empty($providerConfig['enabled']);
+ }
+ unset($providerConfig);
- if ($settings &&
- ($errors = $validator->validate($settings)) === true) {
- $settings = $validator->filter($settings);
- $results = \Vvveb\setMultiSetting($settings);
- $this->view->success[] = __('Settings saved!');
+ // Sanitize named webhook endpoints
+ $definedWebhooks = $settings['providers']['webhooks']['webhooks'] ?? [];
+
+ if (is_array($definedWebhooks)) {
+ $list = [];
+
+ foreach ($definedWebhooks as $webhook) {
+ if (!is_array($webhook) || empty($webhook['url'])) {
+ continue;
+ }
+
+ $method = strtoupper((string)($webhook['method'] ?? 'POST'));
+
+ $list[] = [
+ 'name' => trim((string)($webhook['name'] ?? '')) ?: ('Webhook ' . (count($list) + 1)),
+ 'url' => trim((string)$webhook['url']),
+ 'method' => in_array($method, ['POST', 'PUT', 'PATCH', 'GET'], true) ? $method : 'POST',
+ 'headers' => is_string($webhook['headers'] ?? null) ? trim($webhook['headers']) : '',
+ 'enabled' => !empty($webhook['enabled']),
+ ];
+ }
+
+ $settings['providers']['webhooks']['webhooks'] = $list;
+ }
+
+ // Global cooldown
+ if (isset($settings['providers']['global']['cooldown'])) {
+ $settings['providers']['global']['cooldown'] = max(0, (int)$settings['providers']['global']['cooldown']);
+ }
+ }
+
+ // Per-event cooldowns and webhook selections
+ foreach (($settings['events'] ?? []) as &$eventConfig2) {
+ if (isset($eventConfig2['additional_webhooks']) && is_array($eventConfig2['additional_webhooks'])) {
+ $eventConfig2['additional_webhooks'] = array_values(array_filter(array_map('trim', $eventConfig2['additional_webhooks'])));
+ }
+
+ if (isset($eventConfig2['cooldown']) && $eventConfig2['cooldown'] !== '') {
+ $eventConfig2['cooldown'] = max(0, (int)$eventConfig2['cooldown']);
+ } else {
+ unset($eventConfig2['cooldown']);
+ }
+ }
+ unset($eventConfig2);
+
+ // Handle low stock threshold
+ $settings['low_stock_threshold'] = max(0, (int)($settings['low_stock_threshold'] ?? 5));
+
+ $results = setConfig('notifications', $settings);
+
+ if ($results) {
+ $this->view->success[] = __('Settings saved!');
+ } else {
+ $this->view->errors[] = __('Error saving!');
+ }
} else {
- $this->view->errors = $errors;
+ $this->view->errors[] = __('Invalid settings data!');
}
+
+ $this->index();
}
}
diff --git a/admin/controller/settings/order-status.php b/admin/controller/settings/order-status.php
index 81f69bb..e61133c 100755
--- a/admin/controller/settings/order-status.php
+++ b/admin/controller/settings/order-status.php
@@ -25,9 +25,12 @@ namespace Vvveb\Controller\Settings;
use Vvveb\Controller\Crud;
class OrderStatus extends Crud {
- protected $type = 'order_status';
+ /** @var string The entity type identifier */
+ protected string $type = 'order_status';
- protected $controller = 'order-status';
+ /** @var string The controller route slug */
+ protected string $controller = 'order-status';
- protected $module = 'settings';
+ /** @var string The module namespace */
+ protected string $module = 'settings';
}
diff --git a/admin/controller/settings/order-statuses.php b/admin/controller/settings/order-statuses.php
index 78e6a19..79e3488 100755
--- a/admin/controller/settings/order-statuses.php
+++ b/admin/controller/settings/order-statuses.php
@@ -25,13 +25,18 @@ namespace Vvveb\Controller\Settings;
use Vvveb\Controller\Listing;
class OrderStatuses extends Listing {
- protected $type = 'order_status';
+ /** @var string The entity type identifier */
+ protected string $type = 'order_status';
- protected $controller = 'order-status';
+ /** @var string The single-item controller route slug */
+ protected string $controller = 'order-status';
- protected $listController = 'order-statuses';
+ /** @var string The list controller route slug */
+ protected string $listController = 'order-statuses';
- protected $list = 'order_status';
+ /** @var string The list property name on the view */
+ protected string $list = 'order_status';
- protected $module = 'settings';
+ /** @var string The module namespace */
+ protected string $module = 'settings';
}
diff --git a/admin/controller/settings/payment-status.php b/admin/controller/settings/payment-status.php
old mode 100644
new mode 100755
index 63580d4..532c1f5
--- a/admin/controller/settings/payment-status.php
+++ b/admin/controller/settings/payment-status.php
@@ -25,9 +25,12 @@ namespace Vvveb\Controller\Settings;
use Vvveb\Controller\Crud;
class PaymentStatus extends Crud {
- protected $type = 'payment_status';
+ /** @var string The entity type identifier */
+ protected string $type = 'payment_status';
- protected $controller = 'payment-status';
+ /** @var string The controller route slug */
+ protected string $controller = 'payment-status';
- protected $module = 'settings';
+ /** @var string The module namespace */
+ protected string $module = 'settings';
}
diff --git a/admin/controller/settings/payment-statuses.php b/admin/controller/settings/payment-statuses.php
old mode 100644
new mode 100755
index 130631b..1a08e0c
--- a/admin/controller/settings/payment-statuses.php
+++ b/admin/controller/settings/payment-statuses.php
@@ -25,13 +25,18 @@ namespace Vvveb\Controller\Settings;
use Vvveb\Controller\Listing;
class PaymentStatuses extends Listing {
- protected $type = 'payment_status';
+ /** @var string The entity type identifier */
+ protected string $type = 'payment_status';
- protected $controller = 'payment-status';
+ /** @var string The single-item controller route slug */
+ protected string $controller = 'payment-status';
- protected $listController = 'payment-statuses';
+ /** @var string The list controller route slug */
+ protected string $listController = 'payment-statuses';
- protected $list = 'payment_status';
+ /** @var string The list property name on the view */
+ protected string $list = 'payment_status';
- protected $module = 'settings';
+ /** @var string The module namespace */
+ protected string $module = 'settings';
}
diff --git a/admin/controller/settings/post-type.php b/admin/controller/settings/post-type.php
old mode 100644
new mode 100755
index f8087f6..9995ff1
--- a/admin/controller/settings/post-type.php
+++ b/admin/controller/settings/post-type.php
@@ -28,9 +28,15 @@ use function Vvveb\humanReadable;
use Vvveb\System\Images;
class PostType extends Base {
- protected $type = 'post';
-
- function save() {
+ /** @var string The entity type identifier */
+ protected string $type = 'post';
+
+ /**
+ * Save a post type entry (create or update).
+ *
+ * @return void
+ */
+ public function save(): void {
$postType = $this->request->post['post_type'] ?? false;
$userType = $this->request->get['type'] ?? false;
@@ -47,7 +53,7 @@ class PostType extends Base {
unset($userPostTypes[$userType]);
}
} else {
- return $this->notFound();
+ $this->notFound();
}
} else {
//new
@@ -65,10 +71,15 @@ class PostType extends Base {
}
}
- return $this->index();
+ $this->index();
}
- function index() {
+ /**
+ * Display the post type edit/create form.
+ *
+ * @return void
+ */
+ public function index(): void {
$type = ucfirst($this->type);
$userPostTypes = \Vvveb\getSetting($this->type, 'types', []);
@@ -79,7 +90,7 @@ class PostType extends Base {
$customType = $userPostTypes[$userType];
}
- if ($userType && ! $customType) {
+ if ($userType && !$customType) {
$this->notFound();
}
@@ -93,7 +104,5 @@ class PostType extends Base {
$controllerPath = $admin_path . 'index.php?module=media/media';
$view->scanUrl = "$controllerPath&action=scan";
$view->uploadUrl = "$controllerPath&action=upload";
-
- //$this->view->taxonomy_id = $taxonomy_item_id;
}
}
diff --git a/admin/controller/settings/product-type.php b/admin/controller/settings/product-type.php
index 0338956..162d434 100644
--- a/admin/controller/settings/product-type.php
+++ b/admin/controller/settings/product-type.php
@@ -23,5 +23,6 @@
namespace Vvveb\Controller\Settings;
class ProductType extends PostType {
- protected $type = 'product';
+ /** @var string The entity type identifier */
+ protected string $type = 'product';
}
diff --git a/admin/controller/settings/product-types.php b/admin/controller/settings/product-types.php
old mode 100644
new mode 100755
index 899adc8..89ed947
--- a/admin/controller/settings/product-types.php
+++ b/admin/controller/settings/product-types.php
@@ -23,5 +23,6 @@
namespace Vvveb\Controller\Settings;
class ProductTypes extends PostTypes {
- protected $type = 'product';
+ /** @var string The entity type identifier */
+ protected string $type = 'product';
}
diff --git a/admin/controller/settings/return-reason.php b/admin/controller/settings/return-reason.php
index af66f78..62e4c1c 100755
--- a/admin/controller/settings/return-reason.php
+++ b/admin/controller/settings/return-reason.php
@@ -25,9 +25,12 @@ namespace Vvveb\Controller\Settings;
use Vvveb\Controller\Crud;
class ReturnReason extends Crud {
- protected $type = 'return_reason';
+ /** @var string The entity type identifier */
+ protected string $type = 'return_reason';
- protected $controller = 'return-reason';
+ /** @var string The controller route slug */
+ protected string $controller = 'return-reason';
- protected $module = 'settings';
+ /** @var string The module namespace */
+ protected string $module = 'settings';
}
diff --git a/admin/controller/settings/return-reasons.php b/admin/controller/settings/return-reasons.php
index 6199c83..014575a 100755
--- a/admin/controller/settings/return-reasons.php
+++ b/admin/controller/settings/return-reasons.php
@@ -25,13 +25,18 @@ namespace Vvveb\Controller\Settings;
use Vvveb\Controller\Listing;
class ReturnReasons extends Listing {
- protected $type = 'return_reason';
+ /** @var string The entity type identifier */
+ protected string $type = 'return_reason';
- protected $controller = 'return-reason';
+ /** @var string The single-item controller route slug */
+ protected string $controller = 'return-reason';
- protected $listController = 'return-reasons';
+ /** @var string The list controller route slug */
+ protected string $listController = 'return-reasons';
- protected $list = 'return_reason';
+ /** @var string The list property name on the view */
+ protected string $list = 'return_reason';
- protected $module = 'settings';
+ /** @var string The module namespace */
+ protected string $module = 'settings';
}
diff --git a/admin/controller/settings/return-resolution.php b/admin/controller/settings/return-resolution.php
index 9d2673b..916f61a 100755
--- a/admin/controller/settings/return-resolution.php
+++ b/admin/controller/settings/return-resolution.php
@@ -25,9 +25,12 @@ namespace Vvveb\Controller\Settings;
use Vvveb\Controller\Crud;
class ReturnResolution extends Crud {
- protected $type = 'return_resolution';
+ /** @var string The entity type identifier */
+ protected string $type = 'return_resolution';
- protected $controller = 'return-resolution';
+ /** @var string The controller route slug */
+ protected string $controller = 'return-resolution';
- protected $module = 'settings';
+ /** @var string The module namespace */
+ protected string $module = 'settings';
}
diff --git a/admin/controller/settings/return-resolutions.php b/admin/controller/settings/return-resolutions.php
index 98a9fb5..0390c53 100755
--- a/admin/controller/settings/return-resolutions.php
+++ b/admin/controller/settings/return-resolutions.php
@@ -25,13 +25,18 @@ namespace Vvveb\Controller\Settings;
use Vvveb\Controller\Listing;
class ReturnResolutions extends Listing {
- protected $type = 'return_resolution';
+ /** @var string The entity type identifier */
+ protected string $type = 'return_resolution';
- protected $controller = 'return-resolution';
+ /** @var string The single-item controller route slug */
+ protected string $controller = 'return-resolution';
- protected $listController = 'return-resolutions';
+ /** @var string The list controller route slug */
+ protected string $listController = 'return-resolutions';
- protected $list = 'return_resolution';
+ /** @var string The list property name on the view */
+ protected string $list = 'return_resolution';
- protected $module = 'settings';
+ /** @var string The module namespace */
+ protected string $module = 'settings';
}
diff --git a/admin/controller/settings/return-status.php b/admin/controller/settings/return-status.php
index 2ff706f..7259d35 100755
--- a/admin/controller/settings/return-status.php
+++ b/admin/controller/settings/return-status.php
@@ -25,9 +25,12 @@ namespace Vvveb\Controller\Settings;
use Vvveb\Controller\Crud;
class ReturnStatus extends Crud {
- protected $type = 'return_status';
+ /** @var string The entity type identifier */
+ protected string $type = 'return_status';
- protected $controller = 'return-status';
+ /** @var string The controller route slug */
+ protected string $controller = 'return-status';
- protected $module = 'settings';
+ /** @var string The module namespace */
+ protected string $module = 'settings';
}
diff --git a/admin/controller/settings/return-statuses.php b/admin/controller/settings/return-statuses.php
index fea491e..adc67f5 100755
--- a/admin/controller/settings/return-statuses.php
+++ b/admin/controller/settings/return-statuses.php
@@ -25,13 +25,18 @@ namespace Vvveb\Controller\Settings;
use Vvveb\Controller\Listing;
class ReturnStatuses extends Listing {
- protected $type = 'return_status';
+ /** @var string The entity type identifier */
+ protected string $type = 'return_status';
- protected $controller = 'return-status';
+ /** @var string The single-item controller route slug */
+ protected string $controller = 'return-status';
- protected $listController = 'return-statuses';
+ /** @var string The list controller route slug */
+ protected string $listController = 'return-statuses';
- protected $list = 'return_status';
+ /** @var string The list property name on the view */
+ protected string $list = 'return_status';
- protected $module = 'settings';
+ /** @var string The module namespace */
+ protected string $module = 'settings';
}
diff --git a/admin/controller/settings/settings.php b/admin/controller/settings/settings.php
index cdad11d..dae8605 100755
--- a/admin/controller/settings/settings.php
+++ b/admin/controller/settings/settings.php
@@ -27,7 +27,12 @@ use Vvveb\Controller\Base;
use Vvveb\System\Validator;
class Settings extends Base {
- function save() {
+ /**
+ * Save general settings.
+ *
+ * @return void
+ */
+ public function save(): void {
$validator = new Validator(['settings']);
$settings = $this->request->post['settings'] ?? false;
$errors = [];
@@ -35,7 +40,7 @@ class Settings extends Base {
if ($settings /*&&
($errors = $validator->validate($settings)) === true*/) {
//$settings = $validator->filter($settings);
- $results = \Vvveb\setMultiSetting('settings',$settings);
+ $results = \Vvveb\setMultiSetting('settings', $settings);
if ($results) {
$this->view->success[] = __('Settings saved!');
@@ -49,6 +54,10 @@ class Settings extends Base {
$this->index();
}
- function index() {
- }
+ /**
+ * Display general settings.
+ *
+ * @return void
+ */
+ public function index(): void {}
}
diff --git a/admin/controller/settings/shipping-status.php b/admin/controller/settings/shipping-status.php
old mode 100644
new mode 100755
index 8fdf76d..d0b0fe9
--- a/admin/controller/settings/shipping-status.php
+++ b/admin/controller/settings/shipping-status.php
@@ -25,9 +25,12 @@ namespace Vvveb\Controller\Settings;
use Vvveb\Controller\Crud;
class ShippingStatus extends Crud {
- protected $type = 'shipping_status';
+ /** @var string The entity type identifier */
+ protected string $type = 'shipping_status';
- protected $controller = 'shipping-status';
+ /** @var string The controller route slug */
+ protected string $controller = 'shipping-status';
- protected $module = 'settings';
+ /** @var string The module namespace */
+ protected string $module = 'settings';
}
diff --git a/admin/controller/settings/shipping-statuses.php b/admin/controller/settings/shipping-statuses.php
old mode 100644
new mode 100755
index 51225f2..2c71616
--- a/admin/controller/settings/shipping-statuses.php
+++ b/admin/controller/settings/shipping-statuses.php
@@ -25,13 +25,18 @@ namespace Vvveb\Controller\Settings;
use Vvveb\Controller\Listing;
class ShippingStatuses extends Listing {
- protected $type = 'shipping_status';
+ /** @var string The entity type identifier */
+ protected string $type = 'shipping_status';
- protected $controller = 'shipping-status';
+ /** @var string The single-item controller route slug */
+ protected string $controller = 'shipping-status';
- protected $listController = 'shipping-statuses';
+ /** @var string The list controller route slug */
+ protected string $listController = 'shipping-statuses';
- protected $list = 'shipping_status';
+ /** @var string The list property name on the view */
+ protected string $list = 'shipping_status';
- protected $module = 'settings';
+ /** @var string The module namespace */
+ protected string $module = 'settings';
}
diff --git a/admin/controller/settings/shipping.php b/admin/controller/settings/shipping.php
index ace6f06..091bb91 100755
--- a/admin/controller/settings/shipping.php
+++ b/admin/controller/settings/shipping.php
@@ -27,11 +27,21 @@ use Vvveb\Controller\Base;
use Vvveb\System\Validator;
class Shipping extends Base {
- function save() {
+ /**
+ * Save shipping settings.
+ *
+ * @return void
+ */
+ public function save(): void {
$this->index();
}
- function index() {
+ /**
+ * Display and validate shipping settings.
+ *
+ * @return void
+ */
+ public function index(): void {
$validator = new Validator(['settings']);
$settings = $this->request->post['settings'] ?? false;
$errors = [];
@@ -39,7 +49,7 @@ class Shipping extends Base {
if ($settings &&
($errors = $validator->validate($settings)) === true) {
$settings = $validator->filter($settings);
- $results = \Vvveb\setMultiSetting('shipping',$settings);
+ $results = \Vvveb\setMultiSetting('shipping', $settings);
$this->view->success[] = __('Settings saved!');
} else {
$this->view->errors = $errors;
diff --git a/admin/controller/settings/site.php b/admin/controller/settings/site.php
index bde079b..341f231 100644
--- a/admin/controller/settings/site.php
+++ b/admin/controller/settings/site.php
@@ -27,8 +27,7 @@ use Vvveb\Controller\Base;
use function Vvveb\friendlyDate;
use function Vvveb\getTemplateList;
use function Vvveb\slugify;
-use Vvveb\Sql\CountrySQL;
-use Vvveb\Sql\regionSQL;
+use Vvveb\Sql\RegionSQL;
use Vvveb\Sql\SiteSQL;
use Vvveb\System\Cache;
use Vvveb\System\CacheManager;
@@ -37,71 +36,75 @@ use Vvveb\System\Extensions\Themes;
use Vvveb\System\Images;
use Vvveb\System\Locale;
use Vvveb\System\Media\Image;
+use Vvveb\System\Payment;
+use Vvveb\System\Shipping;
use Vvveb\System\Sites;
+use Vvveb\System\User\Admin;
use Vvveb\System\User\Role;
use Vvveb\System\Validator;
+use function Vvveb\url;
class Site extends Base {
- private function data() {
- $countryModel = new CountrySQL();
- $options = $this->global;
- $options['status'] = 1;
-
- unset($options['limit']);
-
- $country = $countryModel->getAll($options);
- $this->view->countries = $country['country'] ?? [];
-
- //set Regions for default store country
- /*
- $region = new RegionSQL();
- $regions = $countryModel->getAll($options);
-
- $options['country_id'] = $country_id;
- $this->view->regions = $regions['region'] ?? [];
- */
- $this->view->regionsUrl = url(['module' => 'checkout/checkout', 'action' => 'regions']);
- }
-
- function dateFormat() {
+ /**
+ * Output a formatted date for preview.
+ *
+ * @return never
+ */
+ public function dateFormat(): never {
$format = $this->request->get['format'] ?? false;
- die(date($format));
+ exit(date($format));
}
- private function invoiceFormatPreview($format) {
+ /**
+ * Generate an invoice format preview string.
+ *
+ * @param string $format The invoice format pattern
+ *
+ * @return string The formatted preview string
+ */
+ private function invoiceFormatPreview(string $format): string {
$data = ['order_id' => 777, 'customer_order_id' => 'OI888', 'user_id' => 1000, 'site_id' => 1];
return \Vvveb\invoiceFormat($format, $data);
}
- private function orderIdFormatPreview($format) {
- $data = ['order_id' => 777, 'customer_order_id' => 'OI888', 'user_id' => 1000, 'site_id' => 1];
-
- return \Vvveb\invoiceFormat($format, $data);
- }
-
- function invoiceFormat() {
+ /**
+ * Output an invoice format preview for AJAX.
+ *
+ * @return never
+ */
+ public function invoiceFormat(): never {
$format = $this->request->get['format'] ?? false;
if ($format) {
$format = $this->invoiceFormatPreview($format);
}
- die($format);
+ exit($format);
}
- function orderIdFormat() {
+ /**
+ * Output an order ID format preview for AJAX.
+ *
+ * @return never
+ */
+ public function orderIdFormat(): never {
$format = $this->request->get['format'] ?? false;
if ($format) {
$format = $this->invoiceFormatPreview($format);
}
- die($format);
+ exit($format);
}
- function regions() {
+ /**
+ * Return regions for a given country as JSON.
+ *
+ * @return void
+ */
+ public function regions(): void {
$country_id = $this->request->get['country_id'] ?? false;
$regions = [];
@@ -118,11 +121,23 @@ class Site extends Base {
$this->response->output($regions);
}
- function add() {
+ /**
+ * Alias for save().
+ *
+ * @return void
+ */
+ public function add(): void {
$this->save();
}
- private function themeTemplates($theme) {
+ /**
+ * Get template file list for a given theme.
+ *
+ * @param string $theme The theme name
+ *
+ * @return array<int|string, mixed> The template file list
+ */
+ private function themeTemplates(string $theme): array {
$templates = getTemplateList($theme, ['email']);
$files = ['index.html' => 'Home page'];
@@ -137,22 +152,47 @@ class Site extends Base {
return $files;
}
- function getThemeTemplates() {
+ /**
+ * Return theme templates as JSON for AJAX.
+ *
+ * @return array<int|string, mixed>|null The template files or null if no theme
+ */
+ public function getThemeTemplates(): ?array {
$theme = $this->request->get['theme'];
if ($theme) {
$files = $this->themeTemplates($theme);
$this->response->setType('json');
+
return $files;
}
+
+ return null;
}
- function save() {
+ /**
+ * Save a site (create or update) with settings, routes, and templates.
+ *
+ * @return void
+ */
+ public function save(): void {
+ $site_id = $this->request->get['site_id'] ?? false;
+ $edit_other_sites = Admin::hasCapability('edit_other_sites');
+
+ if (!$edit_other_sites) {
+ $access = Admin::siteAccess();
+ if (!$site_id || !in_array($site_id, $access)) {
+ $this->notFound('Permission denied!', 403);
+
+ return;
+ }
+ }
+
$siteValidator = new Validator(['site']);
$settingsValidator = new Validator(['site-settings']);
$view = $this->view;
- $site = $this->request->post['site'] ?? [];
+ $site = $this->request->post['site'] ?? [];
$settings = $this->request->post['settings'] ?? [];
$routes = $this->request->post['route'] ?? [];
$routesType = $this->request->post['routes-type'] ?? [];
@@ -162,7 +202,7 @@ class Site extends Base {
$r = $route['route'];
unset($route['route']);
foreach ($route as $key => &$value) {
- if (! $value) {
+ if (!$value) {
unset($route[$key]);
}
}
@@ -174,23 +214,23 @@ class Site extends Base {
($errors = $settingsValidator->validate($settings)) === true) {
$sites = new SiteSQL();
- if (! isset($site['host']) || ! $site['host']) {
+ if (!isset($site['host']) || !$site['host']) {
$site['host'] = slugify($site['name']) . '.*.*';
}
if ($this->request->post['site-type'] == 'subfolder') {
$site['host'] = '*.*.*';
- if (! $site['path']) {
+ if (!$site['path']) {
$site['path'] = slugify($site['name']);
}
}
if ($this->request->post['site-type'] == 'both') {
- if (! $site['path'] && $site['path']) {
+ if (!$site['host']) {
$site['host'] = '*.*.*';
}
- if (! $site['path']) {
+ if (!$site['path']) {
$site['path'] = slugify($site['name']);
}
}
@@ -225,11 +265,12 @@ class Site extends Base {
//array_walk_recursive($settings['description'], '\Vvveb\sanitizeHTML');
- if (isset($this->request->get['site_id']) && ($site_id = $this->request->get['site_id'])) {
+ if ($site_id) {
$data['site_id'] = (int)$site_id;
$site['settings'] = json_encode($settings);
$data['site'] = $site;
$site['site_id'] = $data['site_id'];
+ unset($data['site']['template']);
$result = $sites->edit($data);
//Sites::saveSite($site);
@@ -237,7 +278,7 @@ class Site extends Base {
Sites::setSiteDataById($data['site_id'], null, $site);
- list($site, $settings, $site_id, $data) = Event :: trigger(__CLASS__,__FUNCTION__, $site, $settings, $site_id, $data);
+ [$site, $settings, $site_id, $data] = Event :: trigger(__CLASS__, __FUNCTION__, $site, $settings, $site_id, $data);
if ($result >= 0) {
//CacheManager::delete('site');
@@ -256,7 +297,7 @@ class Site extends Base {
$view->success['get'] = $message;
//$this->redirect(['module'=>'settings/sites', 'success'=> $message]);
} else {
- $this->view->errors = [$sites->error];
+ $view->errors = ($sites->error ?? []) ?: [];
}
} else {
$newHomepage = $this->request->post['new-homepage'] ?? [];
@@ -266,7 +307,7 @@ class Site extends Base {
continue;
}
- $template = $site['template'][$languageId] ?: 'index.html';
+ $template = $site['template'][$languageId] ?: 'index.html';
$newTemplate = str_replace('.html', '', $template) . '-' . slugify($site['name']);
if ($languageId) {
@@ -297,7 +338,7 @@ class Site extends Base {
}
foreach ($site['template'] as $id => $template) {
- if (! $template) {
+ if (!$template) {
unset($site['template'][$id]);
}
}
@@ -307,10 +348,10 @@ class Site extends Base {
$return = $sites->add($data);
$site_id = $return['site'];
$site['state'] = 'live';
- $site['site_id'] = $site_id;
+ $site['site_id'] = $site_id;
Sites::saveSite($site);
- list($site, $settings, $site_id, $data) = Event :: trigger(__CLASS__,__FUNCTION__, $site, $settings, $site_id, $data);
+ [$site, $settings, $site_id, $data] = Event :: trigger(__CLASS__, __FUNCTION__, $site, $settings, $site_id, $data);
if ($site_id) {
$siteRoutes = DIR_CONFIG . "site-$site_id-routes.php";
@@ -327,9 +368,10 @@ class Site extends Base {
CacheManager::delete();
$message = __('Site saved!');
$view->success['get'] = $message;
- $view->errors = [$sites->error];
+ $view->errors = ($sites->error ?? []) ?: [];
+ $this->redirect(['module' => 'settings/site', 'success' => $message, 'site_id' => $site_id]);
} else {
- $this->redirect(['module'=>'settings/site', 'success' => $message, 'site_id' => $site_id]);
+ $view->errors = ($sites->error ?? []) ?: [];
}
}
} else {
@@ -339,25 +381,39 @@ class Site extends Base {
$this->index();
}
- function index() {
+ /**
+ * Display the site edit/create form with all configuration data.
+ *
+ * @return void
+ */
+ public function index(): void {
$themeList = Themes:: getList();
$site_id = $this->request->get['site_id'] ?? null;
$view = $this->view;
$site = [];
- $siteSql = new SiteSQL();
+ $siteSQL = new SiteSQL();
if ($site_id) {
- $site = $siteSql->get(['site_id' => $site_id]);
- $data = Sites::getSiteById($site_id);
+ $view_other_sites = Admin::hasCapability('view_other_sites');
+
+ if (!$view_other_sites) {
+ $access = Admin::siteAccess();
+ if (!in_array($site_id, $access)) {
+ $this->notFound('Permission denied!', 403);
- if (! $site || ! $data) {
- return $this->notFound();
+ return;
+ }
}
- if ($data) {
- $site = $data + $site;
+ $site = $siteSQL->get(['site_id' => $site_id]);
+ $data = Sites::getSiteById($site_id);
+
+ if (!$site || !$data) {
+ $this->notFound();
}
+
+ $site = $data + $site;
}
$default = '{"logo":"logo.png","logo-sticky":"logo.png","logo-dark":"logo-white.png","logo-dark-sticky":"logo-white.png","favicon":"favicon.ico","webbanner":"biglogo.png", "country_id":223, "region_id":3655}';
@@ -369,7 +425,7 @@ class Site extends Base {
}
}
- $data = $siteSql->getData(['language_id' => $this->global['language_id']] + ($setting ?? []) + $this->global);
+ $data = $siteSQL->getData(['language_id' => $this->global['language_id']] + ($setting ?? []) + $this->global);
$data['complete_status_id'] = $data['processing_status_id'] = ($data['order_status_id'] ?? []);
$data['timezone'] = [];
@@ -403,9 +459,9 @@ class Site extends Base {
$data['time_format'][$format] = date($format);
}
- list($site, $setting, $site_id, $data) = Event :: trigger(__CLASS__,__FUNCTION__, $site, $setting, $site_id, $data);
+ [$site, $setting, $site_id, $data] = Event :: trigger(__CLASS__, __FUNCTION__, $site, $setting, $site_id, $data);
- if (! defined('CLI')) {
+ if (!defined('CLI')) {
$view->domain = '';
if ($domain) {
@@ -416,24 +472,24 @@ class Site extends Base {
$setting['order_id_format_preview'] = $this->invoiceFormatPreview($setting['order_id_format'] ?? '');
$view->set($data);
- //$site['full-url'] = $site ? ('//' . Sites::url($site['host']) . (V_SUBDIR_INSTALL ? V_SUBDIR_INSTALL : '') . ($site['path'] ?? '' ? '/' . $site['path'] : '')) : '';
- $site['full-url'] = $site ? ('//' . $site['url']) : '';
- $view->site = $site + $setting;
- $view->path = $site['path'] ?? '';
- $view->setting = $setting;
- $view->resize = ['cs' => __('Crop & Resize'), 's' => __('Stretch'), 'c' => __('Crop')];
- $view->formats = Image::formats();
- $view->themeList = $themeList;
- $view->subdir = V_SUBDIR_INSTALL ? V_SUBDIR_INSTALL : '';
- $view->templateList = getTemplateList(false, ['email']);
+ //$site['full-url'] = $site ? ('//' . Sites::url($site['host']) . V_SUBDIR_INSTALL . ($site['path'] ?? '' ? '/' . $site['path'] : '')) : '';
+ $site['full-url'] = $site ? ('//' . $site['url']) : '';
+ $view->site = $site + $setting;
+ $view->path = $site['path'] ?? '';
+ $view->setting = $setting;
+ $view->resize = ['cs' => __('Crop & Resize'), 'r' => __('Resize'), 's' => __('Stretch'), 'c' => __('Crop')];
+ $view->formats = Image::formats();
+ $view->themeList = $themeList;
+ $view->subdir = V_SUBDIR_INSTALL ?: '';
+ $view->templateList = getTemplateList(null, ['email']);
$view->currenciesList = Locale :: availableCurrencies();
$siteRoutes = DIR_CONFIG . "site-$site_id-routes.php";
if (file_exists($siteRoutes)) {
- $view->routes = include $siteRoutes;
+ $view->routes = include $siteRoutes;
$view->routesType = 'site';
} else {
- $view->routes = include DIR_CONFIG . 'app-routes.php';
+ $view->routes = include DIR_CONFIG . 'app-routes.php';
$view->routesType = 'global';
}
@@ -441,16 +497,22 @@ class Site extends Base {
$cache = Cache::getInstance();
- $view->modules = $cache->cache(APP, 'app-actions',function () {
+ $view->modules = $cache->cache(APP, 'app-actions', function() {
$actions = Role::controllers('app');
//set home first
$home = $actions['index'];
- $actions = array_merge($home, $actions);
- return $actions;
+ return array_merge($home, $actions);
}, 259200);
+ $payment = Payment::getInstance();
+ $shipping = Shipping::getInstance();
+
+ $checkoutInfo = [];
+ $view->paymentMethods = $payment->getMethods($checkoutInfo);
+ $view->shippingMethods = $shipping->getMethods($checkoutInfo);
+
$controllerPath = $admin_path . 'index.php?module=media/media';
$view->scanUrl = "$controllerPath&action=scan";
$view->uploadUrl = "$controllerPath&action=upload";
diff --git a/admin/controller/settings/stock-status.php b/admin/controller/settings/stock-status.php
index 6acc9fd..ba9e0bb 100755
--- a/admin/controller/settings/stock-status.php
+++ b/admin/controller/settings/stock-status.php
@@ -25,9 +25,12 @@ namespace Vvveb\Controller\Settings;
use Vvveb\Controller\Crud;
class StockStatus extends Crud {
- protected $type = 'stock_status';
+ /** @var string The entity type identifier */
+ protected string $type = 'stock_status';
- protected $controller = 'stock-status';
+ /** @var string The controller route slug */
+ protected string $controller = 'stock-status';
- protected $module = 'settings';
+ /** @var string The module namespace */
+ protected string $module = 'settings';
}
diff --git a/admin/controller/settings/stock-statuses.php b/admin/controller/settings/stock-statuses.php
index ade655d..8b8a0b9 100755
--- a/admin/controller/settings/stock-statuses.php
+++ b/admin/controller/settings/stock-statuses.php
@@ -25,13 +25,18 @@ namespace Vvveb\Controller\Settings;
use Vvveb\Controller\Listing;
class StockStatuses extends Listing {
- protected $type = 'stock_status';
+ /** @var string The entity type identifier */
+ protected string $type = 'stock_status';
- protected $controller = 'stock-status';
+ /** @var string The single-item controller route slug */
+ protected string $controller = 'stock-status';
- protected $listController = 'stock-statuses';
+ /** @var string The list controller route slug */
+ protected string $listController = 'stock-statuses';
- protected $list = 'stock_status';
+ /** @var string The list property name on the view */
+ protected string $list = 'stock_status';
- protected $module = 'settings';
+ /** @var string The module namespace */
+ protected string $module = 'settings';
}
diff --git a/admin/controller/settings/subscription-plan.php b/admin/controller/settings/subscription-plan.php
old mode 100644
new mode 100755
index 95748b1..947c676
--- a/admin/controller/settings/subscription-plan.php
+++ b/admin/controller/settings/subscription-plan.php
@@ -24,16 +24,101 @@ namespace Vvveb\Controller\Settings;
use function Vvveb\__;
use Vvveb\Controller\Crud;
+use function Vvveb\getSetting;
+use function Vvveb\model;
class SubscriptionPlan extends Crud {
- protected $type = 'subscription_plan';
+ /** @var string The entity type identifier */
+ protected string $type = 'subscription_plan';
- protected $controller = 'subscription-plan';
+ /** @var string The controller route slug */
+ protected string $controller = 'subscription-plan';
- protected $module = 'settings';
+ /** @var string The module namespace */
+ protected string $module = 'settings';
- function index() {
- parent :: index();
+ /**
+ * Save the plan and propagate interval changes to live gateway subscriptions.
+ *
+ * Gateway prices are immutable, so a period/cycle change creates a new
+ * price and swaps every active Stripe-provisioned subscription on the
+ * plan. Local-only rows are untouched.
+ *
+ * @return void
+ */
+ public function save(): void {
+ $planId = $this->request->post['subscription_plan_id'] ?? $this->request->get['subscription_plan_id'] ?? false;
+ $old = null;
+
+ if ($planId) {
+ try {
+ $old = model('subscription_plan')->get([
+ 'subscription_plan_id' => (int)$planId,
+ 'language_id' => $this->global['language_id'] ?? 1,
+ ] + $this->global);
+ } catch (\Throwable $e) {
+ }
+ }
+
+ parent::save();
+
+ if (!empty($this->view->errors) || !$planId || !is_array($old)) {
+ return;
+ }
+
+ $new = null;
+
+ try {
+ $new = model('subscription_plan')->get([
+ 'subscription_plan_id' => (int)$planId,
+ 'language_id' => $this->global['language_id'] ?? 1,
+ ] + $this->global);
+ } catch (\Throwable $e) {
+ return;
+ }
+
+ if (!is_array($new)
+ || ((($old['period'] ?? null) === ($new['period'] ?? null))
+ && (($old['cycle'] ?? null) == ($new['cycle'] ?? null)))
+ ) {
+ return;
+ }
+
+ if (!class_exists('Vvveb\Plugins\Stripe\System\Stripe')) {
+ return;
+ }
+
+ $settings = getSetting('stripe', []);
+
+ if (empty($settings['secret_key'])) {
+ return;
+ }
+
+ try {
+ $api = new \Vvveb\Plugins\Stripe\System\Stripe();
+ $result = $api->propagatePlanInterval($new, $settings['secret_key']);
+ } catch (\Throwable $e) {
+ $this->view->errors[] = __('Plan saved, but interval propagation failed!');
+
+ return;
+ }
+
+ $updated = count($result['updated']);
+ $failed = count($result['failed']);
+
+ if ($updated || $failed) {
+ $this->view->success[] = sprintf(__('Plan saved! Interval applied to %d subscription(s).'), $updated)
+ . ($failed ? ' ' . sprintf(__('%d failed.'), $failed) : '');
+ }
+ }
+
+ /**
+ * Display the subscription plan edit/create form with period and trial options.
+ *
+ * @return void
+ */
+ public function index(): void {
+ parent::index();
$this->view->period = ['day' => __('Day'), 'week' => __('Week'), 'month' => __('Month'), 'year' => __('Year')];
$this->view->trial_period = $this->view->period;
diff --git a/admin/controller/settings/subscription-plans.php b/admin/controller/settings/subscription-plans.php
old mode 100755
new mode 100644
index a83759e..b04ac4a
--- a/admin/controller/settings/subscription-plans.php
+++ b/admin/controller/settings/subscription-plans.php
@@ -25,15 +25,21 @@ namespace Vvveb\Controller\Settings;
use Vvveb\Controller\Listing;
class SubscriptionPlans extends Listing {
- protected $additionalPermissionCheck = ['settings/subscription-plan/save'];
-
- protected $type = 'subscription_plan';
+ /** @var array<int, string> Additional permission URLs required for access */
+ protected ?array $additionalPermissionCheck = ['settings/subscription-plan/save'];
- protected $controller = 'subscription-plan';
+ /** @var string The entity type identifier */
+ protected string $type = 'subscription_plan';
- protected $listController = 'subscription-plans';
+ /** @var string The single-item controller route slug */
+ protected string $controller = 'subscription-plan';
- protected $list = 'subscription_plan';
+ /** @var string The list controller route slug */
+ protected string $listController = 'subscription-plans';
- protected $module = 'settings';
+ /** @var string The list property name on the view */
+ protected string $list = 'subscription_plan';
+
+ /** @var string The module namespace */
+ protected string $module = 'settings';
}
diff --git a/admin/controller/settings/subscription-status.php b/admin/controller/settings/subscription-status.php
index fa641fb..44042ef 100755
--- a/admin/controller/settings/subscription-status.php
+++ b/admin/controller/settings/subscription-status.php
@@ -25,9 +25,12 @@ namespace Vvveb\Controller\Settings;
use Vvveb\Controller\Crud;
class SubscriptionStatus extends Crud {
- protected $type = 'subscription_status';
+ /** @var string The entity type identifier */
+ protected string $type = 'subscription_status';
- protected $controller = 'subscription-status';
+ /** @var string The controller route slug */
+ protected string $controller = 'subscription-status';
- protected $module = 'settings';
+ /** @var string The module namespace */
+ protected string $module = 'settings';
}
diff --git a/admin/controller/settings/subscription-statuses.php b/admin/controller/settings/subscription-statuses.php
index 6698ca6..6e9a5a2 100755
--- a/admin/controller/settings/subscription-statuses.php
+++ b/admin/controller/settings/subscription-statuses.php
@@ -25,13 +25,18 @@ namespace Vvveb\Controller\Settings;
use Vvveb\Controller\Listing;
class SubscriptionStatuses extends Listing {
- protected $type = 'subscription_status';
+ /** @var string The entity type identifier */
+ protected string $type = 'subscription_status';
- protected $controller = 'subscription-status';
+ /** @var string The single-item controller route slug */
+ protected string $controller = 'subscription-status';
- protected $listController = 'subscription-statuses';
+ /** @var string The list controller route slug */
+ protected string $listController = 'subscription-statuses';
- protected $list = 'subscription_status';
+ /** @var string The list property name on the view */
+ protected string $list = 'subscription_status';
- protected $module = 'settings';
+ /** @var string The module namespace */
+ protected string $module = 'settings';
}
diff --git a/admin/controller/settings/tax-rate.php b/admin/controller/settings/tax-rate.php
index 6c5eecd..d8edc65 100755
--- a/admin/controller/settings/tax-rate.php
+++ b/admin/controller/settings/tax-rate.php
@@ -24,19 +24,31 @@ namespace Vvveb\Controller\Settings;
use function Vvveb\__;
use Vvveb\Controller\Crud;
-use Vvveb\Sql\Region_GroupSQL;
+use Vvveb\Sql\Region_groupSQL;
+use Vvveb\Sql\Tax_rate_to_user_groupSQL;
+use Vvveb\Sql\User_groupSQL;
+use Vvveb\System\Cart\Tax;
class TaxRate extends Crud {
- protected $type = 'tax_rate';
+ /** @var string The entity type identifier */
+ protected string $type = 'tax_rate';
- protected $controller = 'tax-rate';
+ /** @var string The controller route slug */
+ protected string $controller = 'tax-rate';
- protected $module = 'settings';
+ /** @var string The module namespace */
+ protected string $module = 'settings';
- function index() {
+ /**
+ * Display the tax rate edit/create form with region groups and
+ * customer group restrictions.
+ *
+ * @return void
+ */
+ public function index(): void {
parent::index();
- $geoRegion = new Region_GroupSQL();
+ $geoRegion = new Region_groupSQL();
$regions = $geoRegion->getAll();
$region_group_id = [];
@@ -45,7 +57,136 @@ class TaxRate extends Crud {
$region_group_id[$region_group['region_group_id']] = $region_group['name'];
}
- $this->view->type = ['f' => __('Fixed'), 'p' => __('Percent')];
- $this->view->region_group_id = $region_group_id;
+ $this->view->type = ['f' => __('Fixed'), 'p' => __('Percent')];
+ $this->view->region_group_id = $region_group_id;
+ $this->view->user_groups = $this->userGroups();
+ $this->view->rate_user_groups = $this->rateUserGroups();
+ $this->view->user_groups_label = __('Customer groups');
+ $this->view->user_groups_hint = __('Leave all unticked to apply this rate to every group.');
+ }
+
+ /**
+ * Save a tax rate and its customer group restrictions, then drop the
+ * cached region rules so the new rate applies immediately.
+ *
+ * @return void
+ */
+ public function save(): void {
+ $tax_rate_id = $this->request->get['tax_rate_id'] ?? false;
+
+ if (!$tax_rate_id) {
+ //Crud::save() redirects (and dies) on create, before we could
+ //store the group mapping, so suppress the redirect, save the
+ //mapping, then redirect manually.
+ $this->redirect = false;
+ parent::save();
+ $new_id = (int)($this->tax_rate_id ?? 0);
+
+ if (!$new_id) {
+ //save failed, errors are already in the view, re-render
+ $this->index();
+
+ //return $result;
+ }
+
+ $this->saveUserGroups($new_id);
+ Tax::clearRulesCache();
+ $this->redirect(['module' => $this->module . '/' . $this->controller, 'tax_rate_id' => $new_id]);
+
+ //return $result;
+ }
+
+ parent::save();
+ $this->saveUserGroups((int)$tax_rate_id);
+ Tax::clearRulesCache();
+ }
+
+ /**
+ * Delete tax rates and drop the cached region rules.
+ *
+ * Group mappings are removed by the model delete procedure.
+ *
+ * @return void
+ */
+ public function delete(): void {
+ parent::delete();
+ Tax::clearRulesCache();
+ }
+
+ /**
+ * All customer groups for the restriction checkboxes.
+ *
+ * @return array<int, array<string, mixed>>
+ */
+ private function userGroups(): array {
+ try {
+ $options = $this->global;
+ $options['language_id'] = $this->global['language_id'] ?? 1;
+ unset($options['limit'], $options['start'], $options['page']);
+
+ $groups = (new User_groupSQL())->getAll($options);
+
+ return $groups['user_group'] ?? [];
+ } catch (\Throwable $e) {
+ return [];
+ }
+ }
+
+ /**
+ * Customer group ids currently restricting the edited rate.
+ * Empty means the rate applies to every group.
+ *
+ * @return array<int, int>
+ */
+ private function rateUserGroups(): array {
+ $tax_rate_id = (int)($this->request->get['tax_rate_id'] ?? 0);
+
+ if (!$tax_rate_id) {
+ return [];
+ }
+
+ try {
+ $rows = (new Tax_rate_to_user_groupSQL())->getAll(['tax_rate_id' => $tax_rate_id]);
+ $selected = [];
+
+ foreach ($rows['tax_rate_to_user_group'] ?? [] as $row) {
+ $selected[] = (int)$row['user_group_id'];
+ }
+
+ return $selected;
+ } catch (\Throwable $e) {
+ return [];
+ }
+ }
+
+ /**
+ * Replace the customer group restrictions for one rate.
+ * No checkboxes ticked clears the restriction (rate applies to all).
+ *
+ * @param int $tax_rate_id
+ *
+ * @return void
+ */
+ private function saveUserGroups(int $tax_rate_id): void {
+ if (!$tax_rate_id) {
+ return;
+ }
+
+ $posted = array_unique(array_map('intval', (array)($this->request->post['user_group'] ?? [])));
+ $valid = [];
+
+ foreach ($this->userGroups() as $group) {
+ $id = (int)($group['user_group_id'] ?? 0);
+
+ if ($id && in_array($id, $posted, true)) {
+ $valid[] = ['user_group_id' => $id];
+ }
+ }
+
+ try {
+ (new Tax_rate_to_user_groupSQL())->add(['tax_rate_user_group' => $valid, 'tax_rate_id' => $tax_rate_id]);
+ } catch (\Throwable $e) {
+ $this->view->errors[] = __('Error saving customer groups!');
+ }
}
}
diff --git a/admin/controller/settings/tax-rates.php b/admin/controller/settings/tax-rates.php
index bcd4044..7fcecf9 100755
--- a/admin/controller/settings/tax-rates.php
+++ b/admin/controller/settings/tax-rates.php
@@ -25,13 +25,18 @@ namespace Vvveb\Controller\Settings;
use Vvveb\Controller\Listing;
class TaxRates extends Listing {
- protected $type = 'tax_rate';
+ /** @var string The entity type identifier */
+ protected string $type = 'tax_rate';
- protected $controller = 'tax-rate';
+ /** @var string The single-item controller route slug */
+ protected string $controller = 'tax-rate';
- protected $listController = 'tax-rates';
+ /** @var string The list controller route slug */
+ protected string $listController = 'tax-rates';
- protected $list = 'tax_rate';
+ /** @var string The list property name on the view */
+ protected string $list = 'tax_rate';
- protected $module = 'settings';
+ /** @var string The module namespace */
+ protected string $module = 'settings';
}
diff --git a/admin/controller/settings/tax-type.php b/admin/controller/settings/tax-type.php
index 8e9e6ce..1bed56e 100755
--- a/admin/controller/settings/tax-type.php
+++ b/admin/controller/settings/tax-type.php
@@ -22,36 +22,62 @@
namespace Vvveb\Controller\Settings;
+use function Vvveb\__;
use Vvveb\Controller\Crud;
-use Vvveb\Sql\Tax_RateSQL;
-use Vvveb\Sql\Tax_RuleSQL;
+use Vvveb\Sql\Tax_rateSQL;
+use Vvveb\Sql\Tax_ruleSQL;
+use Vvveb\System\Cart\Tax;
class TaxType extends Crud {
- protected $type = 'tax_type';
+ /** @var string The entity type identifier */
+ protected string $type = 'tax_type';
- protected $controller = 'tax-type';
+ /** @var string The controller route slug */
+ protected string $controller = 'tax-type';
- protected $module = 'settings';
+ /** @var string The module namespace */
+ protected string $module = 'settings';
- function save() {
+ /**
+ * Save a tax type and its associated tax rules.
+ *
+ * @return void
+ */
+ public function save(): void {
$tax_rule = $this->request->post['tax_rule'] ?? [];
$tax_type_id = $this->request->get['tax_type_id'] ?? false;
if ($tax_type_id) {
- $taxRules = new Tax_RuleSQL();
+ $taxRules = new Tax_ruleSQL();
$taxRules->add(['tax_type_id' => $tax_type_id, 'tax_rule' => $tax_rule]);
}
parent::save();
+ Tax::clearRulesCache();
}
- function index() {
+ /**
+ * Delete tax types and drop the cached region rules.
+ *
+ * @return void
+ */
+ public function delete(): void {
+ parent::delete();
+ Tax::clearRulesCache();
+ }
+
+ /**
+ * Display the tax type edit/create form with tax rules and rates.
+ *
+ * @return void
+ */
+ public function index(): void {
parent::index();
$tax_type_id = $this->request->get['tax_type_id'] ?? false;
if ($tax_type_id) {
- $taxRules = new Tax_RuleSQL();
- $taxRates = new Tax_RateSQL();
+ $taxRules = new Tax_ruleSQL();
+ $taxRates = new Tax_rateSQL();
$tax_rates = $taxRates->getAll(['tax_type_id' => $tax_type_id]);
$this->view->tax_rates = $tax_rates['tax_rate'];
@@ -60,6 +86,6 @@ class TaxType extends Crud {
}
$this->view->tax_type_id = $tax_type_id;
- $this->view->based = ['shipping' =>'Shipping Address', 'payment' => 'Payment Address', 'store' => 'Store Address'];
+ $this->view->based = ['shipping' => __('Shipping Address'), 'payment' => __('Payment Address'), 'store' => __('Store Address')];
}
-}
\ No newline at end of file
+}
diff --git a/admin/controller/settings/tax-types.php b/admin/controller/settings/tax-types.php
index 94e2643..ba57cdc 100755
--- a/admin/controller/settings/tax-types.php
+++ b/admin/controller/settings/tax-types.php
@@ -25,13 +25,18 @@ namespace Vvveb\Controller\Settings;
use Vvveb\Controller\Listing;
class TaxTypes extends Listing {
- protected $type = 'tax_type';
+ /** @var string The entity type identifier */
+ protected string $type = 'tax_type';
- protected $controller = 'tax-type';
+ /** @var string The single-item controller route slug */
+ protected string $controller = 'tax-type';
- protected $listController = 'tax-types';
+ /** @var string The list controller route slug */
+ protected string $listController = 'tax-types';
- protected $list = 'tax_type';
+ /** @var string The list property name on the view */
+ protected string $list = 'tax_type';
- protected $module = 'settings';
+ /** @var string The module namespace */
+ protected string $module = 'settings';
}
diff --git a/admin/controller/settings/taxonomies.php b/admin/controller/settings/taxonomies.php
index 6dc6f7b..c2bd734 100755
--- a/admin/controller/settings/taxonomies.php
+++ b/admin/controller/settings/taxonomies.php
@@ -25,13 +25,18 @@ namespace Vvveb\Controller\Settings;
use Vvveb\Controller\Listing;
class Taxonomies extends Listing {
- protected $type = 'taxonomy';
+ /** @var string The entity type identifier */
+ protected string $type = 'taxonomy';
- protected $controller = 'taxonomy';
+ /** @var string The single-item controller route slug */
+ protected string $controller = 'taxonomy';
- protected $listController = 'taxonomies';
+ /** @var string The list controller route slug */
+ protected string $listController = 'taxonomies';
- protected $list = 'taxonomy';
+ /** @var string The list property name on the view */
+ protected string $list = 'taxonomy';
- protected $module = 'settings';
+ /** @var string The module namespace */
+ protected string $module = 'settings';
}
diff --git a/admin/controller/settings/taxonomy.php b/admin/controller/settings/taxonomy.php
old mode 100644
new mode 100755
index d215833..625d1dd
--- a/admin/controller/settings/taxonomy.php
+++ b/admin/controller/settings/taxonomy.php
@@ -27,32 +27,38 @@ use Vvveb\Controller\Crud;
use Vvveb\System\Event;
class Taxonomy extends Crud {
- protected $type = 'taxonomy';
+ /** @var string The entity type identifier */
+ protected string $type = 'taxonomy';
- protected $controller = 'taxonomy';
+ /** @var string The controller route slug */
+ protected string $controller = 'taxonomy';
- protected $module = 'settings';
+ /** @var string The module namespace */
+ protected string $module = 'settings';
- function index() {
+ /**
+ * Display the taxonomy edit/create form with post type options.
+ *
+ * @return void
+ */
+ public function index(): void {
parent::index();
$this->view->type = ['categories' => __('Categories'), 'tags' => __('Tags')];
- $postType = ['post' => __('Post'), 'page' => __('Page'), 'product' => __('product')];
+ $postType = ['post' => __('Post'), 'page' => __('Page'), 'product' => __('Product')];
$userPostTypes = \Vvveb\getSetting('post', 'types', []);
- list($pluginPostTypes) = Event::trigger('Vvveb\Controller\Base', 'customPost', []);
+ [$pluginPostTypes] = Event::trigger('Vvveb\Controller\Base', 'customPost', []);
$customPost = $userPostTypes + $pluginPostTypes;
array_walk($customPost, fn (&$type, $key) => $type = ucfirst($key));
$postType += $customPost;
$userProductTypes = \Vvveb\getSetting('product', 'types', []);
- list($pluginProductTypes) = Event::trigger('Vvveb\Controller\Base', 'customProduct', []);
+ [$pluginProductTypes] = Event::trigger('Vvveb\Controller\Base', 'customProduct', []);
$customProduct = $userProductTypes + $pluginProductTypes;
array_walk($customProduct, fn (&$type, $key) => $type = ucfirst($key));
$postType += $customProduct;
$this->view->post_type = $postType;
-
- //$this->view->taxonomy_id = $taxonomy_item_id;
}
}
diff --git a/admin/controller/settings/weight-type.php b/admin/controller/settings/weight-type.php
index 50931e0..cd21aec 100755
--- a/admin/controller/settings/weight-type.php
+++ b/admin/controller/settings/weight-type.php
@@ -25,9 +25,12 @@ namespace Vvveb\Controller\Settings;
use Vvveb\Controller\Crud;
class WeightType extends Crud {
- protected $type = 'weight_type';
+ /** @var string The entity type identifier */
+ protected string $type = 'weight_type';
- protected $controller = 'weight-type';
+ /** @var string The controller route slug */
+ protected string $controller = 'weight-type';
- protected $module = 'settings';
+ /** @var string The module namespace */
+ protected string $module = 'settings';
}
diff --git a/admin/controller/settings/weight-types.php b/admin/controller/settings/weight-types.php
index dc6f6df..6866b57 100755
--- a/admin/controller/settings/weight-types.php
+++ b/admin/controller/settings/weight-types.php
@@ -25,13 +25,18 @@ namespace Vvveb\Controller\Settings;
use Vvveb\Controller\Listing;
class WeightTypes extends Listing {
- protected $type = 'weight_type';
+ /** @var string The entity type identifier */
+ protected string $type = 'weight_type';
- protected $controller = 'weight-type';
+ /** @var string The single-item controller route slug */
+ protected string $controller = 'weight-type';
- protected $listController = 'weight-types';
+ /** @var string The list controller route slug */
+ protected string $listController = 'weight-types';
- protected $list = 'weight_type';
+ /** @var string The list property name on the view */
+ protected string $list = 'weight_type';
- protected $module = 'settings';
+ /** @var string The module namespace */
+ protected string $module = 'settings';
}
diff --git a/admin/controller/theme/fonts.php b/admin/controller/theme/fonts.php
old mode 100644
new mode 100755
index 7a3c78b..88895c0
--- a/admin/controller/theme/fonts.php
+++ b/admin/controller/theme/fonts.php
@@ -34,15 +34,35 @@ use Vvveb\System\Traits\Media as MediaTrait;
class Fonts extends Base {
use MediaTrait;
- protected $dirMedia = DIR_PUBLIC . 'fonts' . DS;
-
- protected $fontsPath = '../../../fonts/'; // /public/fonts relative to /themes/theme-slug/css folder
-
- private function getTheme() {
- return $theme = sanitizeFileName($this->request->get['theme'] ?? Sites::getTheme($this->global['site_id']) ?? 'default');
+ /**
+ * Directory path for public font assets.
+ *
+ * @var string
+ */
+ protected string $dirMedia = DIR_PUBLIC . 'fonts' . DS;
+
+ /**
+ * Relative path from theme CSS folder to the public fonts directory.
+ *
+ * @var string
+ */
+ protected string $fontsPath = '../../../fonts/'; // /public/fonts relative to /themes/theme-slug/css folder
+
+ /**
+ * Get the current theme slug from the request or default.
+ *
+ * @return string The sanitized theme slug.
+ */
+ private function getTheme(): string {
+ return sanitizeFileName($this->request->get['theme'] ?? Sites::getTheme($this->global['site_id']));
}
- function save() {
+ /**
+ * Save custom font definitions to the theme's fonts.css file.
+ *
+ * @return void
+ */
+ public function save(): void {
$fonts = $this->request->post['font'] ?? [];
if ($fonts) {
@@ -51,10 +71,10 @@ class Fonts extends Base {
$cssFile = DS . 'css' . DS . 'fonts.css';
//try to create file if it doesn't exist
- if ($theme && ! file_exists($themeFolder . $cssFile) && ! touch($themeFolder . $cssFile)) {
+ if ($theme && !file_exists($themeFolder . $cssFile) && !touch($themeFolder . $cssFile)) {
$this->view->errors[] = sprintf(__('Can not create file %s!'), $theme . $cssFile);
- return $this->index();
+ $this->index();
}
if ($theme && is_writable($themeFolder . $cssFile)) {
@@ -74,7 +94,7 @@ class Fonts extends Base {
$css .= "\n$fontsCss";
- if (! file_put_contents($themeFolder . $cssFile, $css)) {
+ if (!file_put_contents($themeFolder . $cssFile, $css)) {
$this->view->errors[] = sprintf(__('%s is not writable!'), $theme . $cssFile);
}
}
@@ -83,10 +103,15 @@ class Fonts extends Base {
}
}
- return $this->index();
+ $this->index();
}
- function index() {
+ /**
+ * Display the font management page with built-in and custom font faces.
+ *
+ * @return void
+ */
+ public function index(): void {
$theme = $this->getTheme();
//var_dump(Font::themeFonts($theme));
if ($theme && is_dir($themeCssDir = DIR_THEMES . $theme . DS . 'css' . DS)) {
diff --git a/admin/controller/theme/market.php b/admin/controller/theme/market.php
index ffba864..7fade83 100755
--- a/admin/controller/theme/market.php
+++ b/admin/controller/theme/market.php
@@ -30,7 +30,12 @@ use Vvveb\System\Extensions\Themes;
use Vvveb\System\Validator;
class Market extends Base {
- function install() {
+ /**
+ * Install a theme from the marketplace by slug.
+ *
+ * @return void
+ */
+ public function install(): void {
$slug = $this->request->post['slug'] ?? false;
try {
@@ -38,10 +43,12 @@ class Market extends Base {
$theme = Themes :: getMarketList(['slug' => $slug])['themes'];
if ($theme && isset($theme[0])) {
- $themeInfo = $theme[0];
- extract($themeInfo);
- $url = Themes :: marketUrl();
- $downloadLink = "$url$download_link";
+ $themeInfo = $theme[0];
+ $download_link = $themeInfo['download_link'] ?? '';
+ $name = $themeInfo['name'] ?? '';
+ $slug = $themeInfo['slug'] ?? $slug;
+ $url = Themes :: marketUrl();
+ $downloadLink = "$url$download_link";
$this->view->log[] = sprintf(__('Installing "%s"'), $name);
$this->view->log[] = sprintf(__('Downloading "%s"'), $downloadLink);
@@ -54,9 +61,9 @@ class Market extends Base {
$themeName = \Vvveb\humanReadable($slug);
$themeName = "<b>$themeName</b>";
- $themeActivateUrl = \Vvveb\url(['module' => 'theme/themes', 'action'=> 'activate', 'theme' => $slug]);
+ $themeActivateUrl = \Vvveb\url(['module' => 'theme/themes', 'action' => 'activate', 'theme' => $slug]);
- $successMessage = sprintf(__('Theme %s was successfully installed!'), $themeName, $themeActivateUrl);
+ $successMessage = sprintf(__('Theme %s was successfully installed!'), $themeName);
$this->view->log[] = $successMessage;
$successMessage .= "<button class='btn btn-primary btn-sm btn-icon m-2' formaction='$themeActivateUrl' name='theme' value='$slug'>" . __('Activate theme') . '</button>';
@@ -84,10 +91,15 @@ class Market extends Base {
$this->view->setType('json');
}
- return $this->index();
+ $this->index();
}
- function index() {
+ /**
+ * Display the theme marketplace with categories and installed status.
+ *
+ * @return void
+ */
+ public function index(): void {
$view = View :: getInstance();
$validator = new Validator(['themes']);
@@ -103,8 +115,10 @@ class Market extends Base {
$categories = Themes :: getMarketCategories(['limit' => 100] + $request, 'categories');
$installed = Themes :: getList($this->global['site_id']);
- foreach ($themes['themes'] as &$theme) {
- $theme['installed'] = isset($installed[$theme['slug']]);
+ if ($themes) {
+ foreach ($themes['themes'] as &$theme) {
+ $theme['installed'] = isset($installed[$theme['slug']]);
+ }
}
} catch (\Exception $e) {
$view->warning[] = __('Failed to connect to marketplace');
diff --git a/admin/controller/theme/themes.php b/admin/controller/theme/themes.php
index 6701c82..3385296 100755
--- a/admin/controller/theme/themes.php
+++ b/admin/controller/theme/themes.php
@@ -36,19 +36,26 @@ use Vvveb\System\Import\Theme;
use Vvveb\System\Sites;
class Themes extends Base {
- function update() {
- $slug = $this->request->post['theme'] ?? false;
+ /**
+ * Update an installed theme from the marketplace.
+ *
+ * @return void
+ */
+ public function update(): void {
+ $slug = sanitizeFileName(basename($this->request->post['theme'] ?? ''));
try {
if ($slug) {
- $slug = sanitizeFileName($slug);
+ $slug = sanitizeFileName($slug);
$theme = ThemesList :: getMarketList(['slug' => $slug])['themes'];
if ($theme && isset($theme[0])) {
- $themeInfo = $theme[0];
- extract($themeInfo);
- $url = ThemesList :: marketUrl();
- $downloadLink = "$url$download_link";
+ $themeInfo = $theme[0];
+ $download_link = $themeInfo['download_link'] ?? '';
+ $name = $themeInfo['name'] ?? '';
+ $slug = $themeInfo['slug'] ?? $slug;
+ $url = ThemesList :: marketUrl();
+ $downloadLink = "$url$download_link";
$this->view->log[] = sprintf(__('Installing "%s"'), $name);
$this->view->log[] = sprintf(__('Downloading "%s"'), $downloadLink);
@@ -61,10 +68,10 @@ class Themes extends Base {
$srcDir = DIR_THEMES . $slug;
$destDir = DIR_THEMES . $newSlug;
- $skipFolders = [/*'backup', */'src', 'node_modules', '.git'];
- if ($theme && is_dir($srcDir)) {
+ $skipFolders = [/*'backup', */ 'src', 'node_modules', '.git'];
+ if (is_dir($srcDir)) {
if (rcopy($srcDir, $destDir, $skipFolders)) {
- $themePhp = $destDir . DS . 'theme.php';
+ $themePhp = $destDir . DS . 'theme.json';
$content = file_get_contents($themePhp);
if ($content) {
@@ -89,7 +96,7 @@ class Themes extends Base {
$this->view->log[] = sprintf(__('Unpacking "%s"'), $tempFile);
- if (! is_writable(DIR_THEMES . $slug) && ! @chmod($path, 0750)) {
+ if (!is_writable(DIR_THEMES . $slug) && !@chmod(DIR_THEMES . $slug, 0750)) {
$this->view->errors[] = sprintf(__('"%s" is not writable'), DIR_THEMES . $slug);
}
@@ -102,9 +109,9 @@ class Themes extends Base {
ThemesList :: clearThemesCache();
$themeName = humanReadable($slug);
- $themeActivateUrl = \Vvveb\url(['module' => 'theme/themes', 'action'=> 'activate', 'theme' => $slug]);
+ $themeActivateUrl = \Vvveb\url(['module' => 'theme/themes', 'action' => 'activate', 'theme' => $slug]);
- $successMessage = sprintf(__('Theme %s was successfully updated!'), $themeName, $themeActivateUrl);
+ $successMessage = sprintf(__('Theme %s was successfully updated!'), $themeName);
$this->view->log[] = $successMessage;
$this->view->success[] = $successMessage;
@@ -132,22 +139,27 @@ class Themes extends Base {
}
}
- function duplicate() {
+ /**
+ * Duplicate a theme with a new name and slug.
+ *
+ * @return void
+ */
+ public function duplicate(): void {
$theme = sanitizeFileName(basename($this->request->post['theme'] ?? ''));
$dest = sanitizeFileName(basename($this->request->post['dest'] ?? ''));
$newSlug = slugify($dest);
$srcDir = DIR_THEMES . $theme;
$destDir = DIR_THEMES . $newSlug;
- $skipFolders = [/*'backup', */'src', 'node_modules', '.git'];
+ $skipFolders = [/*'backup', */ 'src', 'node_modules', '.git'];
if ($dest) {
if (file_exists($destDir)) {
$this->view->errors[] = _('Destination directory already exists!');
} else {
- if ($theme && is_dir($srcDir)) {
+ if (is_dir($srcDir)) {
if (rcopy($srcDir, $destDir, $skipFolders)) {
- $themePhp = $destDir . DS . 'theme.php';
+ $themePhp = $destDir . DS . 'theme.json';
$content = file_get_contents($themePhp);
if ($content) {
@@ -171,14 +183,21 @@ class Themes extends Base {
}
}
- return $this->index();
+ $this->index();
}
- function delete() {
+ /**
+ * Delete a theme directory and clear the themes cache.
+ *
+ * @return void
+ */
+ public function delete(): void {
$theme = sanitizeFileName(basename($this->request->post['theme'] ?? ''));
if ($theme && is_dir(DIR_THEMES . $theme)) {
if (rrmdir(DIR_THEMES . $theme)) {
+ \Vvveb\System\Notifications::trigger('theme.delete', ['subject' => "Theme deleted: $theme", 'message' => "Theme \"$theme\" was deleted.", 'theme' => $theme]);
+
ThemesList :: clearThemesCache();
$this->view->success[] = _('Theme removed!');
} else {
@@ -186,10 +205,15 @@ class Themes extends Base {
}
}
- return $this->index();
+ $this->index();
}
- function upload() {
+ /**
+ * Handle theme file upload and installation.
+ *
+ * @return void
+ */
+ public function upload(): void {
$files = $this->request->files;
$error = false;
@@ -211,24 +235,29 @@ class Themes extends Base {
} else {
$error = true;
$this->view->errors[] = sprintf(__('Error uploading %s!'), $this->themeSlug);
- $this->view->warning[] = sprintf(fileUploadErrMessage($file['error']));
+ $this->view->warning[] = fileUploadErrMessage($file['error']);
}
- if (! $error && $this->themeSlug) {
+ if (!$error && $this->themeSlug) {
$this->themeName = humanReadable($this->themeSlug);
$this->themeName = "<b>$this->themeName</b>";
- $this->themeActivateUrl = \Vvveb\url(['module' => 'theme/themes', 'action'=> 'activate', 'theme' => $this->themeSlug]);
+ $this->themeActivateUrl = \Vvveb\url(['module' => 'theme/themes', 'action' => 'activate', 'theme' => $this->themeSlug]);
$successMessage = sprintf(__('Theme %s was successfully installed!'), '<b>' . $this->themeSlug . '</b>');
- $successMessage .= '<button type="submit" name="theme" value="' . $this->themeSlug . '" class="btn btn-primary btn-sm btn-icon ms-2" onclick="document.getElementById(\'action\').value=\'activate\';">' . __('Activate theme') . '</button>';
+ $successMessage .= '<button type="submit" name="theme" value="' . $this->themeSlug . '" class="btn btn-primary btn-sm btn-icon ms-2" onclick="document.getElementById(\'action\').value=\'activate\';">' . __('Activate theme') . '</button>';
$this->view->success[] = $successMessage;
ThemesList :: clearThemesCache();
}
}
- return $this->index();
+ $this->index();
}
- function index() {
+ /**
+ * Display the themes management page with installed themes and import structure.
+ *
+ * @return void
+ */
+ public function index(): void {
$themes = ThemesList :: getList($this->global['site_id']);
$this->view->themes = $themes;
@@ -238,11 +267,20 @@ class Themes extends Base {
$structure = $themeImport->getStructure();
$this->view->import = $structure;
- $this->view->required_plugins = ['seo'=> '', 'markdown' => '', 'test1' => ''];
+ $this->view->required_plugins = ['seo' => '', 'markdown' => '', 'test1' => ''];
$this->view->recommended_plugins = $structure;
}
- function processImport($data, $path, $type = false) {
+ /**
+ * Process theme import data recursively.
+ *
+ * @param array<int|string, mixed> $data The data to process.
+ * @param string $path The current path in the data tree.
+ * @param string|false $type The content type being processed.
+ *
+ * @return void
+ */
+ public function processImport(array $data, string $path, string|false $type = false): void {
foreach ($data as $key => $value) {
if (is_array($value)) {
switch ($key) {
@@ -263,7 +301,12 @@ class Themes extends Base {
}
}
- function import() {
+ /**
+ * Handle theme import (placeholder).
+ *
+ * @return void
+ */
+ public function import(): void {
/*
$import = $this->request->post['import'];
$required_plugins = $this->request->post['required_plugins'];
@@ -273,17 +316,20 @@ class Themes extends Base {
//$this->processImport($import, '');
//print_r($required_plugins);
//print_r($recommended_plugins);
-
- return;
}
- function activate() {
- $theme = $this->request->post['theme'] ?? false;
+ /**
+ * Activate a theme for the current site and clear caches.
+ *
+ * @return void
+ */
+ public function activate(): void {
+ $theme = sanitizeFileName(basename($this->request->post['theme'] ?? ''));
if ($theme && Sites::setTheme($this->global['site_id'], $theme, 'index.html')) {
$themeName = humanReadable($theme);
- $this->themeActivateUrl = \Vvveb\url(['module' => 'theme/themes', 'action'=> 'import', 'theme' => $theme]);
- $successMessage = sprintf(__('Theme <b>%s</b> was activated!'), $themeName, $this->themeActivateUrl);
+ $this->themeActivateUrl = \Vvveb\url(['module' => 'theme/themes', 'action' => 'import', 'theme' => $theme]);
+ $successMessage = sprintf(__('Theme <b>%s</b> was activated!'), $themeName);
//$successMessage .= '<a class="btn btn-success btn-sm ms-4" href="' . $this->themeActivateUrl . '">' . __('Import theme content') . '</a>';
$successMessage .= '<a class="btn btn-outline-primary btn-sm btn-icon ms-2" target="_blank" href="/">' . __('View website') . '</a>';
@@ -295,12 +341,12 @@ class Themes extends Base {
} else {
$error = __('Error activating theme');
- if (! is_writable(DIR_CONFIG . 'sites.php')) {
+ if (!is_writable(DIR_CONFIG . 'sites.php')) {
$error .= ' - ' . sprintf(__('%s is not writable!'), 'config/sites.php');
}
$this->view->errors[] = $error;
}
- return $this->index();
+ $this->index();
}
}
diff --git a/admin/controller/user/login.php b/admin/controller/user/login.php
index e7e8d5d..b8d5e9d 100755
--- a/admin/controller/user/login.php
+++ b/admin/controller/user/login.php
@@ -22,26 +22,40 @@
namespace Vvveb\Controller\User;
-use \Vvveb\System\Functions\Str;
use function Vvveb\__;
use function Vvveb\pregMatch;
-use Vvveb\Sql\Admin_Failed_LoginSQL;
+use Vvveb\Sql\Admin_failed_loginSQL;
use Vvveb\System\Event;
use Vvveb\System\Extensions\Plugins;
+use Vvveb\System\Functions\Str;
use Vvveb\System\Locale;
use Vvveb\System\User\Admin;
use Vvveb\System\Validator;
#[\AllowDynamicProperties]
class Login {
- //failed attemps per minute Y-m-d H:i:00
- protected $failedTimeInterval = 'Y-m-d H:00:00'; //failed attemps per hour
-
- protected $failedCount = 10; //the number of failures before account is locked
-
- protected function language() {
+ /**
+ * Time interval format for grouping failed login attempts.
+ *
+ * @var string
+ */
+ protected string $failedTimeInterval = 'Y-m-d H:00:00';
+
+ /**
+ * Maximum number of failed login attempts before the account is locked.
+ *
+ * @var int
+ */
+ protected int $failedCount = 10;
+
+ /**
+ * Initialize the default language and RTL settings for the login page.
+ *
+ * @return void
+ */
+ protected function language(): void {
$default_rtl = false;
- if (! ($default_code = $this->session->get('code'))) {
+ if (!($default_code = $this->session->get('code'))) {
$languages = Locale::availableLanguages();
foreach ($languages as $code => $lang) {
@@ -56,47 +70,62 @@ class Login {
break;
}
}
- } else {
}
- Locale :: setLanguage($default_code);
+ Locale::setLanguage($default_code);
$this->global['code'] = $default_code;
- $this->global['rtl'] = $default_rtl;
+ $this->global['rtl'] = $default_rtl;
}
- protected function redirect($url = '/', $parameters = []) {
+ /**
+ * Redirect the user to the specified URL.
+ *
+ * @param string $url The URL to redirect to.
+ * @param array<int|string, mixed> $parameters Additional URL parameters (unused).
+ *
+ * @return void
+ */
+ protected function redirect(string $url = '/', array $parameters = []): void {
header("Location: $url");
exit();
}
- function index() {
+ /**
+ * Handle the login page display and form submission.
+ *
+ * @return void
+ */
+ public function index(): void {
$view = $this->view;
$adminPath = \Vvveb\adminPath();
$view->adminPath = $adminPath;
if (isset($this->request->post['logout'])) {
- return Admin::logout();
+ Admin::logout();
+
+ return;
}
$this->language();
- //$this->checkAlreadyLoggedIn();
$admin = Admin::current();
if ($admin) {
- return $this->redirect($adminPath);
+ $this->redirect($adminPath);
+
+ return;
}
- if (! $this->session->get('csrf')) {
+ if (!$this->session->get('csrf')) {
$this->session->set('csrf', Str::random());
}
//don't load plugins at all if safemode get parameter
- if (! isset($this->request->get['safemode'])) {
+ if (!isset($this->request->get['safemode'])) {
$failedPlugins = [];
try {
- Plugins :: loadPlugins();
+ Plugins::loadPlugins();
} catch (\Throwable $e) {
$file = $e->getFile();
$plugin = pregMatch('@.*[\/]plugins[\/]([^\/]+)[$\/]@', $file, 1) ?: $file;
@@ -148,10 +177,10 @@ class Login {
$method = $this->request->getMethod();
if ($method == 'post') {
- if (! ($csrf = $this->session->get('csrf')) || ! ($postCsrf = ($this->request->post['csrf'] ?? false)) || ($csrf != $postCsrf)) {
+ if (!($csrf = $this->session->get('csrf')) || !($postCsrf = ($this->request->post['csrf'] ?? false)) || ($csrf !== $postCsrf)) {
$view->errors['get'] = __('Invalid csrf!');
+
return;
- //$this->notFound('Invalid csrf!', 403);
}
if (($view->errors = $validator->validate($this->request->post)) === true) {
@@ -167,7 +196,7 @@ class Login {
$loginData['username'] = $user;
}
- $failedLogin = new Admin_Failed_LoginSQL();
+ $failedLogin = new Admin_failed_loginSQL();
$date = date($this->failedTimeInterval);
$lastIp = $_SERVER['REMOTE_ADDR'] ?? '';
$failedAttemps = $failedLogin->get(['updated_at' => $date, 'status' => 1] + $loginData);
@@ -185,7 +214,7 @@ class Login {
$flags['safemode'] = true;
}
- list($loginData) = Event :: trigger(__CLASS__, __FUNCTION__ , $loginData);
+ [$loginData] = Event::trigger(__CLASS__, __FUNCTION__, $loginData);
if ($loginData) {
if ($userInfo = Admin::login($loginData, $flags)) {
@@ -194,7 +223,6 @@ class Login {
if (isset($this->request->post['redir']) && $this->request->post['redir'] && $_SERVER['REQUEST_URI'] != $this->request->post['redir']) {
$url = parse_url($this->request->post['redir']);
$this->redirect($url['path'] . '?' . ($url['query'] ?? '') . '#' . ($url['fragment'] ?? ''));
- //$this->redirect($this->request->post['redirect']);
} else {
$this->redirect($adminPath);
}
@@ -208,7 +236,6 @@ class Login {
}
}
} else {
- //return $this->redirect($adminPath);
$this->session->set('csrf', Str::random());
}
}
diff --git a/admin/controller/user/reset.php b/admin/controller/user/reset.php
index f4eb2d9..6ab4439 100755
--- a/admin/controller/user/reset.php
+++ b/admin/controller/user/reset.php
@@ -32,7 +32,12 @@ use function Vvveb\url;
#[\AllowDynamicProperties]
class Reset {
- function reset() {
+ /**
+ * Process the password reset form submission.
+ *
+ * @return void
+ */
+ public function reset(): void {
$token = $this->request->get['token'] ?? false;
$user = $this->request->get['user'] ?? false;
$password = $this->request->post['password'] ?? false;
@@ -49,7 +54,8 @@ class Reset {
$success = __('Password was reset!');
$this->view->success['login'] = $success;
$this->session->set('success', ['login' => $success]);
- header('Location: ' . url(['module' => 'user/login'/*, 'success' => $success*/]));
+ header('Location: ' . url(['module' => 'user/login']));
+ exit();
} else {
$errors = __('Update failed!');
$this->view->errors['login'] = $errors;
@@ -63,17 +69,25 @@ class Reset {
}
}
- if (! $admin) {
- die(__('Invalid or expired token!'));
+ if (!$admin) {
+ $this->view->errors['login'] = __('Invalid or expired token!');
+ $this->session->set('errors', ['login' => __('Invalid or expired token!')]);
+ header('Location: ' . url(['module' => 'user/login']));
+ exit();
}
}
- function index() {
+ /**
+ * Handle the password reset request page and send reset email.
+ *
+ * @return void
+ */
+ public function index(): void {
$email = $this->request->post['email'] ?? false;
$loginData = [];
$language = $this->session->get('language') ?? 'en_US';
- Locale :: setLanguage($language);
+ Locale::setLanguage($language);
if ($email) {
$loginData['email'] = $email;
@@ -83,29 +97,35 @@ class Reset {
$token = Str::random(32);
Admin::update(['token' => $token], ['email' => $adminData['email']]);
- $agent = $_SERVER['HTTP_USER_AGENT'];
+ $agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
- if (strpos($agent, 'Linux') !== false) {
+ if (str_contains($agent, 'Linux')) {
$os = 'Linux';
- } elseif (strpos($agent, '/Win/') !== false) {
+ } elseif (str_contains($agent, '/Win/')) {
$os = 'Windows';
- } elseif (strpos($agent, '/Mac/') !== false) {
+ } elseif (str_contains($agent, '/Mac/')) {
$os = 'Mac';
} else {
$os = 'UnKnown';
}
- $site = Sites :: getSiteData($this->global['site_id']);
+ $site = Sites::getSiteData($this->global['site_id'] ?? SITE_ID);
$reset_url = url(['module' => 'user/reset', 'action' => 'reset', 'token' => $token, 'user' => $adminData['username'], 'host' => $site['host'] ?? false]);
$data = $adminData + ['token' => $token, 'operating_system' => $os, 'browser_name' => $_SERVER['HTTP_USER_AGENT'], 'reset_url' => $reset_url];
+ \Vvveb\System\Notifications::trigger('admin.password_reset', $data + [
+ 'subject' => __('Password reset'),
+ 'message' => __('A password reset was requested for your account.'),
+ ]);
+
if (email($adminData['email'], __('Password reset'), 'user/reset', $data)) {
$success = __('A reset email was sent, please use it to reset your password!');
$this->view->success[] = $success;
$this->session->set('success', $success);
- header('Location: ' . url(['module' => 'user/login'/* 'success' => $success*/]));
+ header('Location: ' . url(['module' => 'user/login']));
+ exit();
} else {
$this->view->errors['login'] = __('Error sending reset email!');
}
diff --git a/admin/controller/user/user-group.php b/admin/controller/user/user-group.php
old mode 100644
new mode 100755
index ff43a6a..56f08ae
--- a/admin/controller/user/user-group.php
+++ b/admin/controller/user/user-group.php
@@ -25,9 +25,24 @@ namespace Vvveb\Controller\User;
use Vvveb\Controller\Crud;
class UserGroup extends Crud {
- protected $type = 'user_group';
+ /**
+ * Entity type identifier for user groups.
+ *
+ * @var string
+ */
+ protected string $type = 'user_group';
- protected $controller = 'user-group';
+ /**
+ * Singular controller name for detail views.
+ *
+ * @var string
+ */
+ protected string $controller = 'user-group';
- protected $module = 'user';
+ /**
+ * Module path this controller belongs to.
+ *
+ * @var string
+ */
+ protected string $module = 'user';
}
diff --git a/admin/controller/user/user-groups.php b/admin/controller/user/user-groups.php
old mode 100644
new mode 100755
index f12b0bd..68a903c
--- a/admin/controller/user/user-groups.php
+++ b/admin/controller/user/user-groups.php
@@ -25,13 +25,38 @@ namespace Vvveb\Controller\User;
use Vvveb\Controller\Listing;
class UserGroups extends Listing {
- protected $type = 'user_group';
-
- protected $controller = 'user-group';
-
- protected $listController = 'user-groups';
-
- protected $list = 'user_group';
-
- protected $module = 'user';
+ /**
+ * Entity type identifier for user groups.
+ *
+ * @var string
+ */
+ protected string $type = 'user_group';
+
+ /**
+ * Singular controller name for detail views.
+ *
+ * @var string
+ */
+ protected string $controller = 'user-group';
+
+ /**
+ * Plural controller name for listing views.
+ *
+ * @var string
+ */
+ protected string $listController = 'user-groups';
+
+ /**
+ * List key used to identify the data collection.
+ *
+ * @var string
+ */
+ protected string $list = 'user_group';
+
+ /**
+ * Module path this controller belongs to.
+ *
+ * @var string
+ */
+ protected string $module = 'user';
}
diff --git a/admin/controller/user/user.php b/admin/controller/user/user.php
index 7118747..328508b 100755
--- a/admin/controller/user/user.php
+++ b/admin/controller/user/user.php
@@ -34,33 +34,39 @@ use Vvveb\System\User\User as UserSystem;
use Vvveb\System\Validator;
class User extends Base {
- protected $type = 'user';
-
- function index() {
- $view = View :: getInstance();
+ /**
+ * User type identifier (user or admin).
+ *
+ * @var string
+ */
+ protected string $type = 'user';
+
+ /**
+ * Display the user edit form with user data, media URLs, and theme CSS.
+ *
+ * @return void
+ */
+ public function index(): void {
+ $view = View::getInstance();
$user_id = (int)($this->request->get[$this->type . '_id'] ?? false);
-
if ($user_id) {
$options = [$this->type . '_id' => (int)$user_id];
if ($this->type == 'admin') {
- if (Admin::hasCapability('view_other_admin')) {
- } else {
- if ($user_id != $this->global['admin_id']) {
- $message = __('Permission denied!');
- $view->errors[] = $message;
- $this->notFound($message, 403, true);
- }
+ if (!Admin::hasCapability('view_other_admin') && $user_id != $this->global['admin_id']) {
+ $message = __('Permission denied!');
+ $view->errors[] = $message;
+ $this->notFound($message, 403, true);
}
}
$users = model($this->type);
$user = $users->get($options);
- if (! $user) {
- return $this->notFound(__('User not found!'));
+ if (!$user) {
+ $this->notFound(__('User not found!'));
}
if (isset($user['password'])) {
@@ -71,7 +77,7 @@ class User extends Base {
//featured avatar
foreach (['avatar', 'cover'] as $image) {
if (isset($user[$image])) {
- $user[$image . '_url']= Images::image($user[$image], $this->type);
+ $user[$image . '_url'] = Images::image($user[$image], $this->type);
}
}
@@ -89,7 +95,7 @@ class User extends Base {
$view->uploadUrl = "$controllerPath&action=upload";
$view->themeCss = '';
- $theme = Sites::getTheme($this->global['site_id']) ?? 'default';
+ $theme = Sites::getTheme($this->global['site_id']);
if (file_exists(DIR_THEMES . "$theme/css/admin-post-editor.css")) {
$view->themeCss .= PUBLIC_PATH . "themes/$theme/css/admin-post-editor.css";
} else {
@@ -117,11 +123,16 @@ class User extends Base {
}
}
- function loginAs() {
+ /**
+ * Log in as a different user and display the user edit page.
+ *
+ * @return void
+ */
+ public function loginAs(): void {
$user_id = (int)($this->request->get[$this->type . '_id'] ?? false);
if ($user_id) {
- $view = View :: getInstance();
+ $view = View::getInstance();
$userInfo = UserSystem::get(['user_id' => $user_id]);
@@ -137,31 +148,34 @@ class User extends Base {
}
}
- return $this->index();
+ $this->index();
}
- function save() {
+ /**
+ * Save user data after validation, handling both create and update operations.
+ *
+ * @return void
+ */
+ public function save(): void {
$validator = new Validator([$this->type]);
- $view = View :: getInstance();
+ $view = View::getInstance();
$user_id = (int)($this->request->get[$this->type . '_id'] ?? false);
$user = $this->request->post[$this->type] ?? [];
if ($this->type == 'admin') {
$editCapability = 'edit_other_admin';
- if (Admin::hasCapability($editCapability)) {
- } else {
- if (! $user_id || $user_id != $this->global['admin_id']) {
- $view->errors[] = __('Permission denied!');
- return;
- }
+ if (!Admin::hasCapability($editCapability) && (!$user_id || $user_id != $this->global['admin_id'])) {
+ $view->errors[] = __('Permission denied!');
+
+ return;
}
$admin = Admin::current();
if (isset($user['role_id'])) {
//don't allow role change for non admin roles
- if (! in_array($admin['role'], ['super_admin', 'admin'])) {
+ if (!in_array($admin['role'], ['super_admin', 'admin'])) {
unset($user['role_id']);
} else {
//admin role can not set himself super admin, make sure role id is lower than super_admin
@@ -178,7 +192,6 @@ class User extends Base {
//if no password provided don't change
if (empty($user['password'])) {
unset($user['password']);
- } else {
}
if (isset($user['site_access'])) {
@@ -192,7 +205,7 @@ class User extends Base {
}
$user['updated_at'] = date('Y-m-d H:i:s');
- $user['bio'] = sanitizeHTML($user['bio']);
+ $user['bio'] = sanitizeHTML($user['bio']);
if ($user_id) {
if ($this->type == 'admin') {
@@ -219,11 +232,11 @@ class User extends Base {
if (isset($result[$this->type])) {
$id = $result[$this->type];
- if (! $id) {
+ if (!$id) {
$view->errors[] = $users->error;
} else {
$view->success['get'] = ucfirst($this->type) . __(' added!');
- $this->redirect(['module'=> $this->type . '/user', $this->type . '_id' => $id, 'success' => ucfirst(__($this->type)) . __(' added!')]);
+ $this->redirect(['module' => $this->type . '/user', $this->type . '_id' => $id, 'success' => ucfirst(__($this->type)) . __(' added!')]);
}
} else {
if ($result['email'] == $user['email']) {
diff --git a/admin/index.php b/admin/index.php
index a50b38d..d757d4f 100755
--- a/admin/index.php
+++ b/admin/index.php
@@ -25,20 +25,20 @@ define('APP', 'admin');
//no trailing slash for subdir path
//define('V_SUBDIR_INSTALL', '/vvveb');
-if (! isset($PUBLIC_PATH)) {
+if (!isset($PUBLIC_PATH)) {
$PUBLIC_PATH = '/public/';
}
-if (! isset($PUBLIC_THEME_PATH)) {
+if (!isset($PUBLIC_THEME_PATH)) {
$PUBLIC_THEME_PATH = '/public/admin/';
}
/*
if (! defined('PUBLIC_PATH')) {
- define('PUBLIC_PATH', (V_SUBDIR_INSTALL ? V_SUBDIR_INSTALL : '') . $PUBLIC_PATH);
- define('PUBLIC_THEME_PATH', (V_SUBDIR_INSTALL ? V_SUBDIR_INSTALL : '') . $PUBLIC_THEME_PATH);
+ define('PUBLIC_PATH', V_SUBDIR_INSTALL . $PUBLIC_PATH);
+ define('PUBLIC_THEME_PATH', V_SUBDIR_INSTALL . $PUBLIC_THEME_PATH);
}
*/
-if (! isset($FILE)) {
+if (!isset($FILE)) {
$FILE = __FILE__;
}