Skip to content

armgit / Vvveb

Public Imported from GitHub
0

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

System refactor: type hint pass, notifications, payment ledger, queue, subscription manager, sqlp engine templates

Givan9d25539044c8
diff --git a/system/cache-manager.php b/system/cache-manager.php
old mode 100755
new mode 100644
index 40a6ff6..f29ae4b
--- a/system/cache-manager.php
+++ b/system/cache-manager.php
@@ -25,12 +25,20 @@ namespace Vvveb\System;
use function Vvveb\globBrace;
class CacheManager {
- private static function clearFolder($folder, $root = DIR_PUBLIC) {
+ /**
+ * Delete all files in a cache folder.
+ *
+ * @param string $folder Relative folder path under the root directory.
+ * @param string $root Root directory path.
+ *
+ * @return bool Always returns true.
+ */
+ private static function clearFolder(string $folder, string $root = DIR_PUBLIC): bool {
$name = $root . $folder . DS;
$glob = ['*', '*/*', '*/*/*'];
- $files = globBrace($name,$glob);
+ $files = globBrace($name, $glob);
if ($files) {
foreach ($files as $file) {
@@ -38,7 +46,7 @@ class CacheManager {
continue;
}
- if (! @unlink($file)) {
+ if (!@unlink($file)) {
clearstatcache(false, $file);
}
}
@@ -47,20 +55,45 @@ class CacheManager {
return true;
}
- public static function clearFrontend() {
+ /**
+ * Clear the frontend assets cache.
+ *
+ * @return bool Result of clearFolder.
+ */
+ public static function clearFrontend(): bool {
return self :: clearFolder('assets-cache');
}
- public static function clearModelCache() {
+ /**
+ * Clear the model cache files.
+ *
+ * @return bool Result of clearFolder.
+ */
+ public static function clearModelCache(): bool {
return self :: clearFolder('model' . DS . 'app', DIR_STORAGE) &&
self :: clearFolder('model' . DS . 'admin', DIR_STORAGE);
}
- public static function clearImageCache() {
+ /**
+ * Clear the image cache.
+ *
+ * @return bool Result of clearFolder.
+ */
+ public static function clearImageCache(): bool {
return self :: clearFolder('image-cache');
}
- public static function clearCompiledFiles($app = false, $site_id = false, $theme = false, $module = false) {
+ /**
+ * Clear compiled template files, optionally filtered by criteria.
+ *
+ * @param string|false $app App name filter.
+ * @param int|false $site_id Site ID filter.
+ * @param string|false $theme Theme filter.
+ * @param string|false $module Module filter.
+ *
+ * @return bool Always returns true.
+ */
+ public static function clearCompiledFiles(string|false $app = false, int|false $site_id = false, string|false $theme = false, string|false $module = false): bool {
$name = DIR_COMPILED_TEMPLATES;
if ($app) {
@@ -89,7 +122,7 @@ class CacheManager {
continue;
}
- if (! @unlink($file)) {
+ if (!@unlink($file)) {
clearstatcache(false, $file);
}
}
@@ -98,25 +131,52 @@ class CacheManager {
return true;
}
- public static function clearObjectCache($namespace = '', $key = null) {
+ /**
+ * Clear the object cache for a given namespace.
+ *
+ * @param string $namespace Cache namespace.
+ * @param string|false $key Specific key to delete, or false for entire namespace.
+ *
+ * @return bool Result of cache driver delete.
+ */
+ public static function clearObjectCache(string $namespace = '', string|false $key = false): bool {
$cacheDriver = Cache::getInstance();
return $cacheDriver->delete($namespace, $key);
}
- public static function clearPageCache($host = null, $path = '') {
+ /**
+ * Clear the page cache for a given host/path.
+ *
+ * @param string|null $host Hostname.
+ * @param string $path Relative path.
+ *
+ * @return bool Result of page cache purge.
+ */
+ public static function clearPageCache(?string $host = null, string $path = ''): bool {
$pageCache = new PageCache($host);
return $pageCache->purge($path);
}
- public static function delete($namespace = '') {
- self :: clearModelCache($namespace);
+ /**
+ * Clear all caches (model, object, frontend, compiled, page, opcache).
+ *
+ * @param string $namespace Optional namespace to scope the clear.
+ *
+ * @return bool Always returns true.
+ */
+ public static function delete(string $namespace = ''): bool {
+ self :: clearModelCache();
self :: clearObjectCache($namespace);
self :: clearFrontend();
self :: clearCompiledFiles($namespace);
self :: clearPageCache();
+ if (function_exists('opcache_reset')) {
+ @opcache_reset();
+ }
+
return true;
}
}
diff --git a/system/cache.php b/system/cache.php
index 8ea59a3..da5da3c 100755
--- a/system/cache.php
+++ b/system/cache.php
@@ -23,11 +23,21 @@
namespace Vvveb\System;
class Cache {
- private $driver;
+ /** @var object Cache driver instance. */
+ private object $driver;
- private $expire;
+ /** @var int Default cache expiry time in seconds. */
+ private int $expire;
- public static function getInstance() {
+ /** @var array<int|string, mixed> In-memory cache buffer. */
+ private array $buffer = [];
+
+ /**
+ * Get singleton instance of the Cache class.
+ *
+ * @return self
+ */
+ public static function getInstance(): self {
static $inst = null;
if ($inst === null) {
@@ -38,40 +48,81 @@ class Cache {
return $inst;
}
- public function __construct($driver, $expire = 3600) {
- $class = '\\Vvveb\\System\\Cache\\' . $driver;
+ /**
+ * Initialize the cache driver.
+ *
+ * @param string $driver Cache driver name.
+ * @param int $expire Default expiry time in seconds.
+ *
+ * @throws \Exception If the driver class does not exist.
+ *
+ * @return object The instantiated cache driver.
+ */
+ public function __construct(string $driver, int $expire = 3600) {
+ $class = '\Vvveb\System\Cache\\' . $driver;
$this->expire = $expire;
- if (class_exists($class)) {
- $options = \Vvveb\config(APP . '.cache', []);
- $this->driver = new $class($options);
- } else {
- throw new \Exception("Error loading cache driver '$driver'!");
- }
-
- return $this->driver;
+ //if (class_exists($class)) {
+ $options = \Vvveb\config(APP . '.cache', []);
+ $this->driver = new $class($options);
+ //} else {
+ //throw new \Exception("Error loading cache driver $driver!");
+ //}
}
- public function get($namespace, $key) {
- return $this->driver->get($namespace, $key);
+ /**
+ * Retrieve a cached value by namespace and key.
+ *
+ * @param string $namespace Cache namespace.
+ * @param string $key Cache key.
+ *
+ * @return mixed The cached value, or null if not found.
+ */
+ public function get(string $namespace, string $key): mixed {
+ return $this->buffer[$namespace][$key] ??
+ $this->buffer[$namespace][$key] = $this->driver->get($namespace, $key);
}
- public function set($namespace, $key, $value, $expire = 0) {
- $expire = $expire ?? $this->expire;
+ /**
+ * Store a value in the cache.
+ *
+ * @param string $namespace Cache namespace.
+ * @param string $key Cache key.
+ * @param mixed $value Value to store.
+ * @param int $expire Expiry time in seconds, 0 uses the default.
+ *
+ * @return bool True on success, false on failure.
+ */
+ public function set(string $namespace, string $key, mixed $value, int $expire = 0): bool {
+ $expire = $expire ?: $this->expire;
+
+ if (isset($this->buffer[$namespace][$key])) {
+ $this->buffer[$namespace][$key] = $value;
+ }
return $this->driver->set($namespace, $key, $value, $expire);
}
- // cache the results of the callback retrive if exists or save if expired
- public function cache($namespace, $key, $callback, $expire = 0) {
+ /**
+ * Cache the results of a callback. Returns the cached value if it exists,
+ * otherwise invokes the callback and stores the result.
+ *
+ * @param string $namespace Cache namespace.
+ * @param string $key Cache key.
+ * @param callable $callback Callback to invoke when cache misses.
+ * @param int $expire Expiry time in seconds, 0 uses the default.
+ *
+ * @return mixed The cached or freshly computed value.
+ */
+ public function cache(string $namespace, string $key, callable $callback, int $expire = 0): mixed {
if (($value = $this->driver->get($namespace, $key)) !== null) {
return $value;
}
$value = $callback();
- $expire = $expire ?? $this->expire;
+ $expire = $expire ?: $this->expire;
if ($this->driver->set($namespace, $key, $value, $expire)) {
}
@@ -79,21 +130,87 @@ class Cache {
return $value;
}
- public function getMulti($namespace, $key, $serverKey = false) {
- return $this->driver->getMulti($namespace, $key, $serverKey);
+ /**
+ * Retrieve multiple cached values by namespace and keys.
+ *
+ * @param string $namespace Cache namespace.
+ * @param array<int|string, string> $keys Array of cache keys.
+ * @param string|int|false $serverKey Optional server key for distributed caches.
+ *
+ * @return array<int|string, mixed> Associative array<array-key, mixed> of key => value pairs.
+ */
+ public function getMulti(string $namespace, array $keys, string|int|false $serverKey = false): array {
+ if (isset($this->buffer[$namespace])) {
+ $all = true;
+ $result = [];
+
+ foreach ($keys as $key) {
+ if (isset($this->buffer[$namespace][$key])) {
+ $result[$key] = $this->buffer[$namespace][$key];
+ } else {
+ $all = false;
+ break;
+ }
+ }
+
+ if ($all) {
+ return $result;
+ }
+ }
+
+ return $this->driver->getMulti($namespace, $keys, $serverKey);
}
- public function setMulti($namespace, $items, $expire = 0, $serverKey = false) {
- $expire = $expire ? $expire : $this->expire;
+ /**
+ * Store multiple values in the cache.
+ *
+ * @param string $namespace Cache namespace.
+ * @param array<int|string, mixed> $items Associative array of key => value pairs.
+ * @param int $expire Expiry time in seconds, 0 uses the default.
+ * @param string|int|false $serverKey Optional server key for distributed caches.
+ *
+ * @return bool True on success, false on failure.
+ */
+ public function setMulti(string $namespace, array $items, int $expire = 0, string|int|false $serverKey = false): bool {
+ $expire = $expire ?: $this->expire;
+
+ $this->buffer[$namespace] = ($this->buffer[$namespace] ?? []) + $items;
return $this->driver->setMulti($namespace, $items, $expire, $serverKey);
}
- public function delete($namespace, $key = '') {
+ /**
+ * Delete a cached value or an entire namespace from the cache.
+ *
+ * @param string $namespace Cache namespace.
+ * @param string|false $key Cache key to delete, or false to delete the entire namespace.
+ *
+ * @return bool True on success, false on failure.
+ */
+ public function delete(string $namespace, string|false $key = false): bool {
+ if ($key) {
+ unset($this->buffer[$namespace][$key]);
+ } else {
+ unset($this->buffer[$namespace]);
+ }
+
return $this->driver->delete($namespace, $key);
}
- public function purge($namespace = '') {
+ /**
+ * Purge all cached data for a namespace or the entire cache.
+ *
+ * @param string|null $namespace Cache namespace to purge, or null for all.
+ *
+ * @return bool True on success, false on failure.
+ */
+ public function purge(?string $namespace = null): bool {
+ if ($namespace) {
+ unset($this->buffer[$namespace]);
+ } else {
+ $this->buffer = [];
+ }
+
return $this->driver->delete($namespace);
}
}
diff --git a/system/cache/apcu.php b/system/cache/apcu.php
old mode 100755
new mode 100644
index ab2decf..87ff92d
--- a/system/cache/apcu.php
+++ b/system/cache/apcu.php
@@ -23,27 +23,50 @@
namespace Vvveb\System\Cache;
class APCu {
- private $expire = 0;
+ /** @var int Default cache lifetime in seconds. */
+ private int $expire = 0;
- private $options = [];
+ /** @var array<string, mixed> Configuration options merged with defaults. */
+ private array $options = [];
- private $active;
+ /** @var bool Whether APCu is available and enabled. */
+ private bool $active;
- private $cachePrefix = '';
+ /** @var string Cache key prefix (CRC32 of DIR_ROOT for shared-hosting isolation). */
+ private string $cachePrefix = '';
- public function __construct($options) {
+ /**
+ * @param array<string, mixed> $options Configuration options: expire (int).
+ */
+ public function __construct(array $options) {
$this->options += $options;
- $this->cachePrefix = crc32(DIR_ROOT); //unique instance for shared hosting
+ $this->cachePrefix = sprintf('%d', crc32(DIR_ROOT)); //unique instance for shared hosting
$this->expire = $this->options['expire'] ?? $this->expire;
$this->active = function_exists('apcu_cache_info') && ini_get('apc.enabled');
}
- private function key($namespace, $key = '') {
+ /**
+ * Build the full APCu cache key from namespace and key.
+ *
+ * @param string $namespace Cache namespace.
+ * @param string $key Cache key.
+ *
+ * @return string The composite cache key with directory separators replaced by dots.
+ */
+ private function key(string $namespace, string $key = ''): string {
return str_replace(['\\', '/'], '.', $this->cachePrefix . $namespace . '.' . $key);
}
- public function get($namespace, $key) {
+ /**
+ * Retrieve a cached value by namespace and key.
+ *
+ * @param string $namespace Cache namespace.
+ * @param string $key Cache key.
+ *
+ * @return mixed|null The cached value, or null if not found or APCu is inactive.
+ */
+ public function get(string $namespace, string $key): mixed {
$success = false;
$result = $this->active ? apcu_fetch($this->key($namespace, $key), $success) : null;
@@ -54,80 +77,115 @@ class APCu {
return null;
}
- public function set($namespace, $key, $value, $expire = null) {
- if (! $expire) {
+ /**
+ * Store a value in the APCu cache.
+ *
+ * @param string $namespace Cache namespace.
+ * @param string $key Cache key.
+ * @param mixed $value The value to cache.
+ * @param int|null $expire Lifetime in seconds, or null to use the default.
+ *
+ * @return bool True on success, false when APCu is inactive or storage failed.
+ */
+ public function set(string $namespace, string $key, mixed $value, ?int $expire = null): bool {
+ if (!$expire) {
$expire = $this->expire;
}
if ($this->active) {
- apcu_store($this->key($namespace, $key), $value, $expire);
+ return apcu_store($this->key($namespace, $key), $value, $expire);
}
+
+ return false;
}
- public function getMulti($namespace, $keys, $serverKey = false) {
- $result = [];
+ /**
+ * Retrieve multiple cached values by namespace.
+ *
+ * Missing keys map to null; never fails, even when APCu is inactive.
+ *
+ * @param string $namespace Cache namespace.
+ * @param array<int, string> $keys List of cache keys to retrieve.
+ * @param string|int|false $serverKey Unused (reserved for interface compatibility).
+ *
+ * @return array<string, mixed|null> Associative array<array-key, mixed> of originalKey => value.
+ */
+ public function getMulti(string $namespace, array $keys, string|int|false $serverKey = false): array {
$fullKeys = [];
- $success = false;
-
- foreach ($keys as &$key) {
- // simulate with single call version
- //$result[$key] = $this->get($namespace, $key);
- //add namespace
- $newKey = $this->key($namespace, $key);
- $fullKeys[$key] = $newKey;
- $key = $newKey;
+ foreach ($keys as $key) {
+ $fullKeys[$key] = $this->key($namespace, $key);
}
- $result = $this->active ? apcu_fetch($keys, $success) : null;
+ $fetched = $this->active ? apcu_fetch(array_values($fullKeys), $success) : false;
- if ($result) {
- foreach ($fullKeys as $key => &$fullKey) {
- $fullKeys[$key] = null;
+ if (!is_array($fetched)) {
+ $fetched = [];
+ }
- if ($fullKey && isset($result[$fullKey]) && $success) {
- $fullKeys[$key] = $fullKeys[$key];
- }
- }
+ $output = [];
- return $fullKeys;
+ foreach ($fullKeys as $key => $fullKey) {
+ $output[$key] = $fetched[$fullKey] ?? null;
}
- return $result;
+ return $output;
}
- public function setMulti($namespace, $items, $expire = null, $serverKey = false) {
+ /**
+ * Store multiple values in the APCu cache.
+ *
+ * @param string $namespace Cache namespace.
+ * @param array<string, mixed> $items Associative array of key => value pairs.
+ * @param int|null $expire Lifetime in seconds, or null to use the default.
+ * @param string|int|false $serverKey Unused (reserved for interface compatibility).
+ *
+ * @return bool True on success.
+ */
+ public function setMulti(string $namespace, array $items, ?int $expire = null, string|int|false $serverKey = false): bool {
foreach ($items as $key => $value) {
$this->set($namespace, $key, $value, $expire);
}
+
+ return true;
}
- public function delete($namespace, $key = '') {
+ /**
+ * Delete cached entries matching a namespace and optional key.
+ *
+ * When a key is provided, deletes matching entries via APCUIterator regex.
+ * When only a namespace is provided, deletes all entries in that namespace.
+ * When neither is provided, clears the entire APCu cache.
+ *
+ * @param string $namespace Cache namespace.
+ * @param string|false $key Cache key to delete, or false for all in namespace.
+ *
+ * @return bool True when entries were deleted or the whole cache was cleared, false when inactive.
+ */
+ public function delete(string $namespace, string|false $key = false): bool {
if ($this->active) {
if ($namespace) {
- if ($key) {
- return apcu_delete(new \APCUIterator('/' . $this->key($namespace, $key) . '.*/'));
-
- return apcu_delete($this->key($namespace, $key));
- } else {
- return apcu_delete(new \APCUIterator('/' . $this->key($namespace, $key) . '.*/'));
- $cache_info = apcu_cache_info();
-
- $cache_list = $cache_info['cache_list'];
-
- foreach ($cache_list as $entry) {
- if (strpos($entry['info'], $this->key($namespace, $key)) === 0) {
- apcu_delete($entry['info']);
- }
- }
- }
+ //anchor and quote the key: APCUIterator matches unanchored PCRE,
+ //so unescaped dots would also match sibling namespaces
+ apcu_delete(new \APCUIterator('/^' . preg_quote($this->key($namespace, $key ?: ''), '/') . '/'));
+
+ return true;
} else {
return apcu_clear_cache();
}
}
+
+ return false;
}
- public function purge($namespace = '') {
+ /**
+ * Purge the entire APCu cache.
+ *
+ * @param string $namespace Unused (kept for interface compatibility).
+ *
+ * @return bool True if the cache was cleared successfully, false otherwise.
+ */
+ public function purge(string $namespace = ''): bool {
$status = false;
if (function_exists('apcu_clear_cache')) {
diff --git a/system/cache/cache-trait.php b/system/cache/cache-trait.php
old mode 100755
new mode 100644
index 8ced487..8ac1a7b
--- a/system/cache/cache-trait.php
+++ b/system/cache/cache-trait.php
@@ -23,7 +23,14 @@
namespace Vvveb\System\Cache;
trait CacheTrait {
- public function stats($time = false) {
+ /**
+ * Get cache statistics for files matching the current cache prefix.
+ *
+ * @param bool|int $time If numeric, used as expiry threshold in seconds.
+ *
+ * @return array{curr_items: int, total_items: int, bytes: int}|null Returns stats array<array-key, mixed>, or null if no files found.
+ */
+ public function stats(bool|int $time = false): ?array {
$stats = [
'curr_items' => 0,
'total_items' => 0,
@@ -33,29 +40,39 @@ trait CacheTrait {
if ($files) {
foreach ($files as $file) {
- $filename = basename($file);
$stats['total_items']++;
- $stats['bytes'] += filesize($file);
+ //suppress warnings for files removed between glob() and filesize()
+ $stats['bytes'] += @filesize($file) ?: 0;
- $time = (int)substr(strrchr($file, '.'), 1);
+ $fileTime = filemtime($file);
- if (time() - $time > $time) {
+ if ($fileTime && (time() - $fileTime > $time)) {
$stats['curr_items']++;
}
}
}
+
+ return $stats;
}
- public function delete($namespace = false, $time_delay = 0) {
+ /**
+ * Delete expired cache files matching the namespace.
+ *
+ * @param string|false $namespace Cache namespace to filter by, or false for all.
+ * @param int $time_delay Minimum age in seconds before a file is considered expired.
+ *
+ * @return void
+ */
+ public function delete(string|false $namespace = false, int $time_delay = 0): void {
$files = glob($this->cacheDir . $this->cachePrefix . '*');
if ($files) {
foreach ($files as $file) {
$filename = basename($file);
- $time = (int)substr(strrchr($file, '.'), 1);
+ $fileTime = (int)substr(strrchr($file, '.'), 1);
- if (time() - $time > $time) {
+ if (time() - $fileTime > $time_delay) {
$this->delete(substr($filename, 6, strrpos($filename, '.') - 6));
}
}
diff --git a/system/cache/file.php b/system/cache/file.php
index db5396b..50edff1 100755
--- a/system/cache/file.php
+++ b/system/cache/file.php
@@ -24,19 +24,41 @@ namespace Vvveb\System\Cache;
use function Vvveb\sanitizeFileName;
+/**
+ * File-system-based cache driver.
+ *
+ * Stores cached values as JSON-encoded files in a configurable directory.
+ * Each file is named by namespace, optional prefix, and key. Supports
+ * namespace/key validation, multi-get/set, expired-file purging, and
+ * exclusive file locking for concurrent writes.
+ */
class File {
- /* get purge, stats from trait*/
+ // CacheTrait provides stats() and a base delete() implementation.
use CacheTrait;
- private $expire = 3600;
-
- private $options = [];
-
- private $cacheDir = DIR_CACHE;
-
- private $cachePrefix = ''; //'cache.';
-
- public function __construct($options) {
+ /** @var int Default cache lifetime in seconds. */
+ private int $expire = 3600;
+
+ /** @var array<string, mixed> Configuration options merged in the constructor. */
+ private array $options = [];
+
+ /** @var string Absolute path to the cache directory. */
+ private string $cacheDir = DIR_CACHE;
+
+ /** @var string Optional prefix prepended to cache filenames. */
+ private string $cachePrefix = ''; //'cache.';
+
+ /**
+ * Initialize cache settings from the provided options array.
+ *
+ * Supported keys:
+ * - expire (int) Default TTL in seconds (default 3600).
+ * - dir (string) Absolute path to the cache directory.
+ * - prefix (string) Filename prefix for cache files.
+ *
+ * @param array<string, mixed> $options Configuration overrides.
+ */
+ public function __construct(array $options) {
$this->options += $options;
$this->expire = $this->options['expire'] ?? $this->expire;
@@ -44,42 +66,91 @@ class File {
$this->cachePrefix = $this->options['prefix'] ?? $this->cachePrefix;
}
- protected function validateNamespace($namespace) {
+ /**
+ * Sanitise a namespace or key string for use as part of a filename.
+ *
+ * Replaces directory separators with dots and applies the global
+ * sanitizeFileName filter. Empty values are returned as-is.
+ *
+ * @param string $namespace Raw namespace or key value.
+ *
+ * @return string Sanitised filename-safe string, or empty string if input was falsy.
+ */
+ protected function validateNamespace(string $namespace): string {
if ($namespace) {
- $namespace = str_replace(['\\', '/'] , '.', $namespace);
+ $namespace = str_replace(['\\', '/'], '.', $namespace);
$namespace = sanitizeFileName($namespace);
}
return $namespace;
}
- public function get($namespace, $key) {
+ /**
+ * Retrieve a single cached value.
+ *
+ * Looks up the file for the given namespace and key, reads its contents,
+ * and returns the JSON-decoded data.
+ *
+ * Entries store their expiry timestamp as the file modification time,
+ * so expired entries return null without needing a purge pass first.
+ *
+ * @param string $namespace Cache namespace.
+ * @param string $key Cache key.
+ *
+ * @return mixed|null The decoded cache value, or null if the file does not exist or has expired.
+ */
+ public function get(string $namespace, string $key): mixed {
$namespace = $this->validateNamespace($namespace);
$key = $this->validateNamespace($key);
$file = $this->cacheDir . $namespace . '.' . $this->cachePrefix . basename($key);
+
if (file_exists($file)) {
- $data = file_get_contents($file);
+ //mtime holds the expiry timestamp, fail closed when it cannot be read
+ if ((@filemtime($file) ?: 0) <= time()) {
+ return null;
+ }
+
+ $data = @file_get_contents($file);
+
+ if ($data === false) {
+ return null;
+ }
+
return json_decode($data, true);
}
return null;
}
- public function set($namespace, $key, $value, $expire = null) {
+ /**
+ * Store a value in the file cache.
+ *
+ * The value is JSON-encoded and written with exclusive file locking
+ * (LOCK_EX). The file's modification time is set to the expiry timestamp
+ * so that get() and purgeExpired() can detect stale entries.
+ *
+ * @param string $namespace Cache namespace.
+ * @param string $key Cache key.
+ * @param mixed $value The value to cache (will be JSON-encoded).
+ * @param int|null $expire Lifetime in seconds, null to use the default.
+ * Zero or negative values expire immediately.
+ *
+ * @return bool True on success, false if the file could not be opened for writing.
+ */
+ public function set(string $namespace, string $key, mixed $value, ?int $expire = null): bool {
$namespace = $this->validateNamespace($namespace);
$key = $this->validateNamespace($key);
- if (! $expire) {
+ if ($expire === null) {
$expire = $this->expire;
}
$expire = time() + $expire;
//$this->delete($namespace, $key);
$file = $this->cacheDir . $namespace . '.' . $this->cachePrefix . basename($key);
- touch($file, $expire);
- $handle = fopen($file, 'w');
+ $handle = @fopen($file, 'w');
if ($handle) {
flock($handle, LOCK_EX);
@@ -87,10 +158,26 @@ class File {
fflush($handle);
flock($handle, LOCK_UN);
fclose($handle);
+ //set mtime to expiry timestamp so purgeExpired() can detect stale entries
+ //must be done after fclose, otherwise fopen('w') resets mtime to current time
+ @touch($file, $expire);
+
+ return true;
}
+
+ return false;
}
- public function getMulti($namespace, $keys, $serverKey = false) {
+ /**
+ * Retrieve multiple cached values by namespace.
+ *
+ * @param string $namespace Cache namespace.
+ * @param array<int, string> $keys List of cache keys to retrieve.
+ * @param string|int|false $serverKey Unused (reserved for interface compatibility).
+ *
+ * @return array<string, mixed|null> Associative array<array-key, mixed> of key => value pairs.
+ */
+ public function getMulti(string $namespace, array $keys, string|int|false $serverKey = false): array {
$result = [];
foreach ($keys as $key) {
@@ -100,19 +187,56 @@ class File {
return $result;
}
- public function setMulti($namespace, $items, $expire = null, $serverKey = false) {
+ /**
+ * Store multiple values in the file cache.
+ *
+ * @param string $namespace Cache namespace.
+ * @param array<string, mixed> $items Associative array of key => value pairs.
+ * @param int|null $expire Lifetime in seconds, or null to use the default.
+ * @param string|int|false $serverKey Unused (reserved for interface compatibility).
+ *
+ * @return bool Always returns true.
+ */
+ public function setMulti(string $namespace, array $items, ?int $expire = null, string|int|false $serverKey = false): bool {
$namespace = $this->validateNamespace($namespace);
foreach ($items as $key => $value) {
$this->set($namespace, $key, $value, $expire);
}
+
+ return true;
}
- public function purge($namespace = '') {
+ /**
+ * Purge cache entries by deleting matching files.
+ *
+ * Alias for {@see delete()}.
+ *
+ * @param string $namespace Cache namespace to purge, or empty string for all.
+ *
+ * @return bool True if all files were deleted successfully, false otherwise.
+ */
+ public function purge(string $namespace = ''): bool {
$this->delete($namespace);
+
+ return true;
}
- public function delete($namespace, $key = false) {
+ /**
+ * Delete cached entries matching a namespace and optional key.
+ *
+ * When a key is provided, deletes that specific cache file. When only a
+ * namespace is provided, deletes all files in that namespace. When neither
+ * is provided, deletes all cache files in the cache directory.
+ *
+ * Hidden files are never matched (glob('*') excludes dotfiles).
+ *
+ * @param string $namespace Cache namespace, or empty string for all.
+ * @param string|false $key Specific cache key to delete, or false for all in namespace.
+ *
+ * @return bool True if all files were deleted successfully, false if any deletion failed.
+ */
+ public function delete(string $namespace, string|false $key = false): bool {
$namespace = $this->validateNamespace($namespace);
$name = $this->cacheDir;
@@ -127,43 +251,70 @@ class File {
$name .= '*';
}
- $files = glob($name);
+ $files = glob($name);
+ $success = true;
if ($files) {
foreach ($files as $file) {
- if ($file[0] === '.') {
- continue;
- }
-
- if (! @unlink($file)) {
- //clearstatcache(false, $file);
+ if (!@unlink($file)) {
+ $success = false;
}
}
}
+
+ return $success;
}
- public function purgeExpired() {
+ /**
+ * Remove all expired cache files from the cache directory.
+ *
+ * Files store their expiry timestamp as modification time (see set()),
+ * so a file is purged once it has been expired for longer than $expired
+ * seconds. Pass 0 to remove everything that is already expired.
+ * Hidden files (starting with a dot) are skipped.
+ *
+ * @param int $expired Grace period in seconds after expiry before removal.
+ *
+ * @return void
+ */
+ public function purgeExpired(int $expired = 86400): void {
+ //the directory may not exist yet on fresh installs or custom paths
+ if (!is_dir($this->cacheDir)) {
+ return;
+ }
+
if ($files = (scandir($this->cacheDir))) {
+ ignore_user_abort(true);
+
foreach ($files as $file) {
- if ($file[0] == '.') {
+ if ($file[0] === '.') {
continue;
}
+ $file = $this->cacheDir . $file;
+
if (file_exists($file)) {
$time = filemtime($file);
- if ($time < time()) {
- if (! @unlink($file)) {
- clearstatcache(false, $file);
- }
+ if (($time + $expired) < time()) {
+ @unlink($file);
}
}
}
}
}
+ /**
+ * Randomly trigger expired-cache cleanup on object destruction.
+ *
+ * There is a 1-in-1000 chance that purgeExpired() is called each time
+ * a File cache instance is destroyed, providing probabilistic garbage
+ * collection without requiring a cron job.
+ *
+ * @return void
+ */
public function __destruct() {
- if (rand(1, 1000) == 1) {
+ if (random_int(1, 1000) === 1) {
$this->purgeExpired();
}
}
diff --git a/system/cache/memcached.php b/system/cache/memcached.php
index dbb5e1d..9a5c246 100755
--- a/system/cache/memcached.php
+++ b/system/cache/memcached.php
@@ -23,31 +23,45 @@
namespace Vvveb\System\Cache;
class Memcached {
- private $expire;
-
- private $memcached;
-
- private $cachePrefix = '';
-
- public function stats($time = false) {
- $stats = $this->memcached->getStats();
- /*
- [curr_items] => 0
- [total_items] => 0
- [bytes] => 0
- */
- return $stats;
+ /** @var \Memcached The underlying Memcached connection instance. */
+ private \Memcached $memcached;
+
+ /** @var string Cache key prefix (CRC32 of DIR_ROOT for shared-hosting isolation). */
+ private string $cachePrefix = '';
+
+ /**
+ * Get Memcached server statistics.
+ *
+ * @param bool|int $time Unused (kept for interface compatibility).
+ *
+ * @return array<string, mixed> Server statistics.
+ */
+ public function stats(bool|int $time = false): array {
+ return $this->memcached->getStats();
}
- public function purge($namespace = false, $time_delay = 0) {
+ /**
+ * Purge (flush) the entire Memcached cache.
+ *
+ * @param string|false $namespace Unused (kept for interface compatibility).
+ * @param int $time_delay Delay in seconds before the flush takes effect.
+ *
+ * @return bool True on success, false on failure.
+ */
+ public function purge(string|false $namespace = false, int $time_delay = 0): bool {
return $this->memcached->flush($time_delay);
}
- public function __construct($options) {
- //$this->expire = $expire;
+ /**
+ * @param array<string, mixed> $options Configuration options: servers (array), options (array).
+ */
+ public function __construct(array $options) {
+ if (empty($options['servers'])) {
+ throw new \InvalidArgumentException('Memcached cache requires a servers option');
+ }
- $this->cachePrefix = crc32(DIR_ROOT); //unique instance for shared hosting
- $this->memcached = new \Memcached();
+ $this->cachePrefix = sprintf('%d', crc32(DIR_ROOT)); //unique instance for shared hosting
+ $this->memcached = new \Memcached();
$this->memcached->addServers($options['servers']);
if (isset($options['options'])) {
@@ -55,39 +69,135 @@ class Memcached {
$this->memcached->setOption($key, $value);
}
}
-
- return $this->memcached;
}
- private function key($namespace, $key = '') {
+ /**
+ * Build the full cache key from namespace and key.
+ *
+ * @param string $namespace Cache namespace.
+ * @param string $key Cache key.
+ *
+ * @return string The composite cache key.
+ */
+ private function key(string $namespace, string $key = ''): string {
return $this->cachePrefix . ($namespace ? ".$namespace" : '') . $key;
}
- public function get($namespace, $key) {
+ /**
+ * Retrieve a cached value by namespace and key.
+ *
+ * @param string $namespace Cache namespace.
+ * @param string $key Cache key.
+ *
+ * @return mixed The cached value, or false on failure.
+ */
+ public function get(string $namespace, string $key): mixed {
return $this->memcached->get($this->key($namespace, $key));
}
- public function set($namespace, $key, $value, $expire = 0) {
+ /**
+ * Store a value in the Memcached cache.
+ *
+ * @param string $namespace Cache namespace.
+ * @param string $key Cache key.
+ * @param mixed $value The value to cache.
+ * @param int $expire Lifetime in seconds, or 0 for no expiry.
+ *
+ * @return bool True on success, false on failure.
+ */
+ public function set(string $namespace, string $key, mixed $value, int $expire = 0): bool {
return $this->memcached->set($this->key($namespace, $key), $value, $expire);
}
- public function getMulti($namespace, $keys, $serverKey = false) {
+ /**
+ * Retrieve multiple cached values by namespace.
+ *
+ * @param string $namespace Cache namespace.
+ * @param array<int, string> $keys List of cache keys to retrieve.
+ * @param string|int|false $serverKey Server key for consistent hashing, or false for default.
+ *
+ * @return array<string, mixed> Associative array<array-key, mixed> of key => value pairs.
+ */
+ public function getMulti(string $namespace, array $keys, string|int|false $serverKey = false): array {
+ $prefixed = [];
+ $map = [];
+
+ foreach ($keys as $key) {
+ $pkey = $this->key($namespace, $key);
+ $prefixed[] = $pkey;
+ $map[$pkey] = $key;
+ }
+
if ($serverKey) {
- return $this->memcached->getMultiByKey($serverKey, $keys);
+ $result = $this->memcached->getMultiByKey($serverKey, $prefixed);
} else {
- return $this->memcached->getMulti($keys);
+ $result = $this->memcached->getMulti($prefixed);
}
+
+ $output = [];
+
+ foreach ($map as $pkey => $origKey) {
+ $output[$origKey] = $result[$pkey] ?? null;
+ }
+
+ return $output;
}
- public function setMulti($namespace, $items, $expire = 0, $serverKey = false) {
+ /**
+ * Store multiple values in the Memcached cache.
+ *
+ * @param string $namespace Cache namespace.
+ * @param array<string, mixed> $items Associative array of key => value pairs.
+ * @param int $expire Lifetime in seconds, or 0 for no expiry.
+ * @param string|int|false $serverKey Server key for consistent hashing, or false for default.
+ *
+ * @return bool True on success, false on failure.
+ */
+ public function setMulti(string $namespace, array $items, int $expire = 0, string|int|false $serverKey = false): bool {
+ $prefixed = [];
+
+ foreach ($items as $key => $value) {
+ $prefixed[$this->key($namespace, $key)] = $value;
+ }
+
if ($serverKey) {
- return $this->memcached->setMulti($items, $expire);
+ return $this->memcached->setMultiByKey($serverKey, $prefixed, $expire);
} else {
- return $this->memcached->setMultiByKey($serverKey, $items, $expire);
+ return $this->memcached->setMulti($prefixed, $expire);
}
}
- public function delete($namespace, $key) {
- $this->memcached->delete($this->key($namespace, $key));
+ /**
+ * Delete cached entries matching a namespace and optional key.
+ *
+ * Memcached has no wildcard delete, so namespace deletes list all keys
+ * and remove the ones under the namespace prefix.
+ *
+ * @param string $namespace Cache namespace, or empty string for all entries.
+ * @param string|false $key Cache key to delete, or false for all in namespace.
+ *
+ * @return bool True on success, false on failure.
+ */
+ public function delete(string $namespace, string|false $key = false): bool {
+ if ($key) {
+ return (bool)$this->memcached->delete($this->key($namespace, $key));
+ }
+
+ $allKeys = $this->memcached->getAllKeys();
+
+ if (!is_array($allKeys)) {
+ return false;
+ }
+
+ $prefix = $this->key($namespace);
+ $matched = array_values(array_filter($allKeys, fn ($k) => str_starts_with((string)$k, $prefix)));
+
+ if ($matched === []) {
+ return true;
+ }
+
+ $result = $this->memcached->deleteMulti($matched);
+
+ return !in_array(false, $result, true);
}
}
diff --git a/system/cache/redis.php b/system/cache/redis.php
old mode 100755
new mode 100644
index 1e016b7..3e0f4f7
--- a/system/cache/redis.php
+++ b/system/cache/redis.php
@@ -23,50 +23,101 @@
namespace Vvveb\System\Cache;
class Redis {
- private $expire;
+ /** @var int Default cache lifetime in seconds. */
+ private int $expire = 0;
- private $redis;
+ /** @var \Redis The underlying Redis connection instance. */
+ private \Redis $redis;
- private $cachePrefix = ''; //'cache.';
+ /** @var string Cache key prefix. */
+ private string $cachePrefix = ''; //'cache.';
- private $options = ['expire' => 3000, 'prefix' => 'vvveb.'];
+ /** @var array<string, mixed> Default configuration options. */
+ private array $options = ['expire' => 3000, 'prefix' => 'vvveb.'];
- public function __construct($options) {
- $this->options += $options;
+ /**
+ * @param array<string, mixed> $options Configuration options: host (string), port (int),
+ * password (string, optional), expire (int), prefix (string).
+ */
+ public function __construct(array $options) {
+ //user options take precedence over the defaults
+ $this->options = $options + $this->options;
- $this->cachePrefix = crc32(DIR_ROOT); //unique instance for shared hosting
$this->expire = $this->options['expire'] ?? $this->expire;
$this->cachePrefix = $this->options['prefix'] ?? $this->cachePrefix;
+ if (empty($this->options['host'])) {
+ throw new \InvalidArgumentException('Redis cache requires a host option');
+ }
+
$this->redis = new \Redis();
- $this->redis->pconnect($this->options['host'], $this->options['port']);
+ $this->redis->pconnect($this->options['host'], $this->options['port'] ?? 6379);
if (isset($this->options['password'])) {
$this->redis->auth($this->options['password']);
}
}
- private function key($namespace, $key = '') {
+ /**
+ * Build the full cache key from namespace and key.
+ *
+ * @param string $namespace Cache namespace.
+ * @param string $key Cache key.
+ *
+ * @return string The composite cache key.
+ */
+ private function key(string $namespace, string $key = ''): string {
return $this->cachePrefix . ($namespace ? ".$namespace" : '') . $key;
}
- public function get($namespace, $key) {
+ /**
+ * Retrieve a cached value by namespace and key.
+ *
+ * @param string $namespace Cache namespace.
+ * @param string $key Cache key.
+ *
+ * @return mixed|null The decoded cached value, or null if not found.
+ */
+ public function get(string $namespace, string $key): mixed {
$data = $this->redis->get($this->key($namespace, $key));
return json_decode($data, true);
}
- public function set($namespace, $key, $value, $expire = null) {
- $expire = $expire ?? $this->expire;
+ /**
+ * Store a value in the Redis cache.
+ *
+ * Values are JSON-encoded before storage. If an expiry is specified,
+ * a TTL is set on the key after writing.
+ *
+ * @param string $namespace Cache namespace.
+ * @param string $key Cache key.
+ * @param mixed $value The value to cache (will be JSON-encoded).
+ * @param int|null $expire Lifetime in seconds, or null to use the default.
+ *
+ * @return bool True on success, false on failure.
+ */
+ public function set(string $namespace, string $key, mixed $value, ?int $expire = null): bool {
+ $expire ??= $this->expire;
$_key = $this->key($namespace, $key);
- $status = $this->redis->set($_key, json_encode($value));
- if ($status && $expire) {
- $this->redis->expire($_key, $expire);
+ if ($expire) {
+ return (bool)$this->redis->set($_key, json_encode($value), ['ex' => $expire]);
}
+
+ return (bool)$this->redis->set($_key, json_encode($value));
}
- public function getMulti($namespace, $keys, $serverKey = false) {
+ /**
+ * Retrieve multiple cached values by namespace.
+ *
+ * @param string $namespace Cache namespace.
+ * @param array<int, string> $keys List of cache keys to retrieve.
+ * @param string|int|false $serverKey Unused (reserved for interface compatibility).
+ *
+ * @return array<string, mixed|null> Associative array<array-key, mixed> of key => value pairs.
+ */
+ public function getMulti(string $namespace, array $keys, string|int|false $serverKey = false): array {
$result = [];
foreach ($keys as $key) {
@@ -76,26 +127,56 @@ class Redis {
return $result;
}
- public function setMulti($namespace, $items, $expire = null, $serverKey = false) {
- $expire = $expire ?? $this->expire;
+ /**
+ * Store multiple values in the Redis cache.
+ *
+ * @param string $namespace Cache namespace.
+ * @param array<string, mixed> $items Associative array of key => value pairs.
+ * @param int|null $expire Lifetime in seconds, or null to use the default.
+ * @param string|int|false $serverKey Unused (reserved for interface compatibility).
+ *
+ * @return bool True on success, false on failure.
+ */
+ public function setMulti(string $namespace, array $items, ?int $expire = null, string|int|false $serverKey = false): bool {
+ $expire ??= $this->expire;
+ $status = true;
foreach ($items as $key => $value) {
- $this->set($namespace, $key, $value, $expire);
+ $status = $this->set($namespace, $key, $value, $expire) && $status;
}
+
+ return $status;
}
- public function delete($namespace, $key) {
+ /**
+ * Delete cached entries matching a namespace and optional key.
+ *
+ * When a key is provided, deletes that specific entry. When only a namespace
+ * is provided, uses a wildcard pattern to delete all entries in that namespace.
+ * When neither is provided, deletes all cached entries.
+ *
+ * @param string $namespace Cache namespace.
+ * @param string|false $key Cache key to delete, or false to delete all in namespace.
+ *
+ * @return bool Always returns true.
+ */
+ public function delete(string $namespace, string|false $key = false): bool {
if ($key) {
- $keys = $this->key($namespace, $key);
+ $this->redis->del($this->key($namespace, $key));
} else {
- if ($namespace) {
- $keys = $this->key($namespace, '*');
- } else {
- $keys = $this->key('*');
- }
- }
+ $pattern = $namespace ? $this->key($namespace, '*') : $this->key('*');
+
+ //non-blocking iteration, unlike KEYS which blocks the server
+ $iterator = null;
- $this->redis->del($keys);
+ do {
+ $keys = $this->redis->scan($iterator, $pattern);
+
+ if ($keys) {
+ $this->redis->del($keys);
+ }
+ } while ($iterator);
+ }
return true;
}
diff --git a/system/cart/cart.php b/system/cart/cart.php
index a1aae36..38879b0 100755
--- a/system/cart/cart.php
+++ b/system/cart/cart.php
@@ -22,78 +22,93 @@
namespace Vvveb\System\Cart;
-use function \Vvveb\model;
-use function \Vvveb\url;
-use Vvveb\Sql\Product_Option_ValueSQL;
-use Vvveb\Sql\Product_VariantSQL;
-use Vvveb\Sql\ProductSQL;
-use Vvveb\Sql\Subscription_PlanSQL;
+use function Vvveb\model;
+use Vvveb\Sql\Product_option_valueSQL;
+use Vvveb\Sql\Product_variantSQL;
+use Vvveb\Sql\Subscription_planSQL;
use Vvveb\System\Images;
use Vvveb\System\Locale;
use Vvveb\System\Session;
+use function Vvveb\url;
class Cart {
- protected $cart = [];
+ use CouponTrait;
+ use DbTrait;
+ use ProductOptionTrait;
+ use TaxTrait;
+ use TotalTrait;
+ /** @var array<string, mixed> */
+ protected array $cart = [];
- protected $session;
+ protected \Vvveb\System\Session $session;
- protected $currency;
+ protected Currency $currency;
- protected $tax;
+ protected Tax $tax;
- protected $weight;
+ protected Weight $weight;
- protected $productModel = 'product';
+ protected string $productModel = 'product';
- protected $cart_id;
+ /** @var int|string|null */
+ protected int|string|null $cart_id = null;
- protected $encrypted_cart_id;
+ /** @var string|null */
+ protected ?string $encrypted_cart_id = null;
- protected $sessionKey = 'cart';
+ protected string $sessionKey = 'cart';
- protected $persist = 'session';
+ protected string $persist = 'session';
- protected $options;
+ /** @var array<string, mixed> */
+ protected array $options = [];
- protected $products = [];
+ /** @var array<string, mixed> */
+ protected array $products = [];
- protected $taxes = [];
+ /** @var array<string, mixed> */
+ protected array $taxes = [];
- protected $totals = [];
+ /** @var array<string, mixed> */
+ protected array $totals = [];
- protected $total = 0;
+ protected float|int $total = 0;
- protected $total_tax = 0;
+ protected float|int $total_tax = 0;
- protected $total_items = 0;
+ protected int $total_items = 0;
- protected $controlCache = true;
-
- protected $hasChanges = false;
+ protected bool $controlCache = true;
- use TaxTrait, ProductOptionTrait, CouponTrait, TotalTrait, DbTrait;
+ protected bool $hasChanges = false;
- public static function getInstance($options = []) {
- static $inst = null;
+ /**
+ * @param array<string, mixed> $options
+ */
+ public static function getInstance(array $options = []): static {
+ static $inst;
if ($inst === null) {
- $inst = new Cart($options);
+ $inst = new self($options);
}
return $inst;
}
- private function __construct($options = []) {
- $this->session = Session :: getInstance();
- $this->currency = Currency :: getInstance($options);
- $this->tax = Tax :: getInstance();
- $this->weight = Weight :: getInstance();
+ /**
+ * @param array<string, mixed> $options
+ */
+ private function __construct(array $options = []) {
+ $this->session = Session::getInstance();
+ $this->currency = Currency::getInstance($options);
+ $this->tax = Tax::getInstance();
+ $this->weight = Weight::getInstance();
$this->options = $options;
$this->cart_id = $options['cart_id'] ?? null;
$this->encrypted_cart_id = $options['encrypted_cart_id'] ?? null;
- if ($this->encrypted_cart_id || ($this->cart_id && ! is_numeric($this->cart_id))) {
+ if ($this->encrypted_cart_id || ($this->cart_id && !is_numeric($this->cart_id))) {
$cart_id = urldecode($this->encrypted_cart_id ?? $this->cart_id);
$key = \Vvveb\getConfig('app.key');
$cart_id = \Vvveb\decrypt($key, $cart_id);
@@ -106,18 +121,6 @@ class Cart {
$this->read();
- if (! isset($this->total_items)) {
- $this->total_items = 0;
- }
-
- if (! isset($this->total)) {
- $this->total = 0;
- }
-
- if (! isset($this->products)) {
- $this->products = [];
- }
-
if ($this->total_items) {
$this->disableCache();
} else {
@@ -125,14 +128,26 @@ class Cart {
}
}
- public function create() {
- //call only if you need a cart id beforehand, otherwise a cart will be created automatically when adding a product if it does not exist
+ /**
+ * Create a new cart and return its ID.
+ *
+ * Call only if you need a cart id beforehand, otherwise a cart will be
+ * created automatically when adding a product if it does not exist.
+ */
+ public function create(): int|string|null {
$this->write();
return $this->cart_id;
}
- public function setEncryptedId($encrypted_cart_id) {
+ /**
+ * Set the encrypted cart id and decrypt it to retrieve the real cart id.
+ *
+ * @param string $encrypted_cart_id
+ *
+ * @return int|string|null
+ */
+ public function setEncryptedId(string $encrypted_cart_id): int|string|null {
$encrypted_cart_id = urldecode($encrypted_cart_id);
$key = \Vvveb\getConfig('app.key');
$cart_id = \Vvveb\decrypt($key, $encrypted_cart_id);
@@ -145,7 +160,10 @@ class Cart {
return $cart_id;
}
- public function getEncryptedId() {
+ /**
+ * Get the encrypted version of the cart id.
+ */
+ public function getEncryptedId(): string {
if ($this->encrypted_cart_id) {
return $this->encrypted_cart_id;
}
@@ -156,118 +174,71 @@ class Cart {
return $this->encrypted_cart_id;
}
- public function getCartUrl() {
+ /**
+ * Build a URL for the cart view page.
+ */
+ public function getCartUrl(): string {
$id = urlencode($this->getEncryptedId());
$url = url('cart/cart/index', ['cart_id' => $id]);
//app does not have url
- if (! $url) {
+ if (!$url) {
$url = "/checkout/$id";
}
return $url;
}
- public function getCheckoutUrl() {
+ /**
+ * Build a URL for the checkout page.
+ */
+ public function getCheckoutUrl(): string {
$id = urlencode($this->getEncryptedId());
$url = url('checkout/checkout/index', ['cart_id' => $id]);
//app does not have url
- if (! $url) {
+ if (!$url) {
$url = "/checkout/$id";
}
return $url;
}
- public function getId() {
+ /**
+ * Get the raw cart id.
+ */
+ public function getId(): int|string|null {
return $this->cart_id;
}
- public function updateCart() {
+ /**
+ * Recalculate all cart totals, prices, taxes and product data.
+ *
+ * @return array{products: array<int|string, mixed>, count: int}
+ */
+ public function updateCart(): array {
$this->total = 0;
$this->total_items = 0;
+ $this->tax->taxPrecision = $this->currency->getDecimalPlace();
+
$results = ['products' => [], 'count' => 0];
$currency = Locale::getCurrency();
- if (! empty($this->products)) {
- $productIds = [];
- $productOptions = [];
- $productVariants = [];
- $productSubscriptions = [];
-
- foreach ($this->products as $product) {
- $productId = $product['product_id'];
- $productIds[$productId] = $productId;
-
- //get all product options to make one query to get all option values
- if (isset($product['option']) && is_array($product['option'])) {
- foreach ($product['option'] as $value) {
- if (is_numeric($value)) {
- $productOptions[$value] = $value;
- } else {
- if (isset($value['product_option_value_id'])) {
- $product_option_value_id = $value['product_option_value_id'];
- $productOptions[$product_option_value_id] = $product_option_value_id;
- }
- }
- }
- }
-
- if (isset($product['subscription_plan_id']) && $product['subscription_plan_id']) {
- $productSubscriptions[$product['subscription_plan_id']] = $product['subscription_plan_id'];
- }
-
- if (isset($product['product_variant_id']) && $product['product_variant_id']) {
- $productVariants[$product['product_variant_id']] = $product['product_variant_id'];
- }
- }
-
- //get product data from db for products in cart
- $options = [
- 'product_id' => $productIds,
- ] + $this->options;
-
- $productSql = model($this->productModel); //new ProductSQL();
- $results = $productSql->getAll(
- $options
- );
-
- // if products have options get all product options in one query
- $optionResults = [];
-
- if ($productOptions) {
- $productOptionValueSql = new Product_Option_ValueSQL();
- $optionResults = $productOptionValueSql->getAll(
- ['product_option_value_id' => array_values($productOptions)] + $this->options
- )['product_option_value'] ?? [];
- }
-
- // if products have subscriptions get all subscriptions in one query
- $subscriptionResults = [];
-
- if ($productSubscriptions) {
- $subscriptionPlanSql = new Subscription_PlanSQL();
- $subscriptionResults = $subscriptionPlanSql->getAll(
- ['subscription_plan_id' => array_values($productSubscriptions)] + $this->options
- )['subscription_plan'] ?? [];
- }
-
- // if products have variants get all variants in one query
- $variantsResults = [];
-
- if ($productVariants) {
- $productVariantSql = new Product_VariantSQL();
- $variantsResults = $productVariantSql->getAll(
- ['product_variant_id' => array_values($productVariants)] + $this->options
- )['product_variant'] ?? [];
- }
+ $refs = $this->collectProductReferences();
+ if ($refs['productIds']) {
+ $data = $this->loadCartProductData($refs);
+ } else {
+ $data = ['results' => $results, 'optionResults' => [], 'subscriptionResults' => [], 'variantsResults' => []];
}
- $products = $results['product'] ?? [];
+ $results = $data['results'];
+ $optionResults = $data['optionResults'];
+ $subscriptionResults = $data['subscriptionResults'];
+ $variantsResults = $data['variantsResults'];
+ $products = $results['product'] ?? [];
if ($products) {
foreach ($this->products as $key => &$prod) {
- if (! isset($products[$product['product_id']])) {
+ if (!isset($products[$prod['product_id']])) {
unset($this->products[$key]);
continue;
@@ -276,77 +247,20 @@ class Cart {
$productId = $prod['product_id'];
$product = $products[$productId];
- $prod['price'] = (float)$product['price'];
+ $prod['price'] = (float)$product['price'];
+ $prod['weight'] = (float)$product['weight'];
//add option value data and adjust price if necessary
- if (isset($prod['option']) && is_array($prod['option'])) {
- foreach ($prod['option'] as $option_id => $option) {
- if (is_numeric($option)) {
- $product_option_value_id = $option;
- } else {
- if (isset($option['product_option_value_id'])) {
- $product_option_value_id = $option['product_option_value_id'];
- }
- }
-
- $value = $optionResults[$product_option_value_id];
-
- if ($value['price']) {
- if ($value['price_operator'] == '-') {
- $value['price'] -= (float)$value['price'];
- }
-
- $prod['price'] += (float) $value['price'];
-
- $value['price_tax'] = $this->tax->addTaxes($value['price'], $product['tax_type_id'] ?? 0);
- $value['price_formatted'] = $value['price_operator'] . $this->currency->format($value['price_tax']);
- }
-
- if ($value['weight']) {
- if ($value['weight_operator'] == '-') {
- $value['weight'] -= $value['weight'];
- }
-
- $prod['weight'] = ($prod['weight'] ?? 0) + $value['weight'];
- $value['weight_formatted'] = $value['weight'];
- }
-
- if ($value['points']) {
- if ($value['points_operator'] == '-') {
- $value['points'] -= $value['points'];
- }
-
- $prod['points'] += $value['points'];
- $value['points_formatted'] = $value['points'];
- }
-
- $prod['option_value'][$product_option_value_id] = $value;
- }
- }
+ $this->applyProductOptionValues($prod, $product, $optionResults);
//add subscription data
- if (isset($prod['subscription_plan_id']) && $prod['subscription_plan_id']) {
+ if (!empty($prod['subscription_plan_id'])) {
$prod['subscription'] = $subscriptionResults[$prod['subscription_plan_id']] ?? [];
$prod['subscription_name'] = $prod['subscription']['name'] ?? '';
}
//if product variant override price and stock
- if (isset($prod['product_variant_id']) && $prod['product_variant_id']) {
- $variant = $variantsResults[$prod['options']] ?? [];
- if (! $variant) {
- foreach ($variantsResults as $var) {
- if ($prod['product_variant_id'] == $var['product_variant_id']) {
- $variant = $var;
- }
- }
- }
-
- if ($variant && $variant['product_variant_id'] == $prod['product_variant_id']) {
- $prod['variant'] = $variant;
- $prod['price'] = $variant['price'];
- $prod['stock_quantity'] = $variant['stock_quantity'];
- }
- }
+ $this->applyVariantOverrides($prod, $variantsResults);
$url = ['slug' => $product['slug'], 'product_id' => $product['product_id']];
$prod['key'] = $key;
@@ -354,11 +268,9 @@ class Cart {
$prod['remove-url'] = htmlspecialchars(url('cart/cart/remove', $url + ['key' => $key]));
$prod['total'] = $prod['price'] * $prod['quantity'];
- $prod['total_formatted'] = $this->currency->format($prod['total']);
- $taxValue = $this->tax->addTaxes($prod['price'], $product['tax_type_id'], true);
- $prod['price_tax'] = ($taxValue + $prod['price']);
- $prod['tax'] = $prod['price_tax'] * $prod['quantity'];
+ $prod['price_tax'] = $this->tax->addTaxes($prod['price'], $product['tax_type_id']);
+ $prod['tax'] = $this->tax->lineTax($prod['price'], $product['tax_type_id'], $prod['quantity']);
$prod['total_tax'] = $prod['tax'];
$prod['price_currency'] = $currency;
@@ -366,10 +278,7 @@ class Cart {
$prod['price_formatted'] = $this->currency->format($product['price']);
$prod['total_formatted'] = $this->currency->format($prod['total']);
$prod['total_tax_formatted'] = $this->currency->format($prod['total_tax']);
-
- if (isset($products[$productId]['subscription_plan_id'])) {
- //$prod['subscription_plan_id'] = $products[$productId]['subscription_plan_id'];
- }
+ $prod['total_weight'] = $prod['weight'] * $prod['quantity'];
$this->total += $prod['total'];
$this->total_tax += $prod['total_tax'];
@@ -382,8 +291,6 @@ class Cart {
}
unset($prod['content']);
-
- // options add to price
}
}
@@ -401,15 +308,204 @@ class Cart {
return $results;
}
- function add($productId, $quantity = 1, $option = [], $productVariantId = false, $subscriptionPlanId = false) {
- if (! $productId) {
+ /**
+ * Collect unique product/option/variant/subscription references from the
+ * cart rows so each can be fetched with a single query.
+ *
+ * @return array{productIds: array<string, string>, options: array<string, string>, subscriptions: array<string, string>, variants: array<string, string>}
+ */
+ protected function collectProductReferences(): array {
+ $productIds = [];
+ $productOptions = [];
+ $productVariants = [];
+ $productSubscriptions = [];
+
+ foreach ($this->products as $product) {
+ $productId = $product['product_id'];
+ $productIds[$productId] = $productId;
+
+ if (!empty($product['option']) && is_array($product['option'])) {
+ foreach ($product['option'] as $value) {
+ if (is_numeric($value)) {
+ $productOptions[(string)$value] = $value;
+ } elseif (isset($value['product_option_value_id'])) {
+ $id = $value['product_option_value_id'];
+ $productOptions[(string)$id] = $id;
+ }
+ }
+ }
+
+ if (!empty($product['subscription_plan_id'])) {
+ $productSubscriptions[$product['subscription_plan_id']] = $product['subscription_plan_id'];
+ }
+
+ if (!empty($product['product_variant_id'])) {
+ $productVariants[$product['product_variant_id']] = $product['product_variant_id'];
+ }
+ }
+
+ return [
+ 'productIds' => $productIds,
+ 'options' => $productOptions,
+ 'subscriptions' => $productSubscriptions,
+ 'variants' => $productVariants,
+ ];
+ }
+
+ /**
+ * Load product, option value, subscription plan and variant data in bulk.
+ *
+ * @param array{productIds: array<array-key, mixed>, options: array<array-key, mixed>, subscriptions: array<array-key, mixed>, variants: array<array-key, mixed>} $refs
+ *
+ * @return array{results: array<array-key, mixed>, optionResults: array<array-key, mixed>, subscriptionResults: array<array-key, mixed>, variantsResults: array<array-key, mixed>}
+ */
+ protected function loadCartProductData(array $refs): array {
+ $options = ['product_id' => $refs['productIds']] + $this->options;
+
+ $results = model($this->productModel)->getAll($options);
+
+ $optionResults = [];
+
+ if ($refs['options']) {
+ $optionValueSql = new Product_option_valueSQL();
+ $optionResults = $optionValueSql->getAll(
+ ['product_option_value_id' => array_values($refs['options'])] + $this->options
+ )['product_option_value'] ?? [];
+ }
+
+ $subscriptionResults = [];
+
+ if ($refs['subscriptions']) {
+ $subscriptionPlanSql = new Subscription_planSQL();
+ $subscriptionResults = $subscriptionPlanSql->getAll(
+ ['subscription_plan_id' => array_values($refs['subscriptions'])] + $this->options
+ )['subscription_plan'] ?? [];
+ }
+
+ $variantsResults = [];
+
+ if ($refs['variants']) {
+ $productVariantSql = new Product_variantSQL();
+ $variantsResults = $productVariantSql->getAll(
+ ['product_variant_id' => array_values($refs['variants'])] + $this->options
+ )['product_variant'] ?? [];
+ }
+
+ return [
+ 'results' => $results,
+ 'optionResults' => $optionResults,
+ 'subscriptionResults' => $subscriptionResults,
+ 'variantsResults' => $variantsResults,
+ ];
+ }
+
+ /**
+ * Apply option value price/weight/points adjustments to one cart row.
+ *
+ * @param array<string, mixed> &$prod
+ * @param array<string, mixed> $product
+ * @param array<string, array<string, mixed>> $optionResults
+ */
+ protected function applyProductOptionValues(array &$prod, array $product, array $optionResults): void {
+ if (empty($prod['option']) || !is_array($prod['option'])) {
+ return;
+ }
+
+ foreach ($prod['option'] as $option_id => $option) {
+ $product_option_value_id = null;
+
+ if (is_numeric($option)) {
+ $product_option_value_id = $option;
+ } elseif (isset($option['product_option_value_id'])) {
+ $product_option_value_id = $option['product_option_value_id'];
+ }
+
+ if ($product_option_value_id === null || !isset($optionResults[$product_option_value_id])) {
+ continue;
+ }
+
+ $value = $optionResults[$product_option_value_id];
+
+ if (!empty($value['price'])) {
+ if (($value['price_operator'] ?? '+') === '-') {
+ $value['price'] = -(float)$value['price'];
+ }
+
+ $prod['price'] += (float)$value['price'];
+
+ $value['price_tax'] = $this->tax->addTaxes($value['price'], $product['tax_type_id'] ?? 0);
+ $value['price_formatted'] = $value['price_operator'] . $this->currency->format($value['price_tax']);
+ }
+
+ if (!empty($value['weight'])) {
+ if (($value['weight_operator'] ?? '+') === '-') {
+ $value['weight'] = -$value['weight'];
+ }
+
+ $prod['weight'] = ($prod['weight'] ?? 0) + $value['weight'];
+ $value['weight_formatted'] = $value['weight'];
+ }
+
+ if (!empty($value['points'])) {
+ if (($value['points_operator'] ?? '+') === '-') {
+ $value['points'] = -$value['points'];
+ }
+
+ $prod['points'] = ($prod['points'] ?? 0) + $value['points'];
+ $value['points_formatted'] = $value['points'];
+ }
+
+ $prod['option_value'][$product_option_value_id] = $value;
+ }
+ }
+
+ /**
+ * Override price and stock from the selected product variant when present.
+ *
+ * @param array<string, mixed> &$prod
+ * @param array<int|string, array<string, mixed>>|array<array<string, mixed>> $variantsResults
+ */
+ protected function applyVariantOverrides(array &$prod, array $variantsResults): void {
+ if (empty($prod['product_variant_id'])) {
+ return;
+ }
+
+ $variant = $variantsResults[$prod['product_variant_id']] ?? [];
+ if (!$variant) {
+ foreach ($variantsResults as $var) {
+ if ($prod['product_variant_id'] == $var['product_variant_id']) {
+ $variant = $var;
+ }
+ }
+ }
+
+ if ($variant && $variant['product_variant_id'] == $prod['product_variant_id']) {
+ $prod['variant'] = $variant;
+ $prod['price'] = $variant['price'];
+ $prod['stock_quantity'] = $variant['stock_quantity'];
+ }
+ }
+
+ /**
+ * Add a product to the cart.
+ *
+ * @param int|string $productId
+ * @param int|float $quantity
+ * @param array<int|string, mixed> $option
+ * @param int|string|false $productVariantId
+ * @param int|string|false $subscriptionPlanId
+ *
+ * @return string|false The cart item key or false on failure.
+ */
+ public function add(int|string $productId, int|float $quantity = 1, array $option = [], int|string|false $productVariantId = false, int|string|false $subscriptionPlanId = false): string|false {
+ if (!$productId) {
return false;
}
$key = $productId;
$options = '';
- if ($option && is_array($option)) {
+ if ($option) {
ksort($option);
$options = trim(str_replace('"', '', json_encode($option)), '{}');
$key .= '_' . $options;
@@ -429,9 +525,9 @@ class Cart {
$this->products[$key]['quantity'] += $quantity;
} else {
$this->products[$key] = [
- 'product_id' => (int) $productId,
+ 'product_id' => (int)$productId,
'quantity' => (int)$quantity,
- 'option' => $option ?? [],
+ 'option' => $option,
'options' => $options,
'subscription_plan_id' => $subscriptionPlanId,
'product_variant_id' => $productVariantId,
@@ -443,7 +539,18 @@ class Cart {
return $key;
}
- function update($key, $quantity = 1, $option = [], $productVariantId = false, $subscriptionPlanId = false) {
+ /**
+ * Update a cart item by key.
+ *
+ * @param string $key
+ * @param int|float $quantity
+ * @param array<int|string, mixed> $option
+ * @param int|string|false $productVariantId
+ * @param int|string|false $subscriptionPlanId
+ *
+ * @return string|false The cart item key or false if item not found.
+ */
+ public function update(string $key, int|float $quantity = 1, array $option = [], int|string|false $productVariantId = false, int|string|false $subscriptionPlanId = false): string|false {
if (isset($this->products[$key])) {
$this->products[$key]['quantity'] = max(1, $quantity);
@@ -467,12 +574,19 @@ class Cart {
return false;
}
- function getAll() {
- return $this->products ?? [];
+ /**
+ * Get all products in the cart.
+ *
+ * @return array<string, mixed>
+ */
+ public function getAll(): array {
+ return $this->products;
}
- function getNoProducts() {
- //return count($this->products ?? []);
+ /**
+ * Get the total quantity of all products in the cart.
+ */
+ public function getNoProducts(): int {
$total = 0;
foreach ($this->products as $product) {
@@ -482,7 +596,14 @@ class Cart {
return $total;
}
- function remove($key) {
+ /**
+ * Remove one or more products from the cart by key(s).
+ *
+ * @param string|array<int, string> $key
+ *
+ * @return string|array<int, string>|false The key(s) removed or false.
+ */
+ public function remove(string|array $key): string|array|false {
if ($key) {
if (is_array($key)) {
foreach ($key as $value) {
@@ -504,7 +625,12 @@ class Cart {
return false;
}
- public function getSubscription() {
+ /**
+ * Get products that have a subscription.
+ *
+ * @return array<int, mixed>
+ */
+ public function getSubscription(): array {
$product_data = [];
foreach ($this->products as $value) {
@@ -516,41 +642,46 @@ class Cart {
return $product_data;
}
- public function getWeight() {
+ /**
+ * Get the total weight of all shippable products.
+ */
+ public function getWeight(): float|int {
$weight = 0;
foreach ($this->products as $product) {
if (isset($product['requires_shipping']) && $product['requires_shipping']) {
- $weight += $this->weight->convert($product['weight'], $product['weight_type_id'], $this->options['weight_type_id']) * $product['quantity'];
+ $weight += (float)($product['weight'] ?? 0) * $product['quantity'];
}
}
return $weight;
}
- public function countProducts() {
- $product_total = 0;
-
- $products = $this->products;
-
- foreach ($products as $product) {
- $product_total += $product['quantity'];
- }
-
- return $product_total;
- }
-
- public function hasProducts() {
+ /**
+ * Check whether the cart has any products.
+ */
+ public function hasProducts(): int {
return count($this->products);
}
- public function hasSubscription() {
+ /**
+ * Check whether the cart has any subscription products.
+ */
+ public function hasSubscription(): int {
return count($this->getSubscription());
}
- public function hasStock() {
+ /**
+ * Check whether all products in the cart are in stock.
+ *
+ * Products with stock tracking disabled (subtract_stock off) are always
+ * considered in stock; otherwise the cart quantity is compared against the
+ * available stock_quantity.
+ */
+ public function hasStock(): bool {
foreach ($this->products as $product) {
- if (! $product['stock']) {
+ if (!empty($product['subtract_stock']) &&
+ (int)($product['stock_quantity'] ?? 0) < (int)($product['quantity'] ?? 1)) {
return false;
}
}
@@ -558,9 +689,12 @@ class Cart {
return true;
}
- public function hasShipping() {
+ /**
+ * Check whether any product in the cart requires shipping.
+ */
+ public function hasShipping(): bool {
foreach ($this->products as $product) {
- if ($product['requires_shipping']) {
+ if (!empty($product['requires_shipping'])) {
return true;
}
}
@@ -568,9 +702,12 @@ class Cart {
return false;
}
- public function hasDownload() {
+ /**
+ * Check whether any product in the cart has a digital asset.
+ */
+ public function hasDownload(): bool {
foreach ($this->products as $product) {
- if ($product['digital_asset']) {
+ if (!empty($product['digital_asset'])) {
return true;
}
}
@@ -578,46 +715,30 @@ class Cart {
return false;
}
- /*
- protected function read() {
- $data = $this->session->get($this->sessionKey);
-
- if (is_array($data)) {
- foreach ($data as $property => $value) {
- $this->$property = $value;
- }
- }
- }
-
- protected function write() {
- //$data = get_object_vars($this);
- foreach (['products', 'taxes', 'totals', 'total_items', 'coupons', 'product_options'] as $property) {
- $data[$property] = $this->$property;
- }
-
- $this->session->set($this->sessionKey, $data);
- }
-
- public function empty() {
- $this->session->set($this->sessionKey, []);
- $this->enableCache();
- }
- */
- public function enableCache() {
+ /**
+ * Enable browser caching for the cart.
+ */
+ public function enableCache(): void {
//enable cache back by clearing the cart cookie
if ($this->controlCache && isset($_COOKIE['cart'])) {
setcookie('cart', '', time() - 3600, '/');
}
}
- public function disableCache() {
+ /**
+ * Disable browser caching for the cart.
+ */
+ public function disableCache(): void {
//disable cache back setting the cart cookie
- if ($this->controlCache && ! isset($_COOKIE['cart'])) {
+ if ($this->controlCache && !isset($_COOKIE['cart'])) {
setcookie('cart', '1', 0, '/');
}
}
-
- public function __destruct() {
+
+ /**
+ * Persist cart on destruction if there are pending changes.
+ */
+ public function __destruct() {
if ($this->hasChanges) {
$this->write();
}
diff --git a/system/cart/coupon-trait.php b/system/cart/coupon-trait.php
index 56d8e88..9eb154e 100644
--- a/system/cart/coupon-trait.php
+++ b/system/cart/coupon-trait.php
@@ -25,15 +25,21 @@ namespace Vvveb\System\Cart;
use Vvveb\Sql\CouponSQL;
trait CouponTrait {
- protected $coupons = [];
+ /** @var array<string, array<string, mixed>> */
+ protected array $coupons = [];
- public function addCoupon($code) {
+ /**
+ * Validate and add a coupon code to the cart.
+ *
+ * @param string $code
+ */
+ public function addCoupon(string $code): bool {
if ($code) {
$coupon = new CouponSQL();
$options = ['code' => $code, 'status' => 1] + $this->options;
$result = $coupon->get($options);
- if ($result && $result['code'] == $code) {
+ if ($result && $result['code'] === $code) {
$this->coupons[$code] = $result;
return true;
@@ -43,7 +49,16 @@ trait CouponTrait {
return false;
}
- public function removeCoupon($code) {
+ /**
+ * Remove a coupon code from the cart.
+ *
+ * @param string $code
+ */
+ public function removeCoupon(string $code): bool {
+ if (!isset($this->coupons[$code])) {
+ return false;
+ }
+
$coupon = $this->coupons[$code];
$this->removeTotal('coupon', 'coupon.' . $coupon['coupon_id']);
unset($this->coupons[$code]);
@@ -51,11 +66,19 @@ trait CouponTrait {
return true;
}
- public function getCoupons() {
+ /**
+ * Get all applied coupons.
+ *
+ * @return array<string, array<string, mixed>>
+ */
+ public function getCoupons(): array {
return $this->coupons;
}
- function addCouponTotal() {
+ /**
+ * Calculate and add coupon discount totals.
+ */
+ public function addCouponTotal(): void {
$coupons = $this->getCoupons();
$total = $this->getSubTotal();
@@ -63,15 +86,15 @@ trait CouponTrait {
$taxes = $this->getTotals('tax');
foreach ($taxes as $tax) {
$total += $tax['value'];
- }
+ }
+
+ foreach ($coupons as $code => $coupon) {
+ $discount = $coupon['discount'] ?? 0;
- foreach ($coupons as $coupon) {
- if ($coupon['type'] == 'P') {
- $discount = (($coupon['discount'] * $total) / 100);
- } else {
- $discount = $coupon['discount'];
+ if (($coupon['type'] ?? '') === 'P') {
+ $discount = (($discount * $total) / 100);
}
- $this->addTotal('coupon', 'coupon.' . $coupon['coupon_id'], $coupon['name'], -$discount);
+ $this->addTotal('coupon', 'coupon.' . ($coupon['coupon_id'] ?? $code), $coupon['name'] ?? (string)$code, -$discount);
}
}
}
diff --git a/system/cart/currency.php b/system/cart/currency.php
old mode 100644
new mode 100755
index 6eeaaf5..d56556e
--- a/system/cart/currency.php
+++ b/system/cart/currency.php
@@ -25,32 +25,66 @@ namespace Vvveb\System\Cart;
use function Vvveb\session as sess;
use Vvveb\System\Locale;
+/** @phpstan-consistent-constructor */
class Currency {
- private $currencies;
+ /** @var array<string, array{sign_start: string, sign_end: string, decimal_place: int, value: float}> */
+ private array $currencies = [];
- private $options;
+ /** @var array<string, mixed> */
+ private array $options = [];
- public static function getInstance($options = []) {
- static $inst = null;
+ /**
+ * @param array<string, mixed> $options
+ */
+ public static function getInstance(array $options = []): static {
+ static $inst;
if ($inst === null) {
- $inst = new Currency($options);
+ $inst = new static($options);
}
return $inst;
}
- public function __construct($options = []) {
+ /**
+ * @param array<string, mixed> $options
+ */
+ public function __construct(array $options = []) {
$this->options = $options;
$this->currencies = Locale::availableCurrencies();
}
- public function format($number, $currency = false, $format = true, $value = 0) {
- if (! $currency) {
+ /**
+ * Number of decimal places for the given (or current) currency.
+ *
+ * @param string|false|null $currency Currency code, null/false = current.
+ *
+ * @return int
+ */
+ public function getDecimalPlace(string|false|null $currency = null): int {
+ if (!$currency) {
$currency = $this->options['currency'] ?? sess('currency');
}
- if (! $currency || ! isset($this->currencies[$currency])) {
+ return (int)($this->currencies[$currency]['decimal_place'] ?? 2);
+ }
+
+ /**
+ * Format a numeric amount with the appropriate currency symbol.
+ *
+ * @param float|int|string $number
+ * @param string|false $currency
+ * @param bool $format
+ * @param float|int $value
+ *
+ * @return string|float
+ */
+ public function format(float|int|string $number, string|false $currency = false, bool $format = true, float|int $value = 0): string|float {
+ if (!$currency) {
+ $currency = $this->options['currency'] ?? sess('currency');
+ }
+
+ if (!$currency || !isset($this->currencies[$currency])) {
return '';
}
@@ -58,7 +92,7 @@ class Currency {
$sign_end = $this->currencies[$currency]['sign_end'];
$decimal_place = $this->currencies[$currency]['decimal_place'];
- if (! $value) {
+ if (!$value) {
$value = $this->currencies[$currency]['value'];
}
@@ -66,7 +100,7 @@ class Currency {
$amount = round($amount, $decimal_place);
- if (! $format) {
+ if (!$format) {
return $amount;
}
@@ -76,7 +110,7 @@ class Currency {
$string .= $sign_start;
}
- $decimals = 2;
+ $decimals = (int)$decimal_place;
$decimal_separator = '.';
$thousands_separator = ',';
@@ -89,19 +123,21 @@ class Currency {
return $string;
}
- public function convert($value, $from, $to) {
- if (isset($this->currencies[$from])) {
- $from = $this->currencies[$from]['value'];
- } else {
- $from = 1;
- }
-
- if (isset($this->currencies[$to])) {
- $to = $this->currencies[$to]['value'];
- } else {
- $to = 1;
+ /**
+ * Convert a value between two currencies.
+ *
+ * @param float|int $value
+ * @param string $from
+ * @param string $to
+ */
+ public function convert(float|int $value, string $from, string $to): float {
+ $fromRate = $this->currencies[$from]['value'] ?? 1;
+ $toRate = $this->currencies[$to]['value'] ?? 1;
+
+ if (!$fromRate) {
+ return 0.0;
}
- return $value * ($to / $from);
+ return $value * ($toRate / $fromRate);
}
}
diff --git a/system/cart/db-trait.php b/system/cart/db-trait.php
index 8042744..b23af57 100644
--- a/system/cart/db-trait.php
+++ b/system/cart/db-trait.php
@@ -24,17 +24,37 @@ namespace Vvveb\System\Cart;
use Vvveb\Sql\CartSQL;
+/**
+ * Provides database persistence for the cart.
+ *
+ * @property int|string|null $cart_id
+ * @property string $sessionKey
+ * @property array<string, mixed> $products
+ * @property array<string, mixed> $taxes
+ * @property array<string, mixed> $totals
+ * @property int $total_items
+ * @property bool $hasChanges
+ * @property \Vvveb\System\Session $session
+ */
trait DbTrait {
- private $cartTable;
+ private ?CartSQL $cartTable = null;
- protected function initDb() {
+ /**
+ * Initialise the cart database table model.
+ */
+ protected function initDb(): void {
$this->cartTable = new CartSQL();
}
- protected function getDbCart() {
+ /**
+ * Read cart data from the database.
+ *
+ * @return array<string, mixed>
+ */
+ protected function getDbCart(): array {
$data = [];
- if (! $this->cartTable) {
+ if (!$this->cartTable) {
$this->initDb();
}
@@ -47,7 +67,30 @@ trait DbTrait {
return $data;
}
- function loadCart($cart_id) {
+ /**
+ * Apply stored cart data to this instance.
+ *
+ * Only known cart properties are assigned, so unexpected keys in
+ * session or database rows cannot create dynamic properties.
+ *
+ * @param array<string, mixed> $data
+ */
+ private function applyData(array $data): void {
+ foreach (['products', 'taxes', 'totals', 'total_items', 'coupons', 'product_options', 'cart_id'] as $property) {
+ if (array_key_exists($property, $data)) {
+ $this->$property = $data[$property];
+ }
+ }
+ }
+
+ /**
+ * Load a cart from the database by cart ID.
+ *
+ * @param int|string|null $cart_id
+ *
+ * @return array<string, mixed>
+ */
+ public function loadCart(int|string|null $cart_id): array {
$data = [];
if ($cart_id) {
@@ -55,10 +98,8 @@ trait DbTrait {
$data = $this->getDbCart();
}
- if (is_array($data) && $data) {
- foreach ($data as $property => $value) {
- $this->$property = $value;
- }
+ if ($data) {
+ $this->applyData($data);
$this->updateCart();
}
@@ -66,27 +107,33 @@ trait DbTrait {
return $data;
}
- protected function read() {
+ /**
+ * Read cart data from session or database.
+ *
+ * @return array<string, mixed>
+ */
+ protected function read(): array {
$data = $this->session->get($this->sessionKey) ?? [];
- $this->cart_id = $this->cart_id ?? $data['cart_id'] ?? null;
+ $this->cart_id ??= $data['cart_id'] ?? null;
- if (! $data && $this->cart_id) {
+ if (!$data && $this->cart_id) {
$data = $this->getDbCart();
}
- if (is_array($data) && $data) {
- foreach ($data as $property => $value) {
- $this->$property = $value;
- }
+ if ($data) {
+ $this->applyData($data);
}
return $data;
}
- protected function write() {
+ /**
+ * Persist current cart state to database and session.
+ */
+ protected function write(): void {
$data = [];
- foreach (['products', 'taxes', 'totals', 'total_items', 'coupons', 'product_options'] as $property) {
+ foreach (['products', 'taxes', 'totals', 'total_items', 'coupons', 'product_options'] as $property) {
$data[$property] = $this->$property;
}
@@ -95,13 +142,12 @@ trait DbTrait {
$cart = [];
$cart['data'] = $json;
- if (! $this->cartTable) {
+ if (!$this->cartTable) {
$this->initDb();
}
if ($this->cart_id) {
- if ($return = $this->cartTable->edit(['cart_id' => $this->cart_id, 'cart' => $cart])) {
- }
+ $this->cartTable->edit(['cart_id' => $this->cart_id, 'cart' => $cart]);
} else {
if ($return = $this->cartTable->add(['cart' => $cart])) {
$this->cart_id = $return['cart'];
@@ -111,12 +157,15 @@ trait DbTrait {
$data['cart_id'] = $this->cart_id;
$this->session->set($this->sessionKey, $data);
-
+
$this->hasChanges = false;
}
- public function empty() {
- if (! $this->cartTable) {
+ /**
+ * Empty the cart from both session and database.
+ */
+ public function empty(): bool {
+ if (!$this->cartTable) {
$this->initDb();
}
@@ -127,5 +176,7 @@ trait DbTrait {
return true;
}
+
+ return false;
}
}
diff --git a/system/cart/order-cart.php b/system/cart/order-cart.php
old mode 100644
new mode 100755
index df8ad89..82dae79
--- a/system/cart/order-cart.php
+++ b/system/cart/order-cart.php
@@ -26,23 +26,29 @@ use Vvveb\Sql\OrderSQL;
use Vvveb\System\Session;
class OrderCart extends Cart {
- protected $order_id;
+ /** @var int|string|null */
+ protected int|string|null $order_id = null;
- protected $controlCache = false;
+ protected bool $controlCache = false;
- function __construct($order_id, $options = []) {
- $this->session = Session :: getInstance();
- $this->currency = Currency :: getInstance($options);
- $this->tax = Tax :: getInstance();
- $this->weight = Weight :: getInstance();
+ /**
+ * @param int|string $order_id
+ * @param array<string, mixed> $options
+ */
+ public function __construct(int|string $order_id, array $options = []) {
+ $this->session = Session::getInstance();
+ $this->currency = Currency::getInstance($options);
+ $this->tax = Tax::getInstance();
+ $this->tax->pricesIncludeTax = !empty($options['prices_include_tax']);
+ $this->weight = Weight::getInstance();
- $this->tax->setRegionRules($options['country_id'], $options['region_id']);
+ $this->tax->setRegionRules($options['country_id'], $options['region_id'], $options['based'] ?? 'store', $options['user_group_id'] ?? null);
$this->order_id = $order_id;
$this->cart_id = $options['cart_id'] ?? null;
$this->options = $options;
- if ($this->cart_id && ! is_numeric($this->cart_id)) {
+ if ($this->cart_id && !is_numeric($this->cart_id)) {
$cart_id = urldecode($this->cart_id);
$key = \Vvveb\getConfig('app.key');
$cart_id = \Vvveb\decrypt($key, $cart_id);
@@ -54,23 +60,20 @@ class OrderCart extends Cart {
}
$this->read();
-
- if (! isset($this->total_items)) {
- $this->total_items = 0;
- }
-
- if (! isset($this->total)) {
- $this->total = 0;
- }
-
- if (! isset($this->products)) {
- $this->products = [];
- }
}
- function addOrderProduct($productId, $orderProductId = false, $quantity = 1, $option = [], $subscriptionPlanId = false) {
- if (! $productId) {
- return false;
+ /**
+ * Add a product from an existing order into the cart.
+ *
+ * @param int|string $productId
+ * @param int|string|false $orderProductId
+ * @param int|float $quantity
+ * @param array<int, array{product_option_id: int|string, product_option_value_id: int|string}> $option
+ * @param int|string|false $subscriptionPlanId
+ */
+ public function addOrderProduct(int|string $productId, int|string|false $orderProductId = false, int|float $quantity = 1, array $option = [], int|string|false $subscriptionPlanId = false): void {
+ if (!$productId) {
+ return;
}
$key = $productId;
@@ -101,12 +104,20 @@ class OrderCart extends Cart {
'subscription_plan_id' => $subscriptionPlanId,
];
}
-
- //return $this->updateCart();
}
- function addTotal($key, $title, $value, $text = '', $order_total_id = false) {
- $data = ['key' => $key, 'title' => $title, 'value' => $value, 'value_formatted' => $this->currency->format($value), 'text' => $text, 'order_total_id' => $order_total_id];
+ /**
+ * Add or update a total entry for the order cart.
+ *
+ * @param string $namespace
+ * @param string $key
+ * @param string $title
+ * @param float|int|string $value
+ * @param string $text
+ * @param int|string|false $order_total_id
+ */
+ public function addOrderTotal(string $namespace, string $key, string $title, float|int|string $value, string $text = '', int|string|false $order_total_id = false): void {
+ $data = ['namespace' => $namespace, 'key' => $key, 'title' => $title, 'value' => $value, 'value_formatted' => $this->currency->format($value), 'text' => $text, 'order_total_id' => $order_total_id];
if (isset($this->totals[$key])) {
$this->totals[$key]['value'] = $value;
@@ -117,46 +128,52 @@ class OrderCart extends Cart {
//$this->write();
}
- protected function read() {
+ /**
+ * Load order data from the database and populate the cart.
+ *
+ * @return array<string, mixed>
+ */
+ protected function read(): array {
$options = ['order_id' => (int)$this->order_id] + $this->options;
- $orders = new OrderSQL();
- $results = $orders->get($options);
+ $orders = new OrderSQL();
+ $results = $orders->get($options);
- //$this->totals = $results['total'];
if (isset($results['total']) && $results['total']) {
foreach ($results['total'] as $total) {
- $this->addTotal($total['key'], $total['title'], $total['value'], $total['title'], $total['order_total_id']);
+ $this->addOrderTotal($total['namespace'] ?? 'total', $total['key'], $total['title'], $total['value'], $total['title'], $total['order_total_id']);
}
}
- //$this->products = $results['product'];
if (isset($results['products']) && $results['products']) {
foreach ($results['products'] as $product) {
$option_value = $product['option_value'] ? json_decode($product['option_value'], true) : [];
+
+ if (!is_array($option_value)) {
+ $option_value = [];
+ }
+
$this->addOrderProduct($product['product_id'], $product['order_product_id'], $product['quantity'], $option_value);
}
}
$this->updateCart();
- /*
- if (is_array($data)) {
- foreach ($data as $property => $value) {
- $this->$property = $value;
- }
- }*/
+ return $results;
}
- public function write() {
+ /**
+ * Persist the order cart state back to the database.
+ */
+ public function write(): void {
$this->addTaxTotal();
$order_id = $this->order_id;
$orders = new OrderSQL();
- $data = ['total' => $this->getGrandTotal()];
- $result = $orders->edit(['order' => $data, 'order_id' => $order_id]);
+ $data = ['total' => $this->getGrandTotal()];
+ $result = $orders->edit(['order' => $data, 'order_id' => $order_id]);
foreach ($this->products as $key => $product) {
- $product_options = $product['option'];
+ $product_options = $product['option'];
if (isset($product['order_product_id']) && $product['order_product_id']) {
$orders->editProduct(['product' => $product, 'product_options' => $product_options, 'order_product_id' => $product['order_product_id'], 'order_id' => $order_id]);
@@ -174,17 +191,5 @@ class OrderCart extends Cart {
$orders->addTotal(['total' => $total, 'order_id' => $order_id]);
}
}
- /*
- $checkoutInfo['products'] = $cart->getAll();
- $checkoutInfo['product_options'] = $cart->getProductOptions();
- $checkoutInfo['totals'] = $cart->getTotals();
- $checkoutInfo['total'] = $cart->getGrandTotal();
-
- foreach (['products', 'taxes', 'totals', 'total_items', 'coupons', 'product_options'] as $property) {
- $data[$property] = $this->$property;
- }
-
- $this->session->set($this->sessionKey, $data);
- */
}
}
diff --git a/system/cart/order.php b/system/cart/order.php
index 5eddd5e..5043739 100755
--- a/system/cart/order.php
+++ b/system/cart/order.php
@@ -25,14 +25,15 @@ namespace Vvveb\System\Cart;
use function Vvveb\siteSettings;
use Vvveb\Sql\OrderSQL;
+/** @phpstan-consistent-constructor */
class Order {
- private $model;
+ private OrderSQL $model;
- public static function getInstance($options = []) {
- static $inst = null;
+ public static function getInstance(): static {
+ static $inst;
if ($inst === null) {
- $inst = new Order($options);
+ $inst = new static();
}
return $inst;
@@ -42,19 +43,46 @@ class Order {
$this->model = new OrderSQL();
}
- public function getData() {
+ /**
+ * Get raw order data.
+ *
+ * @return array<string, mixed>
+ */
+ public function getData(): array {
return $this->model->getData();
}
- public function get($order_id) {
+ /**
+ * Get an order by its ID.
+ *
+ * @param int|string $order_id
+ *
+ * @return array<string, mixed>
+ */
+ public function get(int|string $order_id): array {
return $this->model->get(['order_id' => $order_id]);
}
- public function edit($data, $order_id) {
+ /**
+ * Edit an existing order.
+ *
+ * @param array<string, mixed> $data
+ * @param int|string $order_id
+ *
+ * @return mixed
+ */
+ public function edit(array $data, int|string $order_id): mixed {
return $this->model->edit(['order' => $data, 'order_id' => $order_id]);
}
- public function add($data) {
+ /**
+ * Add a new order.
+ *
+ * @param array<string, mixed> $data
+ *
+ * @return array<string, mixed>
+ */
+ public function add(array $data): array {
//set defaults
$defaults = ['invoice_format', 'order_id_format', 'order_status_id', 'remote_ip', 'forwarded_for_ip'];
@@ -64,19 +92,22 @@ class Order {
foreach ($defaults as $default) {
if (
- (! isset($data) || ! empty($data)) &&
- (isset($site[$default]) && ! empty($site[$default]))
+ empty($data[$default]) &&
+ isset($site[$default])
) {
$data[$default] = $site[$default];
}
}
+ $data['invoice_format'] ??= '';
+ $data['order_id_format'] ??= '';
+
$data['invoice_no'] = \Vvveb\invoiceFormat($data['invoice_format'], $data);
$data['customer_order_id'] = \Vvveb\invoiceFormat($data['order_id_format'], $data);
//todo: check if email is already registerd for new accounts
//add products one by one to set product options for each
- $products = $data['products'];
+ $products = $data['products'] ?? [];
$data['products'] = [];
$result = $this->model->add(['order' => $data]);
@@ -90,7 +121,7 @@ class Order {
}
//update invoice to set {order_id} variable
$data['order_id'] = $order_id;
- $data['user_id'] = $data['user_id'] ?? 0;
+ $data['user_id'] ??= 0;
$data['customer_order_id'] = \Vvveb\invoiceFormat($data['order_id_format'], $data);
$data['invoice_no'] = \Vvveb\invoiceFormat($data['invoice_format'], $data);
$result = $this->model->edit(['order' => ['invoice_no' => $data['invoice_no'], 'customer_order_id' => $data['customer_order_id']], 'order_id' => $order_id]);
diff --git a/system/cart/product-option-trait.php b/system/cart/product-option-trait.php
index 092ca44..44901ba 100644
--- a/system/cart/product-option-trait.php
+++ b/system/cart/product-option-trait.php
@@ -22,22 +22,42 @@
namespace Vvveb\System\Cart;
+/**
+ * Provides product option helpers for the cart.
+ *
+ * @property array<string, array{price: float|int|string, product_option_type_id: int|string}> $product_options
+ * @property array<int|string, array<array-key, mixed>> $products
+ */
trait ProductOptionTrait {
- protected $product_options = [];
+ /** @var array<string, array{price: float|int|string, product_option_type_id: int|string}> */
+ protected array $product_options = [];
- public function addProductOption($name, $price, $product_optionTypeId) {
+ /**
+ * @param string $name
+ * @param float|int|string $price
+ * @param int|string $product_optionTypeId
+ */
+ public function addProductOption(string $name, float|int|string $price, int|string $product_optionTypeId): void {
if ($price && $product_optionTypeId) {
$this->product_options[$name] = ['price' => $price, 'product_option_type_id' => $product_optionTypeId];
}
}
- public function removeProductOption($name) {
+ /**
+ * @param string $name
+ */
+ public function removeProductOption(string $name): void {
unset($this->product_options[$name]);
}
- public function getProductOptions() {
- $product_options = [];
- $products = $this->products;
+ /**
+ * Get product options for all products in the cart.
+ *
+ * @return array<int|string, mixed>
+ */
+ public function getProductOptions(): array {
+ $product_options = [];
+ $products = $this->products;
foreach ($products as $key => $product) {
if (isset($product['option_value']) && $product['option_value']) {
@@ -48,11 +68,29 @@ trait ProductOptionTrait {
return $product_options;
}
- function addProductOptionTotal() {
+ /**
+ * Add product option totals to the cart totals.
+ */
+ public function addProductOptionTotal(): void {
$product_options = $this->getProductOptions();
- foreach ($product_options as $product_option) {
- $this->addTotal('product_option', 'product_option.' . $product_option['product_option_rate_id'], $product_option['name'], $product_option['value']);
+ foreach ($product_options as $productKey => $optionValues) {
+ if (!is_array($optionValues)) {
+ continue;
+ }
+
+ foreach ($optionValues as $optionValueId => $optionValue) {
+ if (!is_array($optionValue)) {
+ continue;
+ }
+
+ $name = $optionValue['name'] ?? '';
+ $value = $optionValue['value'] ?? '';
+
+ if ($name || $value) {
+ $this->addTotal('product_option', 'product_option.' . $productKey . '.' . $optionValueId, $name, $value);
+ }
+ }
}
}
}
diff --git a/system/cart/tax-trait.php b/system/cart/tax-trait.php
old mode 100644
new mode 100755
index 2158f0b..f8c3f39
--- a/system/cart/tax-trait.php
+++ b/system/cart/tax-trait.php
@@ -22,36 +22,73 @@
namespace Vvveb\System\Cart;
+/**
+ * Provides tax calculation helpers for the cart.
+ *
+ * @property array<string, array{price: float|int|string, tax_type_id: int|string}> $taxes
+ * @property array<int|string, array<array-key, mixed>> $products
+ * @property float|int $total_tax
+ * @property Tax $tax
+ */
trait TaxTrait {
- public function addTax($name, $price, $taxTypeId) {
+ /**
+ * Split a tax-inclusive amount using the cart's resolved rates.
+ *
+ * @param float|int|string $gross
+ * @param int|string $taxTypeId
+ *
+ * @return array{0: float, 1: float} [net, tax]
+ */
+ public function extractTax(float|int|string $gross, int|string $taxTypeId): array {
+ return $this->tax->extractTax($gross, $taxTypeId);
+ }
+
+ /**
+ * @param string $name
+ * @param float|int|string $price
+ * @param int|string $taxTypeId
+ */
+ public function addTax(string $name, float|int|string $price, int|string $taxTypeId): void {
if ($price && $taxTypeId) {
$this->taxes[$name] = ['price' => $price, 'tax_type_id' => $taxTypeId];
}
}
- public function removeTax($name) {
+ /**
+ * @param string $name
+ */
+ public function removeTax(string $name): void {
unset($this->taxes[$name]);
}
- public function getTaxes() {
+ /**
+ * Calculate taxes for all products and custom taxes.
+ *
+ * @return array<int, array{tax_rate_id: int|string, name: string, rate: string, type: string, amount: float|int, value: float|int}>
+ */
+ public function getTaxes(): array {
$taxes = [];
$this->total_tax = 0;
$products = $this->products + $this->taxes;
+ $precision = $this->tax->taxPrecision ?? 2;
foreach ($products as $product) {
if (isset($product['tax_type_id']) && $product['tax_type_id']) {
$tax_rates = $this->tax->getRates($product['price'], $product['tax_type_id']);
foreach ($tax_rates as $tax_rate) {
- $rateId = $tax_rate['tax_rate_id'] ?? false;
+ $rateId = $tax_rate['tax_rate_id'];
- if (! isset($taxes[$rateId])) {
+ if (!isset($taxes[$rateId])) {
$taxes[$rateId] = $tax_rate;
$taxes[$rateId]['value'] = 0;
}
- $taxes[$rateId]['value'] += ($tax_rate['amount'] * ($product['quantity'] ?? 1));
- $this->total_tax = $taxes[$rateId]['value'];
+ //round per order line so the summed total matches the
+ //displayed line taxes instead of drifting by a cent
+ $lineTax = round($tax_rate['amount'] * ($product['quantity'] ?? 1), $precision);
+ $taxes[$rateId]['value'] += $lineTax;
+ $this->total_tax += $lineTax;
}
}
}
@@ -59,14 +96,20 @@ trait TaxTrait {
return $taxes;
}
- public function getTaxTotal() {
+ /**
+ * Get the total tax amount.
+ */
+ public function getTaxTotal(): float|int {
return $this->total_tax;
}
- function addTaxTotal() {
+ /**
+ * Calculate and add all tax totals to the cart totals.
+ */
+ public function addTaxTotal(): void {
$taxes = $this->getTaxes();
$this->removeTotal('tax');
-
+
foreach ($taxes as $tax) {
$this->addTotal('tax', 'tax.' . $tax['tax_rate_id'], $tax['name'], $tax['value']);
}
diff --git a/system/cart/tax.php b/system/cart/tax.php
index e0b386f..4fec18d 100755
--- a/system/cart/tax.php
+++ b/system/cart/tax.php
@@ -25,27 +25,107 @@ namespace Vvveb\System\Cart;
use Vvveb\Sql\Tax_typeSQL;
use Vvveb\System\Cache;
+/** @phpstan-consistent-constructor */
class Tax {
- private $taxRates = [];
+ /** @var array<int, array<int, array{tax_rate_id: int|string, name: string, rate: string, type: string, priority: mixed, based: string}>> */
+ private array $taxRates = [];
- public static function getInstance($options = []) {
- static $inst = null;
+ /**
+ * Tax amounts are rounded per order line to this many decimals
+ * (currency precision, set from the cart currency on each refresh).
+ * Line-level rounding keeps the order tax total identical to the sum
+ * of displayed line taxes, so invoices never drift by a cent.
+ *
+ * @var int
+ */
+ public int $taxPrecision = 2;
+
+ /**
+ * When true, product prices passed to addTaxes()/getRates() already
+ * include tax (e.g. EU catalogue prices) and the tax portion is backed
+ * out instead of added on top. Driven by the per-site
+ * `prices_include_tax` setting. Fee totals added via addTax() are
+ * always net and unaffected.
+ *
+ * @var bool
+ */
+ public bool $pricesIncludeTax = false;
+
+ public static function getInstance(): static {
+ static $inst;
if ($inst === null) {
- $inst = new Tax($options);
+ $inst = new static();
}
return $inst;
}
- public function __construct($options = []) {
+ public function __construct() {}
+
+ /**
+ * Current generation of the cached region rules.
+ *
+ * Tax rule rows are cached per country/region/based/group tuple and the
+ * individual tuples cannot be enumerated for deletion on every driver,
+ * so the generation is part of the cache key and invalidation bumps it.
+ * Stale generations expire naturally via the rules TTL.
+ *
+ * @return int
+ */
+ public static function rulesCacheVersion(): int {
+ $cache = Cache::getInstance();
+ $version = $cache->get(APP, 'tax_rates_version');
+
+ if ($version === null || !is_numeric($version)) {
+ $version = 1;
+ $cache->set(APP, 'tax_rates_version', $version, 259200);
+ }
+
+ return (int)$version;
}
- public function setRegionRules($country_id, $region_id, $based = 'store') {
- $cache = Cache::getInstance();
- $rules = $cache->cache(APP,"tax_rates.$country_id.$region_id.$based",function () use ($country_id, $region_id, $based) {
+ /**
+ * Invalidate all cached region rules.
+ *
+ * Rules are written under the storefront namespace while admin saves run
+ * under a different APP namespace, so bump the generation in both.
+ *
+ * @return void
+ */
+ public static function clearRulesCache(): void {
+ $cache = Cache::getInstance();
+
+ foreach (array_unique([APP, 'app', 'admin']) as $namespace) {
+ try {
+ $cache->set($namespace, 'tax_rates_version', time(), 259200);
+ } catch (\Throwable $e) {
+ }
+ }
+ }
+
+ /**
+ * Set tax rules for a specific region.
+ *
+ * @param int|string $country_id
+ * @param int|string $region_id
+ * @param string $based
+ * @param int|string|null $user_group_id Customer group filter. Null keeps
+ * the historic unfiltered behaviour.
+ */
+ public function setRegionRules(int|string $country_id, int|string $region_id, string $based = 'store', int|string|null $user_group_id = null): void {
+ $cache = Cache::getInstance();
+ $group = ($user_group_id === null || $user_group_id === '') ? 'all' : (int)$user_group_id;
+ $key = sprintf('tax_rates.%d.%s.%s.%s.%s', static::rulesCacheVersion(), $country_id, $region_id, $based, $group);
+ $rules = $cache->cache(APP, $key, function() use ($country_id, $region_id, $based, $user_group_id): array {
$taxType = new Tax_typeSQL();
- $taxRules = $taxType->getRegionRules(['country_id' => $country_id, 'region_id' => $region_id, 'based' => $based]);
+ $params = ['country_id' => $country_id, 'region_id' => $region_id, 'based' => $based];
+
+ if ($user_group_id !== null && $user_group_id !== '') {
+ $params['user_group_id'] = $user_group_id;
+ }
+
+ $taxRules = $taxType->getRegionRules($params);
return $taxRules['tax_rule'] ?? [];
}, 259200);
@@ -62,18 +142,91 @@ class Tax {
}
}
- public function addTaxes($value, $taxTypeId, $onlyTax = false) {
+ /**
+ * Split a tax-inclusive (gross) amount into net amount and tax amount
+ * using the currently resolved rates for the given tax type.
+ *
+ * Percent rates are summed, fixed amounts are subtracted first
+ * (clamped to the gross amount). The tax is rounded to taxPrecision
+ * and the net derived from it so net + tax === gross.
+ *
+ * @param float|int|string $gross
+ * @param int|string $taxTypeId
+ *
+ * @return array{0: float, 1: float} [net, tax]
+ */
+ public function extractTax(float|int|string $gross, int|string $taxTypeId): array {
+ $gross = (float)$gross;
+ $percent = 0.0;
+ $fixed = 0.0;
+
+ foreach ($this->taxRates[$taxTypeId] ?? [] as $taxRate) {
+ if ($taxRate['type'] === 'f') {
+ $fixed += (float)$taxRate['rate'];
+ } else {
+ $percent += (float)$taxRate['rate'];
+ }
+ }
+
+ if ($percent <= 0 && $fixed <= 0) {
+ return [$gross, 0.0];
+ }
+
+ $fixed = min($fixed, $gross);
+ $tax = round($gross - (($gross - $fixed) / (1 + $percent / 100)), $this->taxPrecision);
+
+ return [$gross - $tax, $tax];
+ }
+
+ /**
+ * Calculate one tax rate amount for a value.
+ *
+ * @param float $value
+ * @param array<string, mixed> $taxRate Must contain rate/type keys.
+ *
+ * @return float
+ */
+ private function rateAmount(float $value, array $taxRate): float {
+ $rate = (float)($taxRate['rate'] ?? 0);
+
+ if (($taxRate['type'] ?? '') === 'f') {//fixed
+ return $rate;
+ }
+
+ if (($taxRate['type'] ?? '') === 'p') {//percent
+ return ($value / 100) * $rate;
+ }
+
+ return 0.0;
+ }
+
+ /**
+ * Calculate and add taxes for a given value.
+ *
+ * @param float|int|string $value
+ * @param int|string $taxTypeId
+ * @param bool $onlyTax When true only the tax amount is returned, otherwise value + tax.
+ *
+ * @return float|int
+ */
+ public function addTaxes(float|int|string $value, int|string $taxTypeId, bool $onlyTax = false): float|int {
+ if ($this->pricesIncludeTax) {
+ //value already includes tax, back the tax portion out so the
+ //total stays unchanged instead of stacking tax on tax
+ [, $tax] = $this->extractTax((float)$value, $taxTypeId);
+
+ if ($onlyTax) {
+ return $tax;
+ }
+
+ return $value;
+ }
+
$amount = 0;
if (isset($this->taxRates[$taxTypeId])) {
foreach ($this->taxRates[$taxTypeId] as $taxRate) {
- $rate = (float)$taxRate['rate'];
-
- if ($taxRate['type'] == 'f') {//fixed
- $amount += $rate;
- } elseif ($taxRate['type'] == 'p') {//percent
- $amount += (($value / 100) * $rate);
- }
+ $amount += $this->rateAmount((float)$value, $taxRate);
}
}
@@ -84,31 +237,34 @@ class Tax {
return $value + $amount;
}
- public function getRates($value, $taxTypeId) {
+ /**
+ * Get individual tax rates for a given value and tax type.
+ *
+ * @param float|int|string $value
+ * @param int|string $taxTypeId
+ *
+ * @return array<int, array{tax_rate_id: int|string, name: string, rate: string, type: string, amount: float|int}>
+ */
+ public function getRates(float|int|string $value, int|string $taxTypeId): array {
$taxRate_data = [];
+ if ($this->pricesIncludeTax) {
+ //back the net value out once so per-rate amounts below sum to
+ //the included tax instead of adding tax on top of gross
+ [$value] = $this->extractTax((float)$value, $taxTypeId);
+ }
+
if (isset($this->taxRates[$taxTypeId])) {
foreach ($this->taxRates[$taxTypeId] as $taxRate) {
- if (isset($taxRate_data[$taxRate['tax_rate_id']])) {
- $amount = $taxRate_data[$taxRate['tax_rate_id']]['amount'];
- } else {
- $amount = 0;
- }
- $rate = (float)$taxRate['rate'];
- $value = (float)$value;
-
- if ($taxRate['type'] == 'f') {
- $amount += $rate;
- } elseif ($taxRate['type'] == 'p') {
- $amount += (($value / 100) * $rate);
- }
+ $amount = $taxRate_data[$taxRate['tax_rate_id']]['amount'] ?? 0;
+ $amount += $this->rateAmount((float)$value, $taxRate);
$taxRate_data[$taxRate['tax_rate_id']] = [
- 'tax_rate_id' => $taxRate['tax_rate_id'],
- 'name' => $taxRate['name'],
- 'rate' => $taxRate['rate'],
- 'type' => $taxRate['type'],
- 'amount' => $amount,
+ 'tax_rate_id' => $taxRate['tax_rate_id'],
+ 'name' => $taxRate['name'],
+ 'rate' => $taxRate['rate'],
+ 'type' => $taxRate['type'],
+ 'amount' => $amount,
];
}
}
@@ -116,7 +272,68 @@ class Tax {
return $taxRate_data;
}
- public function clear() {
+ /**
+ * Tax for one order line: per-rate amounts rounded to taxPrecision
+ * before summing, so the line total matches the displayed rate
+ * breakdown exactly. Same rounding as TaxTrait::getTaxes().
+ *
+ * @param float|int|string $price
+ * @param int|string $taxTypeId
+ * @param float|int $quantity
+ *
+ * @return float
+ */
+ public function lineTax(float|int|string $price, int|string $taxTypeId, float|int $quantity = 1): float {
+ $total = 0.0;
+
+ foreach ($this->getRates($price, $taxTypeId) as $rate) {
+ $total += round($rate['amount'] * $quantity, $this->taxPrecision);
+ }
+
+ return $total;
+ }
+
+ /**
+ * Split a refund amount into net and tax portions, pro-rata from the
+ * still-unrefunded tax and total. The tax share is rounded to
+ * taxPrecision and clamped to the remaining recorded tax so sequential
+ * partial refunds can never reverse more tax than was collected; net is
+ * derived so net + tax === amount.
+ *
+ * @param float|int|string $amount Refund amount (gross).
+ * @param float|int|string $remainingTax Recorded tax not yet refunded.
+ * @param float|int|string $remainingTotal Order balance not yet refunded.
+ *
+ * @return array{0: float, 1: float} [net, tax]
+ */
+ public function refundSplit(float|int|string $amount, float|int|string $remainingTax, float|int|string $remainingTotal): array {
+ $amount = (float)$amount;
+ $remainingTax = max(0, (float)$remainingTax);
+ $remainingTotal = (float)$remainingTotal;
+
+ if ($amount <= 0 || $remainingTax <= 0 || $remainingTotal <= 0) {
+ return [$amount, 0.0];
+ }
+
+ $tax = min(round($amount * ($remainingTax / $remainingTotal), $this->taxPrecision), $remainingTax);
+
+ return [$amount - $tax, $tax];
+ }
+
+ public function clear(): void {
$this->taxRates = [];
}
+
+ /**
+ * Whether any region rules are currently loaded.
+ *
+ * Used to detect a rule set that matches nothing (e.g. destination
+ * zones configured for a different `based` value) so callers can
+ * fall back to the legacy store-based rules.
+ *
+ * @return bool
+ */
+ public function hasRates(): bool {
+ return $this->taxRates !== [];
+ }
}
diff --git a/system/cart/total-trait.php b/system/cart/total-trait.php
index c1683aa..a19788d 100644
--- a/system/cart/total-trait.php
+++ b/system/cart/total-trait.php
@@ -22,44 +22,78 @@
namespace Vvveb\System\Cart;
+/**
+ * Provides cart total management.
+ *
+ * @property Currency $currency
+ * @property array<int|string, array<array-key, mixed>> $products
+ * @property array<string, array{namespace: string, key: string, title: string, value: float|int|string, value_formatted: string|float, text: string}> $totals
+ */
trait TotalTrait {
- protected $totals = [];
-
- function addTotal($namespace, $key, $title, $value, $text = '') {
+ /** @var array<string, array{namespace: string, key: string, title: string, value: float|int|string, value_formatted: string|float, text: string}> */
+ protected array $totals = [];
+
+ /**
+ * Add a total entry.
+ *
+ * @param string $namespace
+ * @param string $key
+ * @param string $title
+ * @param float|int|string $value
+ * @param string $text
+ */
+ public function addTotal(string $namespace, string $key, string $title, float|int|string $value, string $text = ''): void {
$data = ['namespace' => $namespace, 'key' => $key, 'title' => $title, 'value' => $value, 'value_formatted' => $this->currency->format($value), 'text' => $text];
$this->totals[$key] = $data;
}
- function removeTotal($namespace, $key = false) {
+ /**
+ * Remove totals by namespace and optionally by key.
+ *
+ * @param string $namespace
+ * @param string|false $key
+ */
+ public function removeTotal(string $namespace, string|false $key = false): void {
if ($key) {
unset($this->totals[$key]);
} else {
foreach ($this->totals as $key => $total) {
- if ($total['namespace'] == $namespace) {
+ if ($total['namespace'] === $namespace) {
unset($this->totals[$key]);
}
}
}
}
- public function getSubTotal() {
+ /**
+ * Calculate the sub-total from all products.
+ */
+ public function getSubTotal(): float|int {
$total = 0;
foreach ($this->products as $product) {
- $total += $product['total'];
+ $total += $product['total'] ?? 0;
}
return $total;
}
- function getTotals($namespace = false, $key = false) {
+ /**
+ * Get totals filtered by namespace and/or key.
+ *
+ * @param string|false $namespace
+ * @param string|false $key
+ *
+ * @return array<string, mixed> Matching totals (single row when $key is given).
+ */
+ public function getTotals(string|false $namespace = false, string|false $key = false): array {
if ($key) {
- return $this->totals[$key];
- } else if ($namespace) {
+ return $this->totals[$key] ?? [];
+ } elseif ($namespace) {
$totals = [];
foreach ($this->totals as $key => $total) {
- if ($total['namespace'] == $namespace) {
+ if ($total['namespace'] === $namespace) {
$totals[$key] = $total;
}
}
@@ -70,7 +104,12 @@ trait TotalTrait {
return $this->totals;
}
- function getAllTotals() {
+ /**
+ * Calculate and return all totals including taxes and coupons.
+ *
+ * @return array<string, array{namespace: string, key: string, title: string, value: float|int|string, value_formatted: string|float, text: string}>
+ */
+ public function getAllTotals(): array {
//include taxes
$this->addTaxTotal();
$this->addCouponTotal();
@@ -78,7 +117,10 @@ trait TotalTrait {
return $this->totals;
}
- public function getGrandTotal() {
+ /**
+ * Calculate the grand total from all totals.
+ */
+ public function getGrandTotal(): float {
$sum = 0;
if ($this->totals) {
@@ -90,7 +132,10 @@ trait TotalTrait {
return $sum;
}
- public function getGrandTotalFormatted() {
+ /**
+ * Get the grand total formatted with the current currency.
+ */
+ public function getGrandTotalFormatted(): string|float {
$sum = $this->getGrandTotal();
return $this->currency->format($sum);
diff --git a/system/cart/total.php b/system/cart/total.php
deleted file mode 100755
index 549cccc..0000000
--- a/system/cart/total.php
+++ /dev/null
@@ -1,52 +0,0 @@
-<?php
-
-/**
- * Vvveb
- *
- * Copyright (C) 2022 Ziadin Givan
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <https://www.gnu.org/licenses/>.
- *
- */
-
-namespace Vvveb\System\Cart;
-
-class Total {
- protected $totals = [];
-
- function addTotal($key, $title, $cost, $text = '') {
- $data = ['title' => $title, 'cost' => $cost, 'cost_formatted' => '$' . $cost, 'text' => $text];
-
- $this->totals[$key] = $data;
- $this->write();
- }
-
- public function getGrandTotal() {
- $sum = 0;
-
- if ($this->totals) {
- foreach ($this->totals as $total) {
- $sum += $total['cost'];
- }
- }
-
- return $sum;
- }
-
- public function getGrandTotalFormatted() {
- $sum = $this->getGrandTotal();
-
- return '$' . $sum;
- }
-}
diff --git a/system/cart/weight.php b/system/cart/weight.php
old mode 100644
new mode 100755
index 53f4c6c..9756b72
--- a/system/cart/weight.php
+++ b/system/cart/weight.php
@@ -25,64 +25,84 @@ namespace Vvveb\System\Cart;
use Vvveb\Sql\Weight_typeSQL;
use Vvveb\System\Cache;
+/** @phpstan-consistent-constructor */
class Weight {
- private $weightRates = [];
+ /** @var array<int, array{value: float, unit: string}> */
+ private array $weightRates = [];
- public static function getInstance($options = []) {
- static $inst = null;
+ public static function getInstance(): static {
+ static $inst;
if ($inst === null) {
- $inst = new Weight($options);
+ $inst = new static();
}
return $inst;
}
- public function __construct($options = []) {
+ public function __construct() {
$this->setWeight();
}
- public function setWeight() {
- $cache = Cache::getInstance();
- $weights = $cache->cache(APP,'weight_type' ,function () {
+ /**
+ * Load weight types from cache / database.
+ */
+ public function setWeight(): void {
+ $cache = Cache::getInstance();
+ $this->weightRates = $cache->cache(APP, 'weight_type', function(): array {
$weightType = new Weight_typeSQL();
- $weights = $weightType->getAll(['start' => 0, 'limit' => 100]);
+ $weights = $weightType->getAll(['start' => 0, 'limit' => 100]);
return $weights['weight_type'] ?? [];
}, 259200);
}
- public function clear() {
+ public function clear(): void {
$this->weightRates = [];
}
- public function convert($value, $from, $to) : float {
- if ($from == $to) {
+ /**
+ * Convert a weight value between two weight types.
+ *
+ * @param float $value
+ * @param string|int $from
+ * @param string|int $to
+ */
+ public function convert(float $value, string|int $from, string|int $to): float {
+ if ($from === $to) {
return $value;
}
- if (isset($this->weightRates[$from])) {
- $from = $this->weightRates[$from]['value'];
- } else {
- $from = 1;
- }
+ $fromRate = $this->weightRates[$from]['value'] ?? 1;
+ $toRate = $this->weightRates[$to]['value'] ?? 1;
- if (isset($this->weightRates[$to])) {
- $to = $this->weightRates[$to]['value'];
- } else {
- $to = 1;
+ if (!$fromRate) {
+ return 0.0;
}
- return $value * ($to / $from);
+ return $value * ($toRate / $fromRate);
}
- public function format($value, $weightTypeId, $decimalPoint = '.', $thousandPoint = ',') {
+ /**
+ * Format a weight value with its unit.
+ *
+ * @param float $value
+ * @param string|int $weightTypeId
+ * @param string $decimalPoint
+ * @param string $thousandPoint
+ */
+ public function format(float $value, string|int $weightTypeId, string $decimalPoint = '.', string $thousandPoint = ','): string {
$unit = $this->weightRates[$weightTypeId]['unit'] ?? '';
return number_format($value, 2, $decimalPoint, $thousandPoint) . $unit;
}
- public function getUnit($weightTypeId) {
- $this->weightRates[$weightTypeId]['unit'] ?? '';
+ /**
+ * Get the unit string for a weight type.
+ *
+ * @param string|int $weightTypeId
+ */
+ public function getUnit(string|int $weightTypeId): string {
+ return $this->weightRates[$weightTypeId]['unit'] ?? '';
}
}
diff --git a/system/component/component-base.php b/system/component/component-base.php
index 808bed6..c7c87d5 100644
--- a/system/component/component-base.php
+++ b/system/component/component-base.php
@@ -24,6 +24,7 @@ namespace Vvveb\System\Component;
use function Vvveb\session as sess;
use function Vvveb\siteSettings;
+use Vvveb\System\Cache;
use Vvveb\System\Core\Request;
use Vvveb\System\Core\View;
use Vvveb\System\Event;
@@ -33,26 +34,37 @@ use Vvveb\System\User\User;
#[\AllowDynamicProperties]
class ComponentBase {
- public $cacheKey;
+ /** @var string|null Cache key for this component instance. */
+ public ?string $cacheKey = null;
- public $cacheExpire = 3600; //seconds
+ /** @var int Cache expiry time in seconds. */
+ public int $cacheExpire = 3600;
- public static $global;
+ /** @var array<string, mixed> Shared global context available to all component instances. */
+ public static array $global = [];
- protected $options;
+ /** @var array<array-key, mixed> Resolved options for this component instance. */
+ protected array $options = [];
- protected $_hash;
+ /** @var string|null Hash used to uniquely identify this component configuration. */
+ protected ?string $_hash = null;
- public static $defaultOptions = [];
+ /** @var array<array-key, mixed> Default options merged with global context; subclasses may override. */
+ public static array $defaultOptions = [];
- function __construct($options = []) {
+ /**
+ * Initialize the component, resolving options against global defaults and request data.
+ *
+ * @param array<array-key, mixed> $options Component-specific options (e.g. from data-v-* attributes).
+ */
+ public function __construct(array $options = []) {
$request = Request :: getInstance();
- if (! self :: $global) {
+ if (!self :: $global) {
$user = User::current();
$site = siteSettings();
self :: $global['start'] = 0;
- self :: $global['site_id'] = (APP == 'admin') ? sess('site_id') ?? SITE_ID : (defined('SITE_ID') ? SITE_ID : 0);
+ self :: $global['site_id'] = (APP === 'admin') ? sess('site_id') ?? SITE_ID : (defined('SITE_ID') ? SITE_ID : 0);
//self :: $global['site'] = siteSettings();
self :: $global['user_id'] = $user['user_id'] ?? null;
self :: $global['user_group_id'] = $user['user_group_id'] ?? 1;
@@ -67,7 +79,7 @@ class ComponentBase {
self :: $global['currencies'] = $site['currencies'] ?? [];
//don't set user session language for default language homepage
- if (! isset($request->get['module']) || $request->get['module'] != 'index/index') {
+ if (!isset($request->get['module']) || $request->get['module'] !== 'index/index') {
self :: $global['language'] = (sess('language') ?? self :: $global['language']);
self :: $global['language_id'] = (sess('language_id') ?? self :: $global['language_id']);
}
@@ -76,7 +88,7 @@ class ComponentBase {
(isset($request->get['language']) && is_string($request->get['language']) && ($lang = $request->get['language']))) {
$languages = Locale::availableLanguages();
if (isset($languages[$lang])) {
- self :: $global['language'] = $lang;
+ self :: $global['language'] = $lang;
self :: $global['language_id'] = $languages[$lang]['language_id'];
}
}
@@ -89,26 +101,26 @@ class ComponentBase {
static :: $defaultOptions += self :: $global;
foreach (['site_id', 'language_id', 'currency_id', 'user_id', 'user_group_id'] as $key) {
- if (! isset(static :: $defaultOptions[$key]) || empty(static :: $defaultOptions[$key])) {
+ if (!isset(static :: $defaultOptions[$key]) || empty(static :: $defaultOptions[$key])) {
static :: $defaultOptions[$key] = self :: $global[$key];
}
}
- if (isset(static :: $defaultOptions)) {
- $this->options = $this->filter($options);
- }
+ $this->options = $this->filter($options);
foreach ($this->options as $key => &$value) {
if (is_array($value)) {
foreach ($value as $val) {
- if (strpos($val, 'url') === 0) {
+ if (is_string($val) && str_starts_with($val, 'url')) {
//check if url parameter is specified ex: url.slug
- if ($dot = strrpos($val,'.')) {
- $key = substr($val, $dot + 1);
+ $lookupKey = $key;
+
+ if ($dot = strrpos($val, '.')) {
+ $lookupKey = substr($val, $dot + 1);
}
- if (isset($request->request[$key])) {
- $value = $request->request[$key];
+ if (isset($request->request[$lookupKey])) {
+ $value = $request->request[$lookupKey];
break;
} else {
@@ -122,13 +134,15 @@ class ComponentBase {
}
}
- if ($value && is_string($value) && strpos($value, 'url') === 0) {
+ if ($value && is_string($value) && str_starts_with($value, 'url')) {
//check if url parameter is specified ex: url.slug
- if ($dot = strrpos($value,'.')) {
- $key = substr($value, $dot + 1);
+ $lookupKey = $key;
+
+ if ($dot = strrpos($value, '.')) {
+ $lookupKey = substr($value, $dot + 1);
}
- $value = ($request->request[$key] ?? ($request->get[$key] ?? null));
+ $value = ($request->request[$lookupKey] ?? ($request->get[$lookupKey] ?? null));
}
if ($value === null) {
@@ -136,66 +150,73 @@ class ComponentBase {
}
}
- list($this->options) = Event :: trigger(get_class($this), __FUNCTION__, $this->options);
+ [$this->options] = Event :: trigger(static::class, __FUNCTION__, $this->options);
$this->di($this);
}
- static function di(&$component) {
+ /**
+ * Inject standard service dependencies into a component instance.
+ *
+ * @param self &$component The component to inject dependencies into.
+ *
+ * @return void
+ */
+ public static function di(self &$component): void {
$component->request = Request::getInstance();
$component->view = View::getInstance();
$component->session = Session::getInstance();
}
- function invalidateCache() {
- }
-
- function cacheKey() {
- if (isset($this->cacheKey)) {
+ /**
+ * Invalidate cached data for this component (stub for subclasses).
+ *
+ * @return void
+ */
+ public function invalidateCache(): void {}
+
+ /**
+ * Generate or retrieve the cache key for this component.
+ *
+ * @return string|null The cache key, or null if not yet generated.
+ */
+ public function cacheKey(): ?string {
+ if ($this->cacheKey !== null) {
return $this->cacheKey;
}
- $className = strtolower(str_replace(['Vvveb\Plugins\\', 'Vvveb\Component\\', '\Component\\'], '',get_class($this)));
- $this->cacheKey = str_replace('\\','-', $className) . '.' . md5(serialize($this->options));
+ $className = strtolower(str_replace(['Vvveb\Plugins\\', 'Vvveb\Component\\', '\Component\\'], '', static::class));
+ $this->cacheKey = str_replace('\\', '-', $className) . '.' . md5(serialize($this->options));
return $this->cacheKey;
}
- function filter(&$options) {
+ /**
+ * Filter and merge component options against the declared default options.
+ *
+ * @param array<array-key, mixed> &$options Raw options to filter (may contain _hash).
+ *
+ * @return array<array-key, mixed> Filtered options merged with defaults.
+ */
+ public function filter(array &$options): array {
//remove fields not declared in the class
- if (is_array($options)) {
- if (isset($options['_hash'])) {
- $this->_hash = $options['_hash'];
- unset($options['_hash']);
- }
-
- //$intersect = array_intersect_key($options, static :: $defaultOptions);
- //$diff = array_diff_key(static :: $defaultOptions, $options);
- //return $options = $intersect + $diff;
- return $options + static :: $defaultOptions;
- } else {
- return static :: $defaultOptions;
+ if (isset($options['_hash'])) {
+ $this->_hash = $options['_hash'];
+ unset($options['_hash']);
}
- return $options;
+ return $options + static :: $defaultOptions;
}
- function results() {
+ /**
+ * Retrieve cached results for this component.
+ *
+ * @return mixed Cached data or null if not cached.
+ */
+ public function results(): mixed {
//check cache
$cache = Cache :: getInstance();
- return $cache->get($this->cacheKey);
- }
-
- function generateCache($results) {
- $cache = Cache :: getInstance();
- $expire = $_SERVER['REQUEST_TIME'] + $this->cacheExpire;
-
- if (! $results) {
- $results = 0;
- }
- $cache->set($this->cacheKey, $results, $expire + COMPONENT_CACHE_EXPIRE);
-
- return $cache->set('expire_' . $this->cacheKey, $expire, $expire + COMPONENT_CACHE_EXPIRE);
+ return $cache->get('component', $this->cacheKey);
}
}
diff --git a/system/component/component.php b/system/component/component.php
index f0703c7..9c4d694 100644
--- a/system/component/component.php
+++ b/system/component/component.php
@@ -27,7 +27,7 @@ use function Vvveb\removeJsonComments;
use Vvveb\System\Cache;
use Vvveb\System\Core\View;
-if (! defined('COMPONENT_CACHE_FLAG_LOCK')) {
+if (!defined('COMPONENT_CACHE_FLAG_LOCK')) {
define('COMPONENT_CACHE_FLAG_LOCK', -10001);
define('COMPONENT_CACHE_FLAG_REGENERATE', -10002);
@@ -36,69 +36,96 @@ if (! defined('COMPONENT_CACHE_FLAG_LOCK')) {
define('COMPONENT_CACHE_WAIT', 1); //wait for cache generation
define('COMPONENT_CACHE_MAX_WAIT_RETRY', 3); //wait for cache generation
define('COMPONENT_CACHE_LOCK_EXPIRE', 20); //lock can not be set more than COMPONENT_CACHE_LOCK_EXPIRE seconds
- define('COMPONENT_CACHE_EXPIRE', 20 * 3600);
+ define('COMPONENT_CACHE_EXPIRE', 20 * 3600);
}
+/**
+ * Discovers data components declared in templates via data-v-component-* attributes,
+ * instantiates them (with a per-cache-key shared-results cache including a
+ * lock/regenerate protocol) and stores their results on the view.
+ */
class Component {
- static private $instance;
+ /** @var self|null Singleton instance. */
+ private static ?self $instance = null;
- private $queue;
+ /** @var array<string, list<array<string, mixed>>>|null Parsed component definitions keyed by component name. */
+ private ?array $components = [];
- private $components = [];
+ /** @var string|null Path to the cached component definitions file. */
+ private ?string $componentsFile = null;
- private $componentsFile;
+ /** @var bool Whether component definitions have been loaded. */
+ private bool $loaded = false;
- private $loaded;
+ /** @var string|false|null Raw page content to parse for components. */
+ private string|false|null $content = false;
- private $content;
+ /** @var View View instance for template access. */
+ private View $view;
- private $view;
+ /** @var string Application context (e.g. 'app', 'admin'). */
+ private string $app = 'app';
- private $app;
+ /** @var string Document type of the template ('html', 'xml', 'json'). */
+ private string $documentType = 'html';
- private $documentType = 'html';
+ /** @var bool Whether to use component caching. */
+ private bool $cache = true;
- private $cache = true;
-
- private $copyFromElements = [];
+ /** @var array<string, array<string, \DOMXPath|\DOMNodeList<\DOMNode>>> Cached copy-from element results keyed by file and selector. */
+ private array $copyFromElements = [];
- static function getInstance($view = false, $regenerate = false, $content = false, $app = null) {
- if (self :: $instance === NULL) {
- if (! $view) {
+ /**
+ * Get or create the singleton Component instance.
+ *
+ * @param View|false|null $view View instance to use, or false/null to obtain the default.
+ * @param bool $regenerate Force regeneration of component definitions.
+ * @param string|null $content Raw HTML/XML content to parse instead of a template file.
+ * @param string|null $app Application context override.
+ *
+ * @return self The singleton Component instance.
+ */
+ public static function getInstance(View|false|null $view = false, bool $regenerate = false, ?string $content = null, ?string $app = null): self {
+ if (self::$instance === null) {
+ if (!$view) {
$view = View::getInstance();
}
- self :: $instance = new self($view, $regenerate, $content);
+ self::$instance = new self($view, $regenerate, $content, $app);
}
- return self :: $instance;
+ return self::$instance;
}
- function __construct($view, $regenerate = false, $content = false, $app = null) {
+ /**
+ * Parse templates, discover components, and optionally cache the definitions.
+ *
+ * @param View|false $view View instance providing template paths.
+ * @param bool $regenerate Force regeneration of the component cache file.
+ * @param string|null $content Raw content to parse instead of loading a template file.
+ * @param string|null $app Application context override (defaults to APP constant).
+ */
+ public function __construct(View|false $view, bool $regenerate = false, ?string $content = null, ?string $app = null) {
if ($this->loaded) {
- return true;
+ return;
}
$this->app = $app ?? APP;
- if (! $view) {
+ if (!$view) {
$view = View::getInstance();
}
- $this->view = $view;
-
+ $this->view = $view;
$this->componentsFile = $view->serviceTemplate() . '.component';
$this->content = $content;
- if ((! file_exists($this->componentsFile)) || $regenerate) {
+ if ((!file_exists($this->componentsFile)) || $regenerate) {
$this->generateRequiredComponents();
$this->saveTemplateComponents();
$this->loadComponents();
$this->loaded = true;
- } else {
- }
- if ($this->loaded) {
- return true;
+ return;
}
$this->loadTemplateComponents();
@@ -106,216 +133,365 @@ class Component {
$this->loaded = true;
}
- function isComponent($name) {
+ /**
+ * Parse a "plugin-{plugin}-{namespace}" component name into its parts.
+ *
+ * @param string $name Component name.
+ *
+ * @return array{plugin_name: string, namespace: string, class: string, file: string}|null Null when the name is not a plugin component.
+ */
+ public function pluginComponentDetails(string $name): ?array {
+ if (!str_starts_with($name, 'plugin')) {
+ return null;
+ }
+
+ $template = str_replace('plugin', '', $name);
+ $p = strrpos($template, '-');
+
+ if ($p === false) {
+ return null;
+ }
+ $pluginName = substr($template, 1, $p - 1);
+ $nameSpace = substr($template, $p + 1);
+
+ $pluginClassName = dashesToCamelCase($pluginName);
+
+ return [
+ 'plugin_name' => $pluginName,
+ 'namespace' => $nameSpace,
+ 'class' => "Vvveb\\Plugins\\$pluginClassName\\Component\\$nameSpace",
+ 'file' => DIR_PLUGINS . "$pluginName/component/" . str_replace('-', '/', $nameSpace) . '.php',
+ ];
+ }
+
+ /**
+ * Resolve the class name and definition file for a component name.
+ *
+ * Core components live in app/component/ (or admin/component/); plugin
+ * components in plugins/{plugin}/component/.
+ *
+ * @param string $component Component name (e.g. 'posts', 'plugin-saas-sites').
+ * @param bool $ucfirstClass Whether to ucfirst() the core component class segment.
+ *
+ * @return array{class: string, file: string}
+ */
+ private function resolveComponentClass(string $component, bool $ucfirstClass = false): array {
+ $details = $this->pluginComponentDetails($component);
+
+ if ($details) {
+ return ['class' => $details['class'], 'file' => $details['file']];
+ }
+
+ $segments = str_replace('-', '\\', $component);
+ if ($ucfirstClass) {
+ $segments = ucfirst($segments);
+ }
+
+ return [
+ 'class' => '\Vvveb\Component\\' . $segments,
+ 'file' => DIR_ROOT . $this->app . DS . 'component' . DS . str_replace('-', '/', $component) . '.php',
+ ];
+ }
+
+ /**
+ * Convert a component name to the underscore form used for view storage.
+ *
+ * @param string $component
+ */
+ private function normalizeComponentName(string $component): string {
+ return str_replace('-', '_', $component);
+ }
+
+ /**
+ * Check whether a component with the given name exists in the parsed definitions.
+ *
+ * @param string $name Component name (e.g. 'content-blog').
+ *
+ * @return bool True if the component is defined.
+ */
+ public function isComponent(string $name): bool {
return isset($this->components[$name]);
}
- function getComponent($name) {
+ /**
+ * Retrieve the parsed definition array for a component.
+ *
+ * @param string $name Component name.
+ *
+ * @return list<array<string, mixed>> Component instances and options, or empty array if not found.
+ */
+ public function getComponent(string $name): array {
return $this->components[$name] ?? [];
}
- function loadComponents() {
- $view = $this->view;
+ /**
+ * Assign a component's results on the view under its normalized name.
+ *
+ * @param View $view
+ * @param string $component
+ * @param mixed $index
+ * @param mixed $results
+ */
+ private function assignResults(View $view, string $component, $index, &$results): void {
+ $component = $this->normalizeComponentName($component);
+ $comp = &$view->_component[$component];
+ $comp[$index] = $results;
+ }
- $cache = [];
- $objs = [];
- $namespace = 'component';
+ /**
+ * Check whether results flagged a not-found condition.
+ *
+ * @param mixed $results
+ */
+ private function isNotFound($results): bool {
+ return isset($results['404']) && $results['404'] === true;
+ }
+ /**
+ * Load, cache, and instantiate all discovered components, then dispatch request callbacks.
+ *
+ * @return void
+ */
+ public function loadComponents(): void {
+ $view = $this->view;
$notFound404 = false;
if (is_array($this->components)) {
- foreach ($this->components as $component => $instances) {
- if (strpos($component, 'plugin') === 0) {
- $template = str_replace('plugin', '', $component);
- $p = strrpos($template, '-');
- $pluginName = substr($template, 1, $p - 1);
- $nameSpace = substr($template, $p + 1);
- $app = '';
-
- $pluginClassName = dashesToCamelCase($pluginName);
- $class = "Vvveb\Plugins\\$pluginClassName\Component\\$nameSpace";
- $file = DIR_PLUGINS . "$pluginName/component/" . str_replace('-', '/', $nameSpace) . '.php';
- } else {
- $class = '\Vvveb\Component\\' . str_replace('-', '\\', $component);
- $file = DIR_ROOT . $this->app . DS . 'component' . DS . str_replace('-', '/', $component) . '.php';
- }
+ [$cache, $objs, $notFound404] = $this->instantiateComponents($notFound404);
- $component = str_replace('-', '_', $component);
+ if ($this->cache) {
+ $this->processComponentCache($cache, $objs, $notFound404);
+ }
+ }
- if (file_exists($file)) {
- include_once $file;
+ $this->dispatchComponentRequests();
- foreach ($instances as $instance => $options) {
- $obj = new $class($options);
+ $this->components = null;
- if ($obj->cacheExpire && $this->cache && ($cacheKey = $obj->cacheKey())) {
- $cacheExpireKey = $cacheKey . '_expire';
- $cache[] = $cacheKey;
- $cache[] = $cacheExpireKey;
- $obj->component = $component;
- $objs[$obj->cacheKey][$instance] = $obj;
- } else {
- $results = $obj->results();
+ if ($notFound404) {
+ \Vvveb\System\Core\FrontController::notFound(false);
+ }
+ }
- if ($results !== false && $results !== null) {
- $results['_instance'] = $obj;
- }
+ /**
+ * Include every component class file and instantiate its objects; components
+ * without caching get their results fetched immediately into the view.
+ *
+ * @param bool $notFound404 Not-found accumulator (updated by reference).
+ *
+ * @return array{0: array<array-key, mixed>, 1: array<array-key, mixed>, 2: bool} [$cache, $objs, $notFound404]
+ */
+ private function instantiateComponents(bool $notFound404 = false): array {
+ $view = $this->view;
+ $objs = [];
+ $cache = [];
+
+ foreach ($this->components ?? [] as $component => $instances) {
+ ['class' => $class, 'file' => $file] = $this->resolveComponentClass($component);
+ $component = $this->normalizeComponentName($component);
+
+ if (!file_exists($file)) {
+ continue;
+ }
- $comp = &$view->_component[$component];
- $comp[$instance] = $results;
+ include_once $file;
- if (isset($results['404']) && $results['404'] == true) {
- $notFound404 = true;
- }
- }
+ foreach ($instances as $instance => $options) {
+ $obj = new $class($options);
+
+ if ($obj->cacheExpire && $this->cache && ($cacheKey = $obj->cacheKey())) {
+ $cache[] = $cacheKey;
+ $cache[] = $cacheKey . '_expire';
+ $obj->component = $component;
+ $objs[$obj->cacheKey][$instance] = $obj;
+ } else {
+ $results = $obj->results();
+
+ if ($results !== false && $results !== null) {
+ $results['_instance'] = $obj;
+ }
+
+ $this->assignResults($view, $component, $instance, $results);
+
+ if ($this->isNotFound($results)) {
+ $notFound404 = true;
}
}
}
+ }
- if ($this->cache) {
- //get cached data
- $cacheDriver = Cache::getInstance();
- //$cacheDriver = new Memcached();
- $null = [];
- $data = $cacheDriver->getMulti($namespace, $cache, SITE_ID) ?? [];
-
- foreach ($objs as $cacheKey => $instances) {
- foreach ($instances as $index => $instance) {
- if (! isset($data[$cacheKey]) || ! is_array($data[$cacheKey])) {
- $data[$cacheKey] = [];
- }
+ return [$cache, $objs, $notFound404];
+ }
- $component = $instance->component;
- $component = str_replace('-', '_', $component);
- $data[$cacheKey]['_instance'] = $instance;
- $comp = &$view->_component[$component];
- $comp[$index] = $data[$cacheKey];
+ /**
+ * Read cached results for all cached component objects, hydrate the view,
+ * mark entries that need regeneration (setting a distributed lock while
+ * regenerating) and wait for other processes that hold a lock.
+ *
+ * @param array<array-key, mixed> $cache Cache keys (keys interleaved with their "_expire" keys).
+ * @param array<array-key, mixed> $objs Cached component objects grouped by cache key.
+ * @param bool $notFound404 Not-found accumulator (updated by reference).
+ *
+ * @return void
+ */
+ private function processComponentCache(array $cache, array $objs, bool &$notFound404): void {
+ $view = $this->view;
+ $namespace = 'component';
- if (isset($comp[$index]['404']) && $comp[$index]['404'] == true) {
- $notFound404 = true;
- }
- }
+ //get cached data
+ $cacheDriver = Cache::getInstance();
+ $data = $cacheDriver->getMulti($namespace, $cache, SITE_ID);
- //cache hit, remove from sql regeneration queue
- $cacheExpireKey = $cacheKey . '_expire';
+ foreach ($objs as $cacheKey => $instances) {
+ foreach ($instances as $index => $instance) {
+ if (!isset($data[$cacheKey]) || !is_array($data[$cacheKey])) {
+ $data[$cacheKey] = [];
+ }
- //if no lock set (! -1) and cache is expiring then set lock and set for regeneration
- if (! isset($data[$cacheExpireKey]) || ! isset($data[$cacheKey]) ||
- ($data[$cacheExpireKey] && ($data[$cacheExpireKey] > 0) &&
- ($data[$cacheExpireKey] + COMPONENT_CACHE_EXPIRE_DELAY) < $_SERVER['REQUEST_TIME'])) {
- ignore_user_abort();
- $cacheDriver->set($namespace, $cacheExpireKey, COMPONENT_CACHE_FLAG_LOCK, COMPONENT_CACHE_LOCK_EXPIRE); //set lock
- $data[$cacheExpireKey] = COMPONENT_CACHE_FLAG_REGENERATE; //set regeneration flag
- }
+ $data[$cacheKey]['_instance'] = $instance;
+ $this->assignResults($view, $instance->component, $index, $data[$cacheKey]);
- if ($data[$cacheExpireKey] > 0) {
- unset($objs[$cacheKey], $cache[$cacheKey], $cache[$cacheExpireKey], $data[$cacheKey], $data[$cacheExpireKey]);
- }
+ if (isset($data[$cacheKey]['404']) && $data[$cacheKey]['404'] === true) {
+ $notFound404 = true;
}
+ }
- $wait = true;
- $retry = 0;
- //run sql queries for uncached components
- $saveCache = [];
+ $cacheExpireKey = $cacheKey . '_expire';
- while ($wait && $retry < COMPONENT_CACHE_MAX_WAIT_RETRY) {
- $wait = false;
- $retry++;
+ //if no lock set and cache is expiring then set lock and queue regeneration
+ if (!isset($data[$cacheExpireKey]) ||
+ ($data[$cacheExpireKey] && ($data[$cacheExpireKey] > 0) &&
+ ($data[$cacheExpireKey] + COMPONENT_CACHE_EXPIRE_DELAY) < $_SERVER['REQUEST_TIME'])) {
+ ignore_user_abort();
+ $cacheDriver->set($namespace, $cacheExpireKey, COMPONENT_CACHE_FLAG_LOCK, COMPONENT_CACHE_LOCK_EXPIRE); //set lock
+ $data[$cacheExpireKey] = COMPONENT_CACHE_FLAG_REGENERATE; //set regeneration flag
+ }
- foreach ($objs as $key => $objects) {
- $cacheExpireKey = $key . '_expire';
+ if ($data[$cacheExpireKey] > 0) {
+ //fresh cache, remove from sql regeneration queue
+ unset($objs[$cacheKey], $cache[$cacheKey], $cache[$cacheExpireKey], $data[$cacheKey], $data[$cacheExpireKey]);
+ }
+ }
- //check lock
- if ((! isset($data[$cacheExpireKey]) || ! ($data[$cacheExpireKey])) ||
- ! isset($data[$key]) ||
- $data[$cacheExpireKey] == COMPONENT_CACHE_FLAG_REGENERATE) {
- //lock set by this script, regenerate content
- $id = key($objects);
+ $retry = 0;
+ //run sql queries for uncached components
+ $saveCache = [];
- $results = $objects[$id]->results();
+ do {
+ $retry++;
- if ($results !== null) {
- $saveCache[$key] = $results;
- $saveCache[$cacheExpireKey] = $objects[$id]->cacheExpire;
- }
+ $wait = $this->regenerateUncachedComponents($objs, $data, $saveCache, $notFound404);
- if (isset($results['404']) && $results['404'] == true) {
- $notFound404 = true;
- }
+ if ($wait) {
+ if (defined('DEBUG') && DEBUG) {
+ error_log('wait cache ' . ($_SERVER['HTTP_HOST'] ?? '') . ($_SERVER['REQUEST_URI'] ?? ''));
+ }
- $data[$cacheExpireKey] = 0;
+ @sleep(COMPONENT_CACHE_WAIT);
+ $data = $cacheDriver->getMulti($namespace, $cache, SITE_ID);
+ }
+ } while ($wait && $retry < COMPONENT_CACHE_MAX_WAIT_RETRY);
- foreach ($objects as $index => $instance) {
- $results['_instance'] = $instance;
- $component = $instance->component;
- $component = str_replace('-', '_', $component);
- $comp = &$view->_component[$component];
- $comp[$index] = $results;
- }
- } else {
- if ($data[$cacheExpireKey] == COMPONENT_CACHE_FLAG_LOCK) {
- //error_log("wait for $cacheExpireKey");
- //item is locked, some other script is generating content
- $wait = true;
- }
- }
- }
+ if ($retry >= COMPONENT_CACHE_MAX_WAIT_RETRY) {
+ error_log('error:CACHE max retry reached for ' . ($_SERVER['HTTP_HOST'] ?? '') . ($_SERVER['REQUEST_URI'] ?? ''));
+ }
- if ($wait) {
- error_log('wait cache ' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . print_r($cache,1));
- //get
- @sleep(COMPONENT_CACHE_WAIT);
- $data = $cacheDriver->getMulti($namespace, $cache, SITE_ID);
- }
+ if (!empty($saveCache)) {
+ $cacheDriver->setMulti($namespace, $saveCache, COMPONENT_CACHE_EXPIRE, SITE_ID);
+ }
+ }
+
+ /**
+ * Run results() for components queued for regeneration; components locked
+ * by another request are left for a later retry pass.
+ *
+ * @param array<array-key, mixed> $objs Cached component objects grouped by cache key (by value).
+ * @param array<array-key, mixed> $data Cached data (updated by reference).
+ * @param array<array-key, mixed> $saveCache Results to persist (updated by reference).
+ * @param bool $notFound404 Not-found accumulator (updated by reference).
+ *
+ * @return bool True when some component was locked and another pass is needed.
+ */
+ private function regenerateUncachedComponents(array $objs, array &$data, array &$saveCache, bool &$notFound404): bool {
+ $view = $this->view;
+ $wait = false;
+
+ foreach ($objs as $key => $objects) {
+ $cacheExpireKey = $key . '_expire';
+
+ //check lock
+ if ((!isset($data[$cacheExpireKey]) || !($data[$cacheExpireKey])) ||
+ !isset($data[$key]) ||
+ $data[$cacheExpireKey] === COMPONENT_CACHE_FLAG_REGENERATE) {
+ //lock set by this script, regenerate content
+ $id = key($objects);
+
+ $results = $objects[$id]->results();
+
+ if ($results !== null) {
+ $saveCache[$key] = $results;
+ $saveCache[$cacheExpireKey] = $objects[$id]->cacheExpire;
}
- if ($retry >= COMPONENT_CACHE_MAX_WAIT_RETRY) {
- error_log('error:CACHE max retry reached for ' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
+ if ($this->isNotFound($results)) {
+ $notFound404 = true;
}
- }
- if (! empty($saveCache)) {
- $cacheDriver->setMulti($namespace, $saveCache, /*$_SERVER['REQUEST_TIME'] + */COMPONENT_CACHE_EXPIRE, SITE_ID);
+ $data[$cacheExpireKey] = 0;
+
+ foreach ($objects as $index => $instance) {
+ $results['_instance'] = $instance;
+ $this->assignResults($view, $instance->component, $index, $results);
+ }
+ } elseif ($data[$cacheExpireKey] === COMPONENT_CACHE_FLAG_LOCK) {
+ //item is locked, some other script is generating content
+ $wait = true;
}
}
- //call request for each component
+ return $wait;
+ }
- foreach ($this->components as $component => $instances) {
- foreach ($instances as $index => $options) {
- $component = str_replace('-', '_', $component);
+ /**
+ * Call the request() callback of every component instance that has results.
+ */
+ private function dispatchComponentRequests(): void {
+ $view = $this->view;
- if (isset($view->_component[$component])) {
- $comp = &$view->_component[$component];
- $results = &$comp[$index];
- $object = $results['_instance'] ?? false;
+ foreach ($this->components ?? [] as $component => $instances) {
+ $component = $this->normalizeComponentName($component);
- if ($object && method_exists($object, 'request')) {
- $object->request($results, $index);
- }
- }
+ if (!isset($view->_component[$component])) {
+ continue;
}
- }
- unset($data, $cache);
- $this->components = NULL;
+ $comp = &$view->_component[$component];
- if ($notFound404) {
- \Vvveb\System\Core\FrontController::notFound(false);
+ foreach ($instances as $index => $options) {
+ $results = &$comp[$index];
+ $object = $results['_instance'] ?? false;
+
+ if ($object && method_exists($object, 'request')) {
+ $object->request($results, $index);
+ }
+ }
}
}
- /* static function isLoaded($component)
- {
- return isset($this->queue[$component]);
- }
- */
- function results() {
+ /**
+ * Get component results (stub for subclasses).
+ *
+ * @return mixed
+ */
+ public function results(): mixed {
+ return null;
}
- function generateRequiredComponents() {
- //get components from html page
- $document = new \DomDocument();
+ /**
+ * Create a DOM document configured for lenient template parsing.
+ */
+ private function createDomDocument(): \DOMDocument {
+ $document = new \DOMDocument();
$document->preserveWhiteSpace = false;
$document->recover = true;
$document->strictErrorChecking = false;
@@ -324,95 +500,123 @@ class Component {
$document->validateOnParse = false;
$document->xmlStandalone = true;
- $view = view::getInstance();
+ return $document;
+ }
+
+ /**
+ * Resolve the absolute file path of a relative template path; paths inside
+ * plugins ("plugins/{plugin}/{path}") resolve to the plugin public folder.
+ *
+ * Absolute paths (starting with "/") are used as-is.
+ *
+ * @param string $template
+ */
+ private function resolveTemplateFilePath(string $template): string {
+ //absolute path as it is
+ if ($template[0] === '/') {
+ return $template;
+ }
+
+ if (str_starts_with($template, 'plugins/')) {
+ $template = str_replace('plugins/', '', $template);
+ $p = strpos($template, '/');
+ $pluginName = substr($template, 0, $p);
+ $nameSpace = substr($template, $p + 1);
+ $app = '';
+
+ if ($this->app !== 'app') {
+ $app = $this->app . DS;
+ }
+
+ return DIR_PLUGINS . $pluginName . DS . 'public' . DS . $app . $nameSpace;
+ }
+
+ $view = $this->view;
+
+ return $view->getTemplatePath() . $template;
+ }
+
+ /**
+ * Load the current content/template into the document, converting json
+ * templates through an xml representation.
+ *
+ * @param \DOMDocument $document
+ */
+ private function loadTemplateDocument(\DOMDocument $document): void {
+ $view = $this->view;
libxml_use_internal_errors(true);
$this->documentType = $view->getDocumentType();
if ($this->content) {
- if ($this->documentType == 'html') {
+ if ($this->documentType === 'html') {
@$document->loadHTML($this->content);
} else {
@$document->loadXML($this->content);
}
- } else {
- $view = $this->view;
- $template = $view->template();
- $extension = strtolower(trim(substr($template, -4), '.'));
- $this->documentType = $extension;
- if ($template[0] == '/') {
- } else {
- if (strpos($template, 'plugins/') === 0) {
- $template = str_replace('plugins/', '', $template);
- $p = strpos($template, '/');
- $pluginName = substr($template, 0, $p);
- $nameSpace = substr($template, $p + 1);
- $app = '';
-
- if ($this->app != 'app') {
- $app = $this->app . DS;
- }
- $template = DIR_PLUGINS . $pluginName . DS . 'public' . DS . $app . $nameSpace;
- } else {
- $template = $view->getTemplatePath() . $template;
- }
- }
+ return;
+ }
- if ($this->documentType == 'html') {
- @$document->loadHTMLFile($template,
- LIBXML_NOWARNING | LIBXML_NOERROR);
+ $template = $this->view->template();
+ $extension = strtolower(trim(substr($template, -4), '.'));
+ $this->documentType = $extension;
+ $template = $this->resolveTemplateFilePath($template);
+
+ if ($this->documentType === 'html') {
+ @$document->loadHTMLFile($template, LIBXML_NOWARNING | LIBXML_NOERROR);
+ } else {
+ $content = file_get_contents($template);
+
+ if ($this->documentType === 'json') {
+ //remove json comments from line start
+ $content = removeJsonComments($content);
+ $json = json_decode($content, true);
+ $json = \Vvveb\prepareJson($json);
+ $xml = \Vvveb\array2xml($json);
+ @$document->loadXML($xml);
} else {
- $content = file_get_contents($template);
-
- if ($this->documentType == 'json') {
- //remove json comments from line start
- $content = removeJsonComments($content);
- $json = json_decode($content, true);
- $json = \Vvveb\prepareJson($json);
- $xml = \Vvveb\array2xml($json);
- @$document->loadXML($xml);
- } else {
- @$document->loadXML($content,
- LIBXML_NOWARNING | LIBXML_NOERROR);
- }
+ @$document->loadXML($content, LIBXML_NOWARNING | LIBXML_NOERROR);
}
}
+ }
- $xpath = new \DOMXpath($document);
- $i = 0;
+ /**
+ * Expand data-v-copy-from / data-v-save-global attributes by pulling the
+ * referenced elements from external files into the document.
+ *
+ * @param \DOMXpath $xpath
+ * @param \DOMDocument $document
+ */
+ private function expandCopyFromElements(\DOMXPath $xpath, \DOMDocument $document): void {
+ $view = $this->view;
+ $i = 0;
//include froms in case any component_ is included
while (($elements = $xpath->query('//*[ @data-v-copy-from or @data-v-save-global ]')) && $elements->length && $i++ < 2) {
- $fromDocument = new \DomDocument();
- $fromDocument->preserveWhiteSpace = false;
- $fromDocument->recover = true;
- $fromDocument->strictErrorChecking = false;
- $fromDocument->formatOutput = false;
- $fromDocument->resolveExternals = false;
- $fromDocument->validateOnParse = false;
- $fromDocument->xmlStandalone = true;
+ $fromDocument = $this->createDomDocument();
foreach ($elements as $element) {
$attribute = $element->getAttribute('data-v-copy-from') ?: $element->getAttribute('data-v-save-global');
$element->removeAttribute('data-v-copy-from');
$element->removeAttribute('data-v-save-global');
- if (preg_match('/([^\,]+)\,([^$,]+)/', $attribute , $from)) {
+ if (preg_match('/([^\,]+)\,([^$,]+)/', $attribute, $from)) {
$file = html_entity_decode(trim($from[1]));
$selector = html_entity_decode(trim($from[2]));
-
+
if (isset($this->copyFromElements[$file][$selector])) {
$fromElements = $this->copyFromElements[$file][$selector];
} else {
- if ($this->documentType == 'html') {
- $fromDocument->loadHTMLFile($view->getTemplatePath() . $file);
+ if ($this->documentType === 'html') {
+ $fromDocument->loadHTMLFile($view->getTemplatePath() . $file, LIBXML_NOWARNING | LIBXML_NOERROR);
} else {
- $fromDocument->loadXML($view->getTemplatePath() . $file);
+ //load() reads from a file path, unlike loadXML() which expects the xml content
+ @$fromDocument->load($view->getTemplatePath() . $file, LIBXML_NOWARNING | LIBXML_NOERROR);
}
- $fromXpath = new \DOMXpath($fromDocument);
+ $fromXpath = new \DOMXPath($fromDocument);
- $fromElements = $fromXpath->query(\Vvveb\cssToXpath($selector));
+ $fromElements = $fromXpath->query(\Vvveb\cssToXpath($selector));
$this->copyFromElements[$file][$selector] = $fromElements;
}
@@ -429,116 +633,131 @@ class Component {
$parent->replaceChild($importedNode, $element);
}
$element = $importedNode;
- //$parent = $element->parentNode;
$count++;
}
}
}
}
}
+ }
- //search for elements that have an attribute starting with data-v-component-
- $elements = $xpath->query('//*[@*[starts-with(name(), "data-v-component-")]]');
+ /**
+ * Extract options from data-v-* attributes of an element, validate them
+ * against the component class defaults and compute the instance hash.
+ *
+ * @param mixed $element
+ *
+ * @return array{component: string, options: array<array-key, mixed>}|null Null when the element must be skipped.
+ */
+ private function parseComponentElement($element): ?array {
+ $component = '';
+ $opts = [];
+
+ foreach ($element->attributes as $attr) {
+ $nodeName = $attr->nodeName;
+
+ if (str_starts_with($nodeName, 'data-v-component-')) {
+ $component = str_replace('data-v-component-', '', $nodeName);
+ } elseif (str_starts_with($nodeName, 'data-v-')) {
+ $option = str_replace('data-v-', '', $nodeName);
+ $opts[$option] = $attr->nodeValue;
+ }
+ }
- foreach ($elements as $element) {
- $component = '';
- $opts = [];
+ ['class' => $componentClass, 'file' => $file] = $this->resolveComponentClass($component, true);
+
+ if (!file_exists($file)) {
+ if (defined('DEBUG') && \DEBUG) {
+ error_log("Component does not exist $componentClass => $file");
+ }
+
+ return null;
+ }
- foreach ($element->attributes as $attr) {
- $nodeName = $attr->nodeName;
+ include_once $file;
- if (strpos($nodeName, 'data-v-component-') === 0) {
- $component = str_replace('data-v-component-', '', $nodeName);
- //$classes = explode(' ', trim($attr->nodeValue));
+ //do not add design only components
+ if (isset($componentClass::$designOnly) && $componentClass::$designOnly === true) {
+ return null;
+ }
+
+ $validOptions = array_keys($componentClass::$defaultOptions);
+ $options = [];
+
+ //save options
+ foreach ($opts as $name => $option) {
+ if (in_array($name, $validOptions) && $option !== null) {
+ if ((isset($option[0]) && ($option[0] === '{' || $option[0] === '[')) || (str_contains($option, ','))) {
+ $options[$name] = json_decode($option, true);
} else {
- if (strpos($nodeName, 'data-v-') === 0) {
- $option = str_replace('data-v-', '', $nodeName);
- $opts[$option] = $attr->nodeValue;
- }
- }
- }
- //get all classes
- //search for options
- $options = null;
- //validate options
- $validOptions = [];
-
- if (strpos($component, 'plugin') === 0) {
- $template = str_replace('plugin', '', $component);
- $p = strrpos($template, '-');
- $pluginName = substr($template, 1, $p - 1);
- $nameSpace = substr($template, $p + 1);
- $app = '';
-
- if ($this->app != 'app') {
- $app = $this->app . DS;
+ $options[$name] = $option;
}
- $pluginClassName = dashesToCamelCase($pluginName);
- $componentClass = "Vvveb\Plugins\\$pluginClassName\Component\\$nameSpace";
- $file = DIR_PLUGINS . "$pluginName/component/" . str_replace('-', '/', $nameSpace) . '.php';
- } else {
- $componentClass = '\Vvveb\Component\\' . ucfirst(str_replace('-', '\\', $component));
- $file = DIR_ROOT . $this->app . DS . 'component/' . str_replace('-', '/', $component) . '.php';
}
+ }
- if (file_exists($file)) {
- include_once $file;
- //$componentClass = new $componentClass;
- //do not add design only components
- if (isset($componentClass::$designOnly) && $componentClass::$designOnly == true) {
- continue;
- }
- $validOptions = array_keys($componentClass::$defaultOptions);
- } else {
- if (defined('DEBUG') && \DEBUG) {
- error_log("Component does not exist $componentClass => $file");
- //die("Component does not exist $componentClass => $file");
- }
+ $options['_hash'] = md5($component . serialize($options));
- continue;
- }
+ return ['component' => $component, 'options' => $options];
+ }
- //save options
- foreach ($opts as $name => $option) {
- if (in_array($name, $validOptions) && isset($option) !== false) {
- if ((isset($option[0]) && ($option[0] == '{' || $option[0] == '[')) || (strpos($option, ',') !== false)) {
- $options[$name] = json_decode($option, 1);
- } else {
- $options[$name] = $option;
- }
- }
- }
+ /**
+ * Parse the template file (HTML/XML/JSON) and extract component definitions from data-v-component-* attributes.
+ *
+ * @return void
+ */
+ public function generateRequiredComponents(): void {
+ $document = $this->createDomDocument();
+
+ $this->loadTemplateDocument($document);
+
+ $xpath = new \DOMXPath($document);
- $options['_hash'] = md5($component . serialize($options));
- $components[$component][] = $options;
+ $this->expandCopyFromElements($xpath, $document);
+
+ //search for elements that have an attribute starting with data-v-component-
+ $elements = $xpath->query('//*[@*[starts-with(name(), "data-v-component-")]]');
+ $components = [];
+
+ foreach ($elements as $element) {
+ $parsed = $this->parseComponentElement($element);
+
+ if ($parsed !== null) {
+ $components[$parsed['component']][] = $parsed['options'];
+ }
}
- if (isset($components)) {
+ if ($components) {
$this->components = $components;
}
- //get fields for component
- //load components and feed fields
}
- function saveTemplateComponents() {
+ /**
+ * Persist the parsed component definitions to a PHP cache file.
+ *
+ * @return int|false Number of bytes written, or false on failure.
+ */
+ public function saveTemplateComponents(): int|false {
$php = var_export($this->components, true);
- $php = preg_replace('/\s+/', ' ', $php);
- //repeating end lines
- $php = preg_replace('/\n+/', '', $php);
- return file_put_contents($this->componentsFile, '<?php $components=' . $php . ';');
+ return file_put_contents($this->componentsFile, '<?php return ' . $php . ';');
}
- function loadTemplateComponents() {
- include_once $this->componentsFile;
+ /**
+ * Load previously cached component definitions from the PHP cache file.
+ *
+ * @return bool True when definitions were loaded.
+ */
+ public function loadTemplateComponents(): bool {
+ if (is_file($this->componentsFile)) {
+ $components = include $this->componentsFile;
- if (isset($components)) {
- $this->components = $components;
- }
- //keep only requested service
- if (isset($_GET['component_ajax'])) {
+ if (is_array($components)) {
+ $this->components = $components;
+
+ return true;
+ }
}
- return true;
+ return false;
}
}
diff --git a/system/config.php b/system/config.php
index 49a4721..3302b82 100755
--- a/system/config.php
+++ b/system/config.php
@@ -23,11 +23,14 @@
namespace Vvveb\System;
class Config {
- private $config = [];
+ /** @var array<string, mixed> */
+ private array $config = [];
- private static $instance;
+ /** @var ?self */
+ private static ?self $instance = null;
- public static function getInstance() {
+ /** @return self */
+ public static function getInstance(): self {
if (self::$instance) {
return self::$instance;
} else {
@@ -35,10 +38,15 @@ class Config {
}
}
- private function loadConfig($namespace) {
+ /**
+ * @param string $namespace
+ *
+ * @return void
+ */
+ private function loadConfig(string $namespace): void {
//avoid checking file for non existing namespace
- if (isset($this->config[$namespace]) &&
- $this->config[$namespace] === NULL) {
+ if (array_key_exists($namespace, $this->config) &&
+ $this->config[$namespace] === null) {
return;
}
@@ -50,15 +58,20 @@ class Config {
} catch (\Exception $e) {
}
} else {
- $this->config[$namespace] = NULL;
+ $this->config[$namespace] = null;
}
}
- private function saveConfig($namespace) {
+ /**
+ * @param string $namespace
+ *
+ * @return bool
+ */
+ private function saveConfig(string $namespace): bool {
$data = $this->config[$namespace];
$configFile = DIR_ROOT . "config/$namespace.php";
- if ($error = file_put_contents($configFile, "<?php\n return " . var_export($data, true) . ';', LOCK_EX)) {
+ if ($bytes = file_put_contents($configFile, "<?php\n return " . var_export($data, true) . ';', LOCK_EX)) {
clearstatcache(true, $configFile);
if (function_exists('opcache_invalidate')) {
@@ -68,18 +81,24 @@ class Config {
return true;
}
- return $error;
+ return false;
}
- public function get($path, $default = null) {
+ /**
+ * @param string $path
+ * @param mixed $default
+ *
+ * @return mixed
+ */
+ public function get(string $path, mixed $default = null): mixed {
$p = strtok($path, '.');
$namespace = $p;
//load config for namespace
- if (! isset($this->config[$namespace])) {
+ if (!isset($this->config[$namespace])) {
$this->loadConfig($namespace);
- if (! isset($this->config[$namespace])) {
+ if (!isset($this->config[$namespace])) {
return null;
}
}
@@ -87,7 +106,7 @@ class Config {
$a = $this->config;
while ($p !== false) {
- if (! isset($a[$p])) {
+ if (!isset($a[$p])) {
return $default;
}
@@ -98,22 +117,28 @@ class Config {
return $a;
}
- public function set($path, $value) {
+ /**
+ * @param string $path
+ * @param mixed $value
+ *
+ * @return bool
+ */
+ public function set(string $path, mixed $value): bool {
$p = strtok($path, '.');
$namespace = $p;
- if (! $namespace) {
+ if (!$namespace) {
return false;
}
$a = &$this->config;
//make sure the namespace is loaded to avoid overriding existing data
- if (! isset($this->config[$namespace])) {
+ if (!isset($this->config[$namespace])) {
$this->loadConfig($namespace);
}
while ($p !== false) {
- if (! isset($a[$p])) {
+ if (!isset($a[$p])) {
$a[$p] = [];
}
@@ -128,7 +153,7 @@ class Config {
$a = $value;
} else {
//if value already set go back one level
- if (! is_array($a)) {
+ if (!is_array($a)) {
$prev[$last] = $value;
} else {
if (is_array($value)) {
@@ -142,22 +167,27 @@ class Config {
return $this->saveConfig($namespace);
}
- public function unset($path) {
+ /**
+ * @param string $path
+ *
+ * @return bool
+ */
+ public function unset(string $path): bool {
$p = strtok($path, '.');
$namespace = $p;
- if (! $namespace) {
+ if (!$namespace) {
return false;
}
$a = &$this->config;
//make sure the namespace is loaded to avoid overriding existing data
- if (! isset($this->config[$namespace])) {
+ if (!isset($this->config[$namespace])) {
$this->loadConfig($namespace);
}
while ($p !== false) {
- if (! isset($a[$p])) {
+ if (!isset($a[$p])) {
$a[$p] = [];
}
diff --git a/system/core/frontcontroller.php b/system/core/frontcontroller.php
index 74f1fbb..255c395 100644
--- a/system/core/frontcontroller.php
+++ b/system/core/frontcontroller.php
@@ -31,101 +31,118 @@ use Vvveb\System\Session;
#[\AllowDynamicProperties]
class FrontController {
/**
- * Standard Controller constructor.
+ * Current module (controller) name.
+ *
+ * @var string
*/
- static private $moduleName;
-
- static private $actionName;
+ private static string $moduleName = '';
- static private $status = 200;
+ /**
+ * Current action name.
+ *
+ * @var string
+ */
+ private static string $actionName = '';
/**
- * Returns current controller name.
+ * Current HTTP status code.
*
- * @return string
+ * @var int
*/
- static function getModuleName() {
- return self :: $moduleName;
- }
+ private static int $status = 200;
/**
* Returns current controller name.
*
* @return string
*/
- static function getActionName() {
- return self :: $actionName;
+ public static function getModuleName(): string {
+ return self::$moduleName;
}
/**
- * Returns current status.
+ * Returns current action name.
*
* @return string
*/
- static function getStatus() {
- return self :: $status;
+ public static function getActionName(): string {
+ return self::$actionName;
}
- static function setStatus($status) {
- return self :: $status = $status;
+ /**
+ * Returns current HTTP status code.
+ *
+ * @return int
+ */
+ public static function getStatus(): int {
+ return self::$status;
}
- static private function callAction($controller, $action = 'index') {
- if ($statusCode !== 200) {
- header(' ', true, $statusCode);
- }
-
- if (include_once DIR_APP . DS . 'controller' . DS . "$controller.php") {
- $controller = 'Vvveb\Controller\\' . $controller;
- self :: $moduleName = $moduleName = $controller;
- $controller = 'Vvveb\Controller\\' . $controller;
- }
+ /**
+ * Sets the current HTTP status code.
+ *
+ * @param int $status
+ *
+ * @return int
+ */
+ public static function setStatus(int $status): int {
+ return self::$status = $status;
}
- static function notFound($service = false, $message = false, $statusCode = 404) {
- self :: $status = $statusCode;
+ /**
+ * Handles 404 (or other error) responses.
+ *
+ * @param mixed $service
+ * @param string|array<array-key, mixed>|false $message
+ * @param int $statusCode
+ *
+ * @return never
+ */
+ public static function notFound(mixed $service = false, string|array|false $message = false, int $statusCode = 404): never {
+ self::$status = $statusCode;
$file = DIR_APP . DS . 'controller' . DS . "error$statusCode.php";
if (file_exists($file)) {
- $controller = 'Vvveb\Controller\Error' . $statusCode;
- self :: $moduleName = $moduleName = 'error' . $statusCode;
- $controller = 'Vvveb\Controller\Error' . $statusCode;
- //http_response_code($statusCode);
- $view = View::getInstance();
+ $controller = 'Vvveb\Controller\Error' . $statusCode;
+ self::$moduleName = 'error' . $statusCode;
+ $view = View::getInstance();
if (is_array($message)) {
$view->set($message);
} else {
$view->message = $message;
}
- self :: call($controller, 'index', $file);
+
+ $view->file = '';
+ $view->trace = [];
+
+ self::call($controller, 'index', $file);
PageCache::getInstance()->cleanUp();
- die();
- return;
+ exit();
} else {
- //header(' ', true, $statusCode);
PageCache::getInstance()->cleanUp();
http_response_code($statusCode);
- die("Http error $statusCode");
+ exit("Http error $statusCode");
}
}
- static function closeConnections() {
- if (function_exists('fastcgi_finish_request')) {
- //fastcgi_finish_request();
- }
- /*
- if (defined('DB_ENGINE') && ($instance = \Vvveb\System\Db::getInstance())) {
- $instance->close();
- }*/
- }
+ /**
+ * Extension point run after the response is sent.
+ *
+ * Currently a no-op: connection teardown is left to PHP shutdown.
+ *
+ * @return void
+ */
+ public static function closeConnections(): void {}
/**
- * Inject dependencies.
- *
- * @param string $controller
+ * Inject dependencies into a controller instance.
+ *
+ * @param object &$controller
+ *
+ * @return void
*/
- static function di(&$controller) {
+ public static function di(object &$controller): void {
$controller->request = Request::getInstance();
$controller->response = Response::getInstance();
$controller->view = View::getInstance();
@@ -133,47 +150,71 @@ class FrontController {
}
/**
- * Initializes the controller class and calls the action.
- *
+ * Builds the structured error payload used by dispatch failures.
+ *
+ * @param string $message Human readable error message.
+ * @param string|array<string, mixed> $detail Extra context included with the error.
+ *
+ * @return array<string, mixed>
+ */
+ private static function errorPayload(string $message, string|array $detail = []): array {
+ $payload = ['message' => $message];
+
+ if (is_array($detail)) {
+ $payload += $detail;
+ }
+
+ return $payload;
+ }
+
+ /**
+ * Route to the 404 handler for a missing controller method.
+ *
* @param string $controllerClass
* @param string $actionName
- * @param string $file
+ *
+ * @return never
*/
- static function call($controllerClass, $actionName, $file = false) {
- if ((! @include_once(DIR_APP . DS . 'controller' . DS . 'base.php')) ||
- (! file_exists($file) || ! @include_once($file))) {
- $message = [
- 'message' => __('Controller file not found!'),
- 'file' => $file,
- ];
-
- return self :: notFound(false, $message);
+ private static function methodNotFound(string $controllerClass, string $actionName): never {
+ self::notFound(false, self :: errorPayload(
+ __('Method does not exist!'),
+ ['file' => "$controllerClass :: $actionName"]
+ ));
+ }
+
+ /**
+ * Initializes the controller class and calls the action.
+ *
+ * @param string $controllerClass
+ * @param string $actionName
+ * @param string|false $file
+ *
+ * @return mixed
+ */
+ public static function call(string $controllerClass, string $actionName, string|false $file = false): mixed {
+ if ((!@include_once (DIR_APP . DS . 'controller' . DS . 'base.php')) ||
+ (!file_exists($file) || !@include_once ($file))) {
+ return self::notFound(false, self :: errorPayload(__('Controller file not found!'), ['file' => $file]));
}
// We check if the controller's class really exists
$controller = false;
- if (class_exists($controllerClass , false)) {// if the controller does not exist route to controller main
+ if (class_exists($controllerClass, false)) {// if the controller does not exist route to controller main
$controller = new $controllerClass();
- if (! $controller || ! method_exists($controller , $actionName) || $actionName == 'init') {
- $message = [
- 'message' => __('Method does not exist!'),
- 'file' => "$controllerClass :: $actionName",
- ];
-
- return self :: notFound(false, $message);
+ if (!method_exists($controller, $actionName) ||
+ $actionName === 'init' || str_starts_with($actionName, '_')) {
+ return self::methodNotFound($controllerClass, $actionName);
}
} else {
- $message = [
- 'message' => __('Controller does not exist!'),
- 'file' => $controllerClass,
- ];
-
- return self :: notFound(false, $message);
+ return self::notFound(false, self :: errorPayload(
+ __('Controller does not exist!'),
+ $controllerClass
+ ));
}
- self :: di($controller);
+ self::di($controller);
if (method_exists($controller, 'init')) {
$return = $controller->init();
@@ -181,27 +222,22 @@ class FrontController {
if ($return) {
$actionName = $return;
- if (! method_exists($controller , $actionName)) {
- $message = [
- 'message' => __('Method does not exist!'),
- 'file' => "$controllerClass :: $actionName",
- ];
-
- return self :: notFound(false, $message);
+ if (!method_exists($controller, $actionName) || str_starts_with($actionName, '_')) {
+ return self::methodNotFound($controllerClass, $actionName);
}
}
}
$response = Response::getInstance();
- $template = str_replace('/', DS, strtolower(self :: $moduleName));
+ $template = str_replace('/', DS, strtolower(self::$moduleName));
$theme = $controller->view->getTheme();
$path = DIR_THEME . $theme . DS;
- $isPlugin = strncmp($template, 'plugins/', 8) === 0;
+ $isPlugin = str_starts_with($template, 'plugins/');
- if ($actionName && $actionName != 'index') {
+ if ($actionName && $actionName !== 'index') {
if ($isPlugin) {
$t = str_replace('plugins' . DS, '', $template);
- $p = strpos($t, DS);
+ $p = str_contains($t, DS) ? strpos($t, DS) : false;
$pluginName = substr($t, 0, $p);
$nameSpace = substr($t, $p + 1);
@@ -217,12 +253,10 @@ class FrontController {
$controller->view->template($template . '.html'); //default html that can be overwritten
- //list($template) = Event :: trigger($controllerClass, "$actionName:before", $template);
-
- //$controller->view->template($template . '.html'); //default html
$template = call_user_func([$controller, $actionName]);
- list($template, $controller, $actionName) = Event::trigger(__CLASS__, __FUNCTION__, $template, $controller, $actionName);
+ [$template, $controller, $actionName] = Event::trigger(__CLASS__, __FUNCTION__, $template, $controller, $actionName);
+
$responseType = $response->getType();
$controller->view->setType($responseType);
@@ -231,7 +265,6 @@ class FrontController {
} else {
if (is_array($template)) {
$response->output($template);
- //echo json_encode($template);
} else {
if ($template) {
$controller->view->template($template);
@@ -239,39 +272,38 @@ class FrontController {
}
}
- $response->setStatus(self :: $status);
+ $response->setStatus(self::$status);
$return = $response->output();
- self :: closeConnections();
+ self::closeConnections();
return $return;
}
/**
- * Redirect or direct to a action or default controller action and parameters
- * it has the ability to http redirect to the specified action
- * internally used to direct to action.
+ * Redirect or direct to a action or default controller action and parameters.
+ * It has the ability to http redirect to the specified action.
+ * Internally used to direct to action.
*
* @param string $moduleName
* @param string $actionName
- * @param array $parameters
- * @param bool $httpRedirect
- * @return bool
+ *
+ * @return mixed
*/
- static function redirect($moduleName , $actionName = 'index') {
- self :: $moduleName = $moduleName;
- self :: $actionName = $actionName;
+ public static function redirect(string $moduleName, string $actionName = 'index'): mixed {
+ self::$moduleName = $moduleName;
+ self::$actionName = $actionName;
if (is_dir(DIR_APP . DS . 'controller' . DS . strtolower($moduleName))) {
- self :: $moduleName = $moduleName .= '/Index';
+ self::$moduleName = $moduleName .= '/Index';
}
$dir = strtolower(str_replace('/', DS, $moduleName));
- $className = \Vvveb\dashesToCamelCase(str_replace(['/', DS], '\\', $moduleName));
+ $className = \Vvveb\dashesToCamelCase(str_replace(['/', DS], '\\', $moduleName));
$controllerClass = 'Vvveb\Controller\\' . $className;
//change file paths for plugins
- if (strpos($moduleName, 'Plugins/') === 0) {
+ if (str_starts_with($moduleName, 'Plugins/')) {
$dir = str_replace('plugins' . DS, '', $dir);
$p = strpos($dir, DS);
$pluginName = $dir;
@@ -292,45 +324,55 @@ class FrontController {
$file = DIR_APP . 'controller' . DS . $dir . '.php';
}
- return self :: call($controllerClass, $actionName, $file);
+ return self::call($controllerClass, $actionName, $file);
}
- static public function getRoute() {
+ /**
+ * Returns the current route from the query string.
+ *
+ * @return string
+ */
+ public static function getRoute(): string {
return $_GET['route'] ?? '';
}
- static public function getModule() {
+ /**
+ * Returns the current module from the query string.
+ *
+ * @return string
+ */
+ public static function getModule(): string {
return $_GET['module'] ?? '';
}
- static public function dispatch(&$site = []) {
+ /**
+ * Dispatches the request to the appropriate controller/action.
+ *
+ * @param array<array-key, mixed> &$site
+ *
+ * @return mixed
+ */
+ public static function dispatch(array &$site = []): mixed {
$module = $_GET['module'] ?? $_POST['module'] ?? null;
$action = $_GET['action'] ?? $_POST['action'] ?? null;
$_REQUEST = array_merge($_GET, $_REQUEST);
- //subdirectory support
- /*
- $subdir = \Vvveb\pregMatch('@(.+)/index.php@',$_SERVER['SCRIPT_NAME'], 1);
- $subdir = str_replace(['/public', '/admin'], '', $subdir);
- define('V_SUBDIR_INSTALL', $subdir);
- */
-
//remove GET parameters to allow correct matching,
- $uri = SITE_URI ?? $_SERVER['REQUEST_URI'] ?? '/';
+ $uri = SITE_URI;
$uri = preg_replace('/\?.*$/', '', $uri);
- $route = false;
+ $route = false;
$routesSiteId = null;
if (isset($site['route'])) {
$routesSiteId = $site['site_id'];
- };
+ }
- if (! $module && (APP != 'admin' && APP != 'install' && (Routes::init(APP, $routesSiteId) && $route = Routes::match($uri)))) {
+ if (!$module && (APP !== 'admin' && APP !== 'install' && (Routes::init(APP, $routesSiteId) && $route = Routes::match($uri)))) {
$_GET = array_merge($route, $_GET);
} else {
- $module = $module ?? ((APP == 'install' || APP == 'admin') ? 'index' : false);
+ $module = $module ?? ((APP === 'install' || APP === 'admin') ? 'index' : false);
- if (! $module && APP == 'app') {
+ if (!$module && APP === 'app') {
return self::notFound(false, ['message' => 'No route!']);
}
}
@@ -338,7 +380,7 @@ class FrontController {
if ($route) {
if (preg_match('@(^.+?)/(\w+$)@', $_GET['module'], $routeMatch)) {
$module = $routeMatch[1];
- $action = $action ?? $routeMatch[2];
+ $action ??= $routeMatch[2];
} else {
$module = trim($_GET['module'], '/');
}
@@ -348,23 +390,14 @@ class FrontController {
$action = 'index';
}
//santize inputs
- if (($module && ! preg_match('@^[a-zA-Z_/0-9\-]{4,70}$@', $module)) ||
- ($action && ! preg_match('@^[a-zA-Z_/0-9\-]{3,70}$@', $action))) {
+ if ((!preg_match('@^[a-zA-Z_/0-9\-]{4,70}$@', $module)) ||
+ (!preg_match('@^[a-zA-Z_/0-9\-]{3,70}$@', $action))) {
return self::notFound(false, ['message' => 'Invalid request!'], 500);
}
- $path = $module;
-
- $module = ucfirst($module);
- $path = '';
-
- array_map(function ($value) use (&$path) {
- if ($path) {
- $path .= '/';
- }
- $path .= ucfirst($value);
- }, explode('/', $module));
+ //capitalize each namespace segment of the module path (ex: content/posts -> Content/Posts)
+ $path = implode('/', array_map('ucfirst', explode('/', $module)));
- return self :: redirect($path, $action);
+ return self::redirect($path, $action);
}
}
diff --git a/system/core/request.php b/system/core/request.php
old mode 100755
new mode 100644
index 565d204..eb3267d
--- a/system/core/request.php
+++ b/system/core/request.php
@@ -23,31 +23,39 @@
namespace Vvveb\System\Core;
class Request {
- public $get = [];
+ /** @var array<string, mixed> */
+ public array $get = [];
- public $post = [];
+ /** @var array<string, mixed> */
+ public array $post = [];
- public $request = [];
+ /** @var array<string, mixed> */
+ public array $request = [];
- public $cookie = [];
+ /** @var array<string, mixed> */
+ public array $cookie = [];
- public $files = [];
+ /** @var array<string, mixed> */
+ public array $files = [];
- public $server = [];
+ /** @var array<string, mixed> */
+ public array $server = [];
- private $method;
+ private string $method;
- protected static $instance;
+ private string $contentType;
- public static function getInstance() {
+ protected static ?self $instance = null;
+
+ public static function getInstance(): self {
if (is_null(static::$instance)) {
- static::$instance = new static();
+ static::$instance = new self();
}
return static::$instance;
}
- final private function __construct() {
+ private function __construct() {
$this->get = &$_GET;
$this->post = &$_POST;
$this->request = &$_REQUEST;
@@ -55,46 +63,60 @@ class Request {
$this->files = &$_FILES;
$this->server = &$_SERVER;
- $this->post = $this->filter($this->post, false);
- $this->get = $this->filter($this->get);
- $this->request = $this->filter($this->request);
- $this->cookie = $this->filter($this->cookie);
- $this->files = $this->filter($this->files);
- $this->method = strtolower($_SERVER['REQUEST_METHOD'] ?? 'get');
+ $this->post = $this->filter($this->post, false);
+ $this->get = $this->filter($this->get);
+ $this->request = $this->filter($this->request);
+ $this->cookie = $this->filter($this->cookie);
+ $this->files = $this->filter($this->files);
+ $this->method = strtolower($_SERVER['REQUEST_METHOD'] ?? 'get');
+ $this->contentType = strtolower($_SERVER['CONTENT_TYPE'] ?? 'text/html');
- if ($this->method == 'put' || $this->method == 'patch') {
+ if ($this->method === 'put' || $this->method === 'patch') {
parse_str(file_get_contents('php://input'), $post);
$this->post = $this->filter($post, false);
}
+ if ($this->contentType == 'application/json') {
+ $rawInput = file_get_contents('php://input');
+ if ($rawInput) {
+ //print_r($rawInput);
+ $json = json_decode($rawInput, true);
+ //malformed json decodes to null: keep post an array
+ $this->post = is_array($json) ? $json : [];
+ }
+ }
+
$this->request = array_merge($this->request, $this->get, $this->post);
}
- public function filter($data, $filterText = true) {
- if (is_array($data)) {
- foreach ($data as $key => $value) {
- unset($data[$key]);
+ /**
+ * Recursively filter array keys and values.
+ *
+ * @param array<array-key, mixed>|string $data The data to filter.
+ * @param bool $filterText Whether to apply text filtering via \Vvveb\filterText.
+ *
+ * @return array<array-key, mixed>|string Filtered data.
+ */
+ public function filter(array|string $data, bool $filterText = true): array|string {
+ if (!is_array($data)) {
+ return $filterText ? \Vvveb\filterText($data) : $data;
+ }
- $key = substr($this->filter($key, $filterText), 0, 255);
- $data[$key] = $this->filter($value, $filterText);
- }
- } else {
- if ($filterText) {
- $data = \Vvveb\filterText($data);
- } else {
- //$data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8');
- $data = $data;
- }
+ $filtered = [];
+
+ foreach ($data as $key => $value) {
+ $key = substr($this->filter((string)$key, $filterText), 0, 255);
+ $filtered[$key] = $this->filter($value, $filterText);
}
- return $data;
+ return $filtered;
}
- public function getMethod() {
+ public function getMethod(): string {
return $this->method;
}
- public function isAjax() {
- return isset($this->server['HTTP_X_REQUESTED_WITH']) && $this->server['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
+ public function isAjax(): bool {
+ return isset($this->server['HTTP_X_REQUESTED_WITH']) && $this->server['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';
}
}
diff --git a/system/core/response.php b/system/core/response.php
index a04bf56..105a324 100644
--- a/system/core/response.php
+++ b/system/core/response.php
@@ -23,27 +23,42 @@
namespace Vvveb\System\Core;
class Response {
- private $headers = [];
+ /** @var array<string, mixed> */
+ private array $headers = [];
- private $done = false;
+ private bool $done = false;
- public $output = true;
+ public bool $output = true;
- public $filters = [];
+ /** @var list<callable> */
+ public array $filters = [];
- private $type = ''; //html, json, xml
+ private string $type = '';
- private $status = 200;
+ private int $status = 200;
- private $callback = 'callback';
+ private string $callback = 'callback';
- private $typeHeaders = ['html' => 'text/html', 'xml' => 'text/xml', 'text' => 'text/plain', 'json' => 'application/json', 'jsonp' => 'application/javascript', 'activityjson' => 'application/activity+json', 'ldjson' => 'application/ld+json', 'jrdjson' => 'application/jrd+json'];
+ /** @var array<string, string> */
+ private array $typeHeaders = [
+ 'html' => 'text/html',
+ 'xml' => 'text/xml',
+ 'text' => 'text/plain',
+ 'json' => 'application/json',
+ 'jsonp' => 'application/javascript',
+ 'activityjson' => 'application/activity+json',
+ 'ldjson' => 'application/ld+json',
+ 'jrdjson' => 'application/jrd+json',
+ ];
- protected static $instance;
+ protected static ?self $instance = null;
- final public static function getInstance() {
+ /**
+ * @return self
+ */
+ final public static function getInstance(): self {
if (is_null(static::$instance)) {
- static::$instance = new static();
+ static::$instance = new self();
}
return static::$instance;
@@ -53,55 +68,66 @@ class Response {
$this->addHeader('X-Powered-By', 'Vvveb ' . V_VERSION);
}
- function addFilter($filter) {
+ public function addFilter(callable $filter): void {
$this->filters[] = $filter;
}
- function getStatus() {
+ public function getStatus(): int {
return $this->status;
}
- function setStatus($status) {
+ public function setStatus(int $status): int {
return $this->status = $status;
}
- public function addHeader($header, $value = null) {
+ public function addHeader(string $header, ?string $value = null): void {
$this->headers[$header] = $value;
}
- public function removeHeader($header) {
+ public function removeHeader(string $header): void {
unset($this->headers[$header]);
}
- public function getHeaders() {
+ /** @return array<string, ?string> */
+ public function getHeaders(): array {
return $this->headers;
}
- public function redirect($url, $status = 302) {
+ /** @return never */
+ public function redirect(string $url, int $status = 302): never {
header('Location: ' . str_replace(['&amp;', "\n", "\r"], ['&', '', ''], $url), true, $status);
exit();
}
- public function getType() {
+ public function getType(): string {
return $this->type;
}
- public function setType($type) {
+ public function setType(string $type): bool {
$contentType = $this->typeHeaders[$type] ?? false;
- if ($contentType) {
- $this->addHeader('Content-Type', $contentType);
- $this->type = $type;
+ if (!$contentType) {
+ return false;
}
+
+ $this->addHeader('Content-Type', $contentType);
+ $this->type = $type;
+
+ return true;
}
- public function output($data = null) {
+ /**
+ * @param array<array-key, mixed>|object|null $data
+ *
+ * @return string|false
+ */
+ public function output(array|object|string|null $data = null): string|false {
if ($this->done) {
return false;
}
- if (! headers_sent()) {
+ if (!headers_sent()) {
foreach ($this->headers as $name => $value) {
if ($value) {
$header = "$name: $value";
@@ -119,14 +145,15 @@ class Response {
$this->done = true;
- if ($this->type == 'text' && $data !== null) {
- $output = $data;
+ if ($this->type === 'text' && $data !== null) {
+ //$data may be an array (see signature): encode it instead of echoing "Array"
+ $output = is_string($data) ? $data : json_encode($data);
} else {
- if (($this->type == 'json' || $this->type == 'jsonp' || $this->type == 'ldjson' || $this->type == 'activityjson' || $this->type == 'jrdjson') && $data !== null && (! defined('CLI'))) {
+ if (in_array($this->type, ['json', 'jsonp', 'ldjson', 'activityjson', 'jrdjson']) && $data !== null && (!defined('CLI'))) {
if (is_array($data) || is_object($data)) {
$data = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
- if ($this->type == 'jsonp') {
+ if ($this->type === 'jsonp') {
$data = "/**/{$this->callback}($data)";
}
}
@@ -139,7 +166,7 @@ class Response {
$view->setType($this->type);
}
- $output = $view->render(true, $this->output && ! $this->filters);
+ $output = $view->render(true, $this->output && !$this->filters);
}
}
diff --git a/system/core/startup.php b/system/core/startup.php
old mode 100755
new mode 100644
index 4b03fc8..2b256d1
--- a/system/core/startup.php
+++ b/system/core/startup.php
@@ -24,7 +24,6 @@ namespace Vvveb\System\Core;
use function Vvveb\camelToUnderscore;
use Vvveb\System\Extensions\Plugins;
-use Vvveb\System\Session;
use Vvveb\System\Sites;
use Vvveb\System\Sqlp\Sqlp;
@@ -35,28 +34,28 @@ if (is_writable($storage_dir)) {
} else {
$storage_dir = sys_get_temp_dir() . DS . 'storage' . DS;
- if (! is_dir($storage_dir)) {
+ if (!is_dir($storage_dir)) {
@mkdir($storage_dir);
@mkdir($storage_dir . 'compiled-templates' . DS);
@mkdir($storage_dir . 'cache');
@mkdir($storage_dir . 'model');
- @mkdir($storage_dir . join(DS, ['model', 'admin']) . DS);
- @mkdir($storage_dir . join(DS, ['model/app']) . DS);
- @mkdir($storage_dir . join(DS, ['model/install']) . DS);
+ @mkdir($storage_dir . implode(DS, ['model', 'admin']) . DS);
+ @mkdir($storage_dir . implode(DS, ['model/app']) . DS);
+ @mkdir($storage_dir . implode(DS, ['model/install']) . DS);
}
define('DIR_STORAGE', $storage_dir);
}
-define('DIR_CACHE', DIR_ROOT . join(DS, ['storage', 'cache']) . DS);
+define('DIR_CACHE', DIR_ROOT . implode(DS, ['storage', 'cache']) . DS);
define('DIR_PLUGINS', DIR_ROOT . 'plugins' . DS);
define('DIR_COMPILED_TEMPLATES', DIR_STORAGE . 'compiled-templates' . DS);
define('DIR_BACKUP', DIR_STORAGE . 'backup' . DS);
-define('DIR_THEMES', DIR_ROOT . join(DS, ['public', 'themes']) . DS);
+define('DIR_THEMES', DIR_ROOT . implode(DS, ['public', 'themes']) . DS);
define('DIR_PUBLIC', DIR_ROOT . 'public' . DS);
-if (APP == 'app') {
- define('DIR_THEME', DIR_ROOT . join(DS, ['public', 'themes']) . DS);
+if (APP === 'app') {
+ define('DIR_THEME', DIR_ROOT . implode(DS, ['public', 'themes']) . DS);
} else {
define('DIR_THEME', DIR_ROOT . 'public' . DS . APP . DS);
}
@@ -69,7 +68,7 @@ define('CDATA_END', ']]>');
$error_log = ini_get('error_log');
-if (! $error_log || $error_log == '/dev/null') {
+if (!$error_log || $error_log === '/dev/null') {
ini_set('error_log', $storage_dir . 'logs/error_log');
}
@@ -85,24 +84,65 @@ require_once DIR_SYSTEM . 'functions.php';
require_once DIR_SYSTEM . 'event.php';
-function logError($message) {
+/**
+ * Log an error message to the error log.
+ *
+ * @param string $message The error message to log.
+ *
+ * @return bool True if the message was successfully written to the log.
+ */
+function logError(string $message): bool {
return error_log($message);
}
-function regenerateSQL($sqlFile, $file, $modelName, $namespace) {
+/**
+ * Regenerate a SQL model file from a SQL definition file.
+ *
+ * @param string $sqlFile Path to the SQL definition file.
+ * @param string $file Output path for the generated PHP model file.
+ * @param string $modelName The model class name.
+ * @param string $namespace The namespace for the generated model class.
+ *
+ * @return void
+ */
+function regenerateSQL(string $sqlFile, string $file, string $modelName, string $namespace): void {
$sqlp = new Sqlp();
$sqlp->parseSqlPfile($sqlFile, $modelName, $namespace);
$dir = dirname($file);
- if (! file_exists($dir)) {
- @mkdir($dir,0755,true);
+ if (!file_exists($dir)) {
+ @mkdir($dir, 0755, true);
+ }
+
+ $code = "<?php \n" . $sqlp->generateModel();
+
+ //never write a broken model to disk, a parse error here would poison every request
+ try {
+ $tokens = token_get_all($code, TOKEN_PARSE);
+ unset($tokens);
+ } catch (\ParseError $e) {
+ throw new \Exception(sprintf('Generated SQL model %s has invalid syntax!', $file));
}
- file_put_contents($file, "<?php \n" . $sqlp->generateModel());
+
+ //write to a temp file and rename, so concurrent requests never read a half written model
+ $tmp = $file . '.' . getmypid() . '.tmp';
+ file_put_contents($tmp, $code);
+ rename($tmp, $file);
}
-function autoload($class) {
+/**
+ * Autoload classes under the Vvveb namespace.
+ *
+ * Resolves class names to file paths, handling plugin SQL classes,
+ * system classes, app/admin controllers, and standard models.
+ *
+ * @param string $class The fully-qualified class name to autoload.
+ *
+ * @return void
+ */
+function autoload(string $class): void {
// project-specific namespace prefix
$prefix = 'Vvveb\\';
@@ -115,110 +155,131 @@ function autoload($class) {
}
$relativeClass = substr($class, $len);
- $isPlugin = (strncmp($relativeClass, 'Plugins\\', 7) === 0);
+ $isPlugin = str_starts_with($relativeClass, 'Plugins\\');
// replace the namespace prefix with the base directory, replace namespace
// separators with directory separators in the relative class name, append
// with .inc
$root = DIR_APP;
//if namespace is Vvveb\System or Vvveb\Plugins load from root dir above app dir
- if ((strncmp($relativeClass, 'System\\', 7) === 0) ||
+ if ((str_starts_with($relativeClass, 'System\\')) ||
$isPlugin ||
- (strncmp($relativeClass, 'Sql\Plugins\\', 11) === 0)) {
+ (str_starts_with($relativeClass, 'Sql\Plugins\\'))) {
$root = DIR_ROOT;
}
//if namespace is App change to app dir
- if ((strncmp($relativeClass, 'App\\', 4) === 0)) {
+ if (str_starts_with($relativeClass, 'App\\')) {
$root = DIR_ROOT . 'app' . DS;
}
//if namespace is Admin change to admin dir
- if ((strncmp($relativeClass, 'Admin\\', 6) === 0)) {
+ if (str_starts_with($relativeClass, 'Admin\\')) {
$root = DIR_ROOT . 'admin' . DS;
}
- $isSql = (substr_compare($relativeClass, 'SQL', -3, 3) === 0);
-
- //check if sql files are changed or missing to regenerate sql class
- if ($isSql) {
- $isFromPlugin = strpos($relativeClass, 'Plugins\\');
- $sqlFile = str_replace(['Sql', '\\'], ['', DS], substr($relativeClass, 0, -3));
- //$sqlFile = strtolower(preg_replace('/(?<!^)(?<!\/)[A-Z]/', '-$0', $sqlFile));
-
- if ($isFromPlugin > 0) {
- //convert camelCase to snake_case
- $sqlFile = strtolower(preg_replace('/(?<!^)(?<!\/)(?<!\\\)[A-Z]/', '-$0', $sqlFile));
- $file = basename($sqlFile);
- $pluginName = str_replace([DS . 'plugins' . DS, DS . $file], '', $sqlFile) . DS;
- $pluginName = strtolower(preg_replace('/(?<!^)(?<!\/)(?<!\\\)[A-Z]/', '-$0', $pluginName));
- $sqlFile = DIR_PLUGINS . $pluginName . 'sql' . DS . DB_ENGINE . DS . $file . '.sql';
- } else {
- $sqlFile = strtolower($sqlFile) . '.sql';
- //$sqlFile = DIR_SQL . $sqlFile . '.sql';
- }
+ //sql model classes are generated from .sql definition files
+ if (substr_compare($relativeClass, 'SQL', -3, 3) === 0) {
+ autoloadSqlModel($relativeClass);
- $name = str_replace(['\\', 'sql' . DS], [DS, ''], strtolower($relativeClass));
- $modelName = ucwords(basename(str_replace('sql', '', $name)));
- $namespace = ucwords(dirname($name));
+ return;
+ }
- if ($namespace != '.') {
- $namespace = str_replace('/', '\\', "\\$namespace");
- } else {
- $namespace = '';
- }
+ //load any other Vvveb class from the app/system/plugin directories
+ $file = $root . str_replace('\\', '/', camelToUnderscore($relativeClass)) . '.php';
+ $fileAsIs = $root . str_replace('\\', '/', strtolower($relativeClass)) . '.php';
- $file = DIR_STORAGE . 'model' . DS . APP . DS . $name . '.' . DB_ENGINE . '.php';
- $fileExists = file_exists($file);
+ if ($isPlugin && ($isController = str_contains($relativeClass, 'Controller\\'))) {
+ $file = str_replace('/controller/', '/' . APP . '/controller/', $file);
+ $fileAsIs = str_replace('/controller/', '/' . APP . '/controller/', $fileAsIs);
+ }
- if (SQL_CHECK || ! $fileExists) {
- $sqlExists = false;
+ foreach ([$file, $fileAsIs] as $f) {
+ if (file_exists($f)) {
+ require_once $f;
- if ($isFromPlugin > 0) {
- $fullSqlFile = $sqlFile;
- $sqlExists = file_exists($fullSqlFile);
- } else {
- //fallback to admin if sql file is missing in APP
- foreach ([APP, 'admin'] as $app) {
- $fullSqlFile = DIR_ROOT . $app . DS . 'sql' . DS . DB_ENGINE . DS . $sqlFile;
+ return;
+ }
+ }
- if (file_exists($fullSqlFile)) {
- $sqlExists = true;
+ //throw(new \Exception($class . ' could not be loaded!'));
+}
- break;
- }
- }
- }
+/**
+ * Resolve, generate when stale, and load a SQL model class.
+ *
+ * Called by autoload() for every class ending in SQL.
+ *
+ * @param string $relativeClass Class name without the Vvveb\ prefix.
+ */
+function autoloadSqlModel(string $relativeClass): void {
+ $isFromPlugin = str_contains($relativeClass, 'Plugins\\');
+ $sqlFile = str_replace(['Sql', '\\'], ['', DS], substr($relativeClass, 0, -3));
+
+ if ($isFromPlugin) {
+ //convert camelCase to snake_case
+ $sqlFile = strtolower(preg_replace('/(?<!^)(?<!\/)(?<!\\\)[A-Z]/', '-$0', $sqlFile));
+ $file = basename($sqlFile);
+ $pluginName = str_replace([DS . 'plugins' . DS, DS . $file], '', $sqlFile) . DS;
+ $pluginName = strtolower(preg_replace('/(?<!^)(?<!\/)(?<!\\\)[A-Z]/', '-$0', $pluginName));
+ $sqlFile = DIR_PLUGINS . $pluginName . 'sql' . DS . DB_ENGINE . DS . $file . '.sql';
+ } else {
+ $sqlFile = strtolower($sqlFile) . '.sql';
+ }
- if (! $sqlExists) {
- throw new \Exception(sprintf(\Vvveb\__('SQL file %s does not exist for %s!'), $sqlFile, $relativeClass));
- }
- //if the file has not been generated yet or sql files is changed recompile
- if (! $fileExists || ((filemtime($fullSqlFile) > filemtime($file)))) {
- regenerateSQL($fullSqlFile, $file, $modelName, $namespace);
- $fileExists = true;
- }
- }
+ $name = str_replace(['\\', 'sql' . DS], [DS, ''], strtolower($relativeClass));
+ $modelName = ucwords(basename(str_replace('sql', '', $name)));
+ $namespace = ucwords(dirname($name));
- if ($fileExists) {
- require_once $file;
- }
+ if ($namespace !== '.') {
+ $namespace = str_replace('/', '\\', "\\$namespace");
} else {
- $file = $root . str_replace('\\', '/', camelToUnderscore($relativeClass)) . '.php';
+ $namespace = '';
+ }
- if ($isPlugin && ($isController = strpos($relativeClass, 'Controller\\'))) {
- $file= str_replace('/controller/', '/' . APP . '/controller/', $file);
- }
+ $file = DIR_STORAGE . 'model' . DS . APP . DS . $name . '.' . DB_ENGINE . '.php';
+ $fileExists = file_exists($file);
+
+ if (SQL_CHECK || !$fileExists) {
+ $sqlExists = false;
- $fileExists = file_exists($file);
+ if ($isFromPlugin) {
+ $fullSqlFile = $sqlFile;
+ $sqlExists = file_exists($fullSqlFile);
+ } else {
+ //fallback to admin if sql file is missing in APP
+ foreach ([APP, 'admin'] as $app) {
+ $fullSqlFile = DIR_ROOT . $app . DS . 'sql' . DS . DB_ENGINE . DS . $sqlFile;
+
+ if (file_exists($fullSqlFile)) {
+ $sqlExists = true;
+
+ break;
+ }
+ }
+ }
- if ($fileExists) {
- require_once $file;
+ if (!$sqlExists) {
+ throw new \Exception(sprintf(\Vvveb\__('SQL file %s does not exist for %s!'), $sqlFile, $relativeClass));
+ }
+ //if the file has not been generated yet or sql files is changed recompile
+ if (!$fileExists || ((filemtime($fullSqlFile) > filemtime($file)))) {
+ regenerateSQL($fullSqlFile, $file, $modelName, $namespace);
+ $fileExists = true;
}
}
+
+ require_once $file;
}
-function autoload_vendor($class) {
+/**
+ * Autoload vendor classes from the vendor directory.
+ *
+ * @param string $class The fully-qualified class name to autoload.
+ *
+ * @return void
+ */
+function autoload_vendor(string $class): void {
$path = str_replace('\\', DS, $class);
$file = DIR_ROOT . 'vendor' . DS . "$path.php";
@@ -229,18 +290,29 @@ function autoload_vendor($class) {
}
}
-function exceptionToArray($exception, $file = false) {
- $file = $exception->getFile() ? $exception->getFile() : $file;
+/**
+ * Convert a throwable exception to a structured array with context.
+ *
+ * Extracts the message, file, line, surrounding code context, and stack trace
+ * from the given exception.
+ *
+ * @param \Throwable $exception The exception to convert.
+ * @param string|false $file Optional override for the source file path.
+ *
+ * @return array<string, mixed> Structured error information array<array-key, mixed>.
+ */
+function exceptionToArray(\Throwable $exception, string|false $file = false): array {
+ $file = $exception->getFile() ?: $file;
$lineNo = $exception->getLine() - 1;
//$code = $exception->getCode();
- $class = get_class($exception);
+ $class = $exception::class;
$lines = [];
$codeLines = [];
$line = $lineNo;
$code = '';
- if (! defined('CLI') && $file && file_exists($file) && ($codeLines = file($file)) && isset($codeLines[$lineNo])) {
- $codeLines[$lineNo] = preg_replace("/\n$/","\t // <==\n", $codeLines[$lineNo]);
+ if (!defined('CLI') && $file && file_exists($file) && ($codeLines = file($file)) && isset($codeLines[$lineNo])) {
+ $codeLines[$lineNo] = preg_replace("/\n$/", "\t // <==\n", $codeLines[$lineNo]);
$lines = array_slice($codeLines, $lineNo - 7, 14);
$line = implode("\n", array_slice($codeLines, $lineNo, 1));
$before = implode("\n", array_slice($codeLines, $lineNo - 6, 5));
@@ -248,7 +320,7 @@ function exceptionToArray($exception, $file = false) {
$code = "$before<b>$line</b>$after";
}
- $message = [
+ return [
'message' => $exception->getMessage(),
'file' => $file,
'line_no' => $lineNo,
@@ -257,29 +329,37 @@ function exceptionToArray($exception, $file = false) {
'trace' => $exception->getTraceAsString(),
'code' => $codeLines,
];
-
- return $message;
}
-function exceptionHandler($exception) {
+/**
+ * Handle uncaught exceptions globally.
+ *
+ * Converts the exception to an array, checks for plugin errors, and
+ * outputs debug information when DEBUG mode is enabled.
+ *
+ * @param \Throwable $exception The uncaught exception.
+ *
+ * @return void
+ */
+function exceptionHandler(\Throwable $exception): void {
static $handled;
if ($handled) {
if (DEBUG) {
- echo $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine();
+ echo $exception->getMessage() . ' in ' . $exception->getFile() . ' on line ' . $exception->getLine();
} else {
- die('Server error, enable debug for more info');
+ exit('Server error, enable debug for more info');
}
+
return;
}
$handled = true;
$message = exceptionToArray($exception, $exception->getFile());
- $handled = true;
//check if error is generated by a plugin and disable it
pluginErrorCheck($message['file']);
- FrontController::notFound(false, $message, 500);
+ //FrontController::notFound(false, $message, 500);
//pluginErrorCheck($file);
if (DEBUG) {
echo '<b>Exception:</b><pre>';
@@ -288,8 +368,21 @@ function exceptionHandler($exception) {
}
}
-function vErrorHandler($errno, $errstr, $errfile, $errline) {
- if (! (error_reporting() && $errno)) {
+/**
+ * Custom error handler for PHP errors.
+ *
+ * Checks if the error is within the current error_reporting level, handles
+ * plugin errors, and throws ErrorException for fatal errors.
+ *
+ * @param int $errno The error level constant (e.g. E_WARNING).
+ * @param string $errstr The error message.
+ * @param string $errfile The filename where the error occurred.
+ * @param int $errline The line number where the error occurred.
+ *
+ * @return bool Returns false to allow the PHP error handler to continue.
+ */
+function vErrorHandler(int $errno, string $errstr, string $errfile, int $errline): bool {
+ if (!(error_reporting() && $errno)) {
// This error code is not included in error_reporting, so let it fall
// through to the standard PHP error handler
return false;
@@ -300,38 +393,34 @@ function vErrorHandler($errno, $errstr, $errfile, $errline) {
switch ($errno) {
case E_USER_WARNING:
case E_WARNING:
- /*
- throw new \Exception($errstr, $errno);
- //throw new \Exception($errstr, $errno, 0, $errfile, $errline);
- return true;
- break;
- */
-
case E_USER_NOTICE:
break;
case E_ERROR:
case E_USER_ERROR:
- /*
- echo "<b>ERROR</b> [$errno] $errstr<br />\n";
- echo " Fatal error on line $errline in file $errfile";
- echo ', PHP ' . PHP_VERSION . ' (' . PHP_OS . ")<br />\n";
- */
//check if error is generated by a plugin and disable it
pluginErrorCheck($errfile);
throw new \ErrorException($errstr, $errno, 0, $errfile, $errline);
-
- return true;
//return FrontController::notFound(false, $errstr, 500);
}
- /* Don't execute PHP internal error handler */
+ // Don't execute PHP internal error handler
return false;
}
-function pluginErrorCheck($file) {
- if (($pos = strpos($file, DIR_PLUGINS)) !== false) {
+/**
+ * Check if an error originates from a plugin and optionally disable it.
+ *
+ * If the error file path is within the plugins directory, logs the error
+ * and deactivates the offending plugin when DISABLE_PLUGIN_ON_ERORR is true.
+ *
+ * @param string $file The file path where the error occurred.
+ *
+ * @return bool True if the error is from a plugin, false otherwise.
+ */
+function pluginErrorCheck(string $file): bool {
+ if (str_contains($file, DIR_PLUGINS)) {
$plugin = \Vvveb\filter('@([^/]+)@', str_replace(DIR_PLUGINS, '', $file));
logError("'$plugin' plugin triggers fatal error.");
@@ -339,16 +428,25 @@ function pluginErrorCheck($file) {
logError(sprintf(\Vvveb\__('Disabling "%s" plugin.'), $plugin));
Plugins::deactivate($plugin);
}
-
+
return true;
}
+
+ return false;
}
-function fatalErrorHandler() {
+/**
+ * Shutdown handler that catches fatal errors.
+ *
+ * Retrieves the last error and delegates it to the custom error handler.
+ *
+ * @return void
+ */
+function fatalErrorHandler(): void {
$message = error_get_last();
if ($message) {
- vErrorHandler($message['type'], $message['message'],$message['file'], $message['line']);
+ vErrorHandler($message['type'], $message['message'], $message['file'], $message['line']);
}
}
@@ -361,37 +459,39 @@ register_shutdown_function('Vvveb\System\Core\fatalErrorHandler');
require DIR_ROOT . '/vendor/autoload.php';
$dbDefault = \Vvveb\config('db.default', 'default');
-$connection = \Vvveb\config('db.connections.' . $dbDefault, []);
+$connection = \Vvveb\config('db.connections.' . $dbDefault, []);
if ($connection) {
// Define default database configuration
- define('DB_ENGINE', $connection['engine']);
- define('DB_HOST', $connection['host'] ?? '');
- define('DB_USER', $connection['user'] ?? '');
- define('DB_PASS', $connection['password'] ?? '');
- define('DB_NAME', $connection['database'] ?? '');
- define('DB_PREFIX', $connection['prefix'] ?? '');
- define('DB_PORT', $connection['port'] ?? null);
-} else {/*
- define('DB_ENGINE', 'mysqli');
- define('DB_HOST', 'localhost');
- define('DB_USER', 'root');
- define('DB_PASS', '');
- define('DB_NAME', 'vvveb');
- define('DB_PREFIX', '');
- */
+ // skipped when an entry point (e.g. the test bootstrap) already defined
+ // DB_ENGINE to run against a different backend than config/db.php
+ if (!defined('DB_ENGINE')) {
+ define('DB_ENGINE', $connection['engine']);
+ define('DB_HOST', $connection['host'] ?? '');
+ define('DB_USER', $connection['user'] ?? '');
+ define('DB_PASS', $connection['password'] ?? '');
+ define('DB_NAME', $connection['database'] ?? '');
+ define('DB_PREFIX', $connection['prefix'] ?? '');
+ define('DB_PORT', $connection['port'] ?? null);
+ }
}
if (defined('DB_ENGINE')) {
define('DIR_SQL', DIR_APP . 'sql' . DS . DB_ENGINE . DS);
}
-function start() {
- //start session
- //Session :: getInstance();
+/**
+ * Bootstrap the application by resolving the site and dispatching the request.
+ *
+ * Loads the site configuration, defines site constants, loads plugins for
+ * the frontend, and dispatches the request via the FrontController.
+ *
+ * @return void
+ */
+function start(): void {
$site_id = false;
$path = $_SERVER['REQUEST_URI'] ?? '/';
-
+
if (isset($_GET['site_id'])) {
//check if admin user to allow site id override for editor
if ($admin = \Vvveb\System\User\Admin :: current()) {
@@ -408,11 +508,15 @@ function start() {
define('SITE_PATH', $site['path'] ?? '');
//load plugins first for APP
- if (APP != 'admin') {
+ if (APP !== 'admin') {
Plugins :: loadPlugins(SITE_ID);
}
- FrontController::dispatch($site);
+ defined('DISPATCH') || define('DISPATCH', true);
+
+ if (DISPATCH) {
+ FrontController::dispatch($site);
+ }
} else {
define('SITE_URL', $_SERVER['HTTP_HOST'] ?? 'localhost');
define('SITE_ID', 1);
diff --git a/system/core/view.php b/system/core/view.php
old mode 100644
new mode 100755
index 5b1d00a..a9fd3a5
--- a/system/core/view.php
+++ b/system/core/view.php
@@ -23,7 +23,6 @@
namespace Vvveb\System\Core;
use function Vvveb\__;
-use function Vvveb\addTranslationDomain;
use function Vvveb\config;
use function Vvveb\isEditor;
use Vvveb\System\Component\Component;
@@ -34,71 +33,108 @@ include DIR_SYSTEM . 'vtpl' . DS . 'vtpl.php';
#[\AllowDynamicProperties]
class View {
- static private $instance;
+ /** @var self|null */
+ private static ?self $instance = null;
- private $templatePath;
+ /** @var string|null */
+ private ?string $templatePath = null;
- private $theme;
+ /** @var string|null */
+ private ?string $theme = null;
- private $htmlPath;
+ /** @var string|null */
+ private ?string $htmlPath = null;
- private $template;
+ /** @var string|false|null */
+ private string|false|null $template = null;
- private $tplFile;
+ /** @var string|null */
+ private ?string $tplFile = null;
- private $templateEngine;
+ /** @var object|null Template engine instance (Vtpl) */
+ private ?object $templateEngine = null;
- private $compiledTemplate;
+ /** @var string|null */
+ private ?string $compiledTemplate = null;
- private $serviceTemplate;
+ /** @var string|null */
+ private ?string $serviceTemplate = null;
- private $component;
+ /** @var string|null */
+ private ?string $component = null;
- private $componentCount;
+ /** @var string|null */
+ private string|int|null $componentCount = null;
- private $componentContent;
+ /** @var string|null */
+ private ?string $componentContent = null;
- private $html;
+ /** @var string|null */
+ private ?string $html = null;
- private $useComponent;
+ /** @var bool|null */
+ private ?bool $useComponent = null;
- private $isEditor = false;
+ private bool $isEditor = false;
- private $_type = 'html';
+ private string $_type = 'html';
- function getTemplateEngineInstance() {
- if (! $this->templateEngine) {
+ /**
+ * Get the template engine instance, creating it if needed.
+ *
+ * @return object|null Template engine instance (Vtpl)
+ */
+ public function getTemplateEngineInstance(): ?object {
+ if (!$this->templateEngine) {
self :: getInstance();
}
return $this->templateEngine;
}
- function __construct($app = null) {
- //$this->theme = \Vvveb\config($this->app . '.theme', 'default');
- $this->app = $app ?? APP;
+ /**
+ * Resolve theme name, theme path and relative path for an app.
+ *
+ * Shared by the constructor and setTheme(): false selects the default
+ * theme for the app, a string selects (and sanitizes) that theme.
+ *
+ * @param string|false $theme Theme name or false for the app default
+ * @param string $app App name (app, admin, ...)
+ *
+ * @return array{0: string, 1: string, 2: string} theme, theme path, relative path
+ */
+ private function resolveThemePaths(string|false $theme, string $app): array {
$relativePath = PUBLIC_PATH . 'themes/';
- if ($this->app == 'app') {
- $this->theme = Sites::getTheme(SITE_ID) ?? 'default';
- $themePath = DIR_ROOT . join(DS, ['public', 'themes']) . DS . $this->theme . DS;
+ if (!$theme) {
+ if ($app === 'app') {
+ $theme = Sites::getTheme(SITE_ID);
+ $themePath = DIR_ROOT . implode(DS, ['public', 'themes']) . DS . $theme . DS;
+ } else {
+ $theme = config($app . '.theme', 'default');
+ $relativePath = PUBLIC_PATH . $app . '/';
+ $themePath = DIR_ROOT . DS . 'public' . DS . $app . DS . $theme . DS;
+ }
} else {
- $this->theme = config($this->app . '.theme', 'default');
- $relativePath = PUBLIC_PATH . $this->app . '/';
- $themePath = DIR_ROOT . DS . 'public' . DS . $this->app . DS . $this->theme . DS;
+ $theme = \Vvveb\filter('/[a-z0-9_-]*/', $theme, 30);
+ $themePath = DIR_ROOT . implode(DS, ['public', 'themes']) . DS . $theme . DS;
}
- if (isEditor()) {
- $this->isEditor = true;
- }
+ return [$theme, $themePath, $relativePath];
+ }
- /*
- $domain = $this->theme . '-domain';
- addTranslationDomain($domain);
- */
+ /**
+ * @param string|null $app
+ */
+ public function __construct(?string $app = null) {
+ $this->app = $app ?? APP;
+
+ [$this->theme, $themePath, $relativePath] = $this->resolveThemePaths(false, $this->app);
+
+ $this->isEditor = isEditor();
$this->htmlPath = $themePath;
- $this->templatePath = $themePath; //\Vvveb\config($this->app . '.theme', 'default') . DS;
+ $this->templatePath = $themePath;
if (isset($_REQUEST['_component_ajax']) && $this->isEditor) {
//check if user key is correct to allow override for editor
@@ -107,21 +143,21 @@ class View {
$key = \Vvveb\getConfig('app.key');
$decriptedKey = \Vvveb\decrypt($key, $userKey);
- if (($admin['admin_id'] != $adminId)|| $decriptedKey != $correctKey) {
- die('Invalid user key!');
+ if (($admin['admin_id'] != $adminId) || $decriptedKey != $correctKey) {
+ exit('Invalid user key!');
}
$this->component = \Vvveb\filter('/[a-z\-]+/', $_REQUEST['_component_ajax'], 80);
- $this->componentCount = \Vvveb\filter('/\d+/', $_REQUEST['_component_id'], 4);
+ $this->componentCount = \Vvveb\filter('/\d+/', $_REQUEST['_component_id'], 4);
$this->componentContent = $_POST['_component_content'] ?? '';
$this->html = $_POST['html'] ?? '';
} else {
- die('Invalid request!');
+ exit('Invalid request!');
}
}
- $selector = $count = null;
+ $selector = null;
if (isset($this->component)) {
$selector = '[data-v-component-' . $this->component . ']';
@@ -135,86 +171,116 @@ class View {
$template->setHtmlPath($this->htmlPath);
if ($this->isEditor) {
- $this->isEditor = true;
$template->removeVattrs(false);
+ $template->setMinifyHtml(false);
} else {
- //$template->removeVattrs(true);
+ $template->removeVattrs(false);
+ //$template->setMinifyHtml(true);
$template->setRelativePath($relativePath . $this->theme . '/');
}
$this->templateEngine = $template;
}
- static function getInstance() {
- if (self :: $instance === NULL) {
+ /**
+ * Get singleton instance of View.
+ */
+ public static function getInstance(): self {
+ if (self :: $instance === null) {
return self :: $instance = new self(); //create class instance
}
return self :: $instance;
}
- function removeVattrs($flag = true) {
+ /**
+ * Remove v-attributes from HTML output.
+ *
+ * @param bool $flag
+ *
+ * @return mixed
+ */
+ public function removeVattrs(bool $flag = true): mixed {
return $this->templateEngine->removeVattrs($flag);
}
- function setTheme($theme = false) {
- $relativePath = PUBLIC_PATH . 'themes/';
-
- if (! $theme) {
- if ($this->app == 'app') {
- $this->theme = Sites::getTheme(SITE_ID) ?? 'default';
- $themePath = DIR_ROOT . join(DS, ['public', 'themes']) . DS . $this->theme . DS;
- } else {
- $this->theme = config($this->app . '.theme', 'default');
- $relativePath = PUBLIC_PATH . $this->app . '/';
- $themePath = DIR_ROOT . DS . 'public' . DS . $this->app . DS . $this->theme . DS;
- }
- } else {
- $theme = \Vvveb\filter('/[a-z0-9_-]*/', $theme, 30);
- $this->theme = $theme;
- $themePath = DIR_ROOT . join(DS, ['public', 'themes']) . DS . $this->theme . DS;
- }
+ /**
+ * Set the active theme.
+ *
+ * @param string|false $theme Theme name or false to use default
+ *
+ * @return void
+ */
+ public function setTheme(string|false $theme = false): void {
+ [$this->theme, $themePath, $relativePath] = $this->resolveThemePaths($theme, $this->app);
$this->htmlPath = $themePath;
$this->templatePath = $themePath;
$this->templateEngine->setHtmlPath($this->htmlPath);
- if (! $this->isEditor) {
+ if (!$this->isEditor) {
$this->templateEngine->setRelativePath($relativePath . $this->theme . '/');
}
}
- function getTheme() {
+ /**
+ * Get the current theme name.
+ */
+ public function getTheme(): string {
return $this->theme;
}
- function getDocumentType() {
+ /**
+ * Get the document type from the template engine.
+ */
+ public function getDocumentType(): string {
return $this->templateEngine->getDocumentType();
}
- function getTemplatePath() {
+ /**
+ * Get the template path.
+ */
+ public function getTemplatePath(): string {
return $this->templatePath;
}
- function compiledTemplate() {
+ /**
+ * Get the compiled template path.
+ */
+ public function compiledTemplate(): ?string {
return $this->compiledTemplate;
}
- function set($data) {
- if ($data && is_array($data)) {
- foreach ($data as $key => &$value) {
- $this->$key = $value;
- }
+ /**
+ * Set dynamic properties from an associative array.
+ *
+ * @param array<string, mixed> $data
+ *
+ * @return void
+ */
+ public function set(array $data): void {
+ foreach ($data as $key => $value) {
+ $this->$key = $value;
}
}
- function serviceTemplate() {
+ /**
+ * Get the service template path.
+ */
+ public function serviceTemplate(): ?string {
return $this->serviceTemplate;
}
- function checkNeedRecompile($service = false) {
- if (! $this->template) {
- return false;
+ /**
+ * Check if the template needs recompilation and recompile if necessary.
+ *
+ * @param object|null $service
+ *
+ * @return void
+ */
+ public function checkNeedRecompile(?object $service = null): void {
+ if (!$this->template) {
+ return;
}
$this->template = str_replace(['/', '\\'], DS, $this->template);
@@ -222,15 +288,15 @@ class View {
$template = $this->template;
$templateMtime = null;
$templateFile = $templatePath . $template;
- $html = DIR_ROOT . APP . DS . 'template' . DS . $this->tplFile;
+ $tpl = DIR_ROOT . APP . DS . 'template' . DS . $this->tplFile;
//absolute path
- if ($this->template[0] == DS) {
+ if ($this->template[0] === DS) {
$templatePath = dirname($this->template) . DS;
$template = basename($this->template);
$templateFile = $this->template;
} else {
- if (strpos($this->template, 'plugins' . DS) === 0) {
+ if (str_starts_with($this->template, 'plugins' . DS)) {
$templatePath = DIR_PUBLIC . 'plugins' . DS;
//$templatePath = $this->templatePath = DIR_PUBLIC . 'plugins' . DS;
@@ -239,43 +305,47 @@ class View {
$pluginName = substr($template, 0, $p);
$nameSpace = substr($template, $p + 1);
- if ($this->app == 'admin') {
- $tpl = $pluginName . DS . join(DS, [$this->app, 'template']) . DS . $nameSpace;
+ if ($this->app === 'admin') {
$template = $pluginName . DS . $this->app . DS . $nameSpace;
} else {
- $tpl = $pluginName . DS . join(DS, [$this->app, 'template']) . DS . $nameSpace;
$template = $pluginName . DS . $nameSpace;
}
+ $tpl = $pluginName . DS . implode(DS, [$this->app, 'template']) . DS . $nameSpace;
+
$this->tplFile = str_replace(['.html', '.xml', '.json'], '.tpl', $tpl);
- $html = DIR_PLUGINS . $this->tplFile;
+ $tpl = DIR_PLUGINS . $this->tplFile;
$templateFile = $templatePath . $template;
}
}
- if (! file_exists($templatePath . $template)) {
- if ($template == 'error404.html' || $template == 'error500.html') {
- //if theme is missing error page then use the default
- $templateFile = DIR_PUBLIC . $template;
+ if (!file_exists($templatePath . $template)) {
+ if ($this->fallback) {
+ $template = $this->fallback;
+ $templateFile = $templatePath . $template;
} else {
- FrontController::notFound(true, [
- 'message' => __('Html template not found!'),
- 'file' => $templatePath . $template,
- ]);
+ if ($template === 'error404.html' || $template === 'error500.html') {
+ //if theme is missing error page then use the default
+ $templateFile = DIR_PUBLIC . $template;
+ } else {
+ FrontController::notFound(true, [
+ 'message' => __('Html template not found!'),
+ 'file' => $templatePath . $template,
+ ]);
+ }
}
}
- //$this->tplFile = $templateFile;
$this->templatePath = $templatePath;
if (file_exists($templateFile)) {
$templateMtime = filemtime($templateFile);
}
- $htmlMtime = 0;
+ $tplMtime = 0;
- if (file_exists($html)) {
- $htmlMtime = filemtime($html);
+ if (file_exists($tpl)) {
+ $tplMtime = filemtime($tpl);
}
$compiledMtime = 0;
@@ -284,19 +354,27 @@ class View {
$compiledMtime = @filemtime($this->compiledTemplate);
}
- if ((max($templateMtime, $htmlMtime) > $compiledMtime
- || ! file_exists($this->compiledTemplate))
+ if ((max($templateMtime, $tplMtime) > $compiledMtime
+ || !file_exists($this->compiledTemplate))
/*|| (defined('DEBUG') && DEBUG) */ || isset($_POST['_component_content'])) {
$this->compile($templateFile, $this->compiledTemplate, $service);
}
}
- private function compile($filename, $file, $service = false) {
- //@touch($file); //if recompiling takes longer avoid avoid other recompile requests
+ /**
+ * Compile the template file.
+ *
+ * @param string $filename
+ * @param string $file
+ * @param ?object $service
+ *
+ * @return void
+ */
+ private function compile(string $filename, string $file, ?object $service = null): void {
//regenerate component file
- if ($this->useComponent && ! defined('CLI')) {
+ if ($this->useComponent && !defined('CLI')) {
//regenerate components cache
- if (! $service) {
+ if (!$service) {
if ($this->html) {
$html = $this->html;
} else {
@@ -311,8 +389,8 @@ class View {
$this->templateEngine->addTemplatePath($this->htmlPath . 'template' . DS);
}
- list($this->template, $filename, $this->tplFile) =
- Event :: trigger(__CLASS__,__FUNCTION__, $this->template, $filename, $this->tplFile, $this->templateEngine, $this);
+ [$this->template, $filename, $this->tplFile] =
+ Event :: trigger(__CLASS__, __FUNCTION__, $this->template, $filename, $this->tplFile, $this->templateEngine, $this);
if ($this->html) {
$errors = $this->templateEngine->loadHtml($this->html);
@@ -321,11 +399,11 @@ class View {
}
//if no template defined use the default
- if ($this->tplFile[0] == DS) {
+ if ($this->tplFile[0] === DS) {
$this->tplFile = DIR_ROOT . APP . DS . 'template' . DS . 'common.tpl';
$this->templateEngine->loadTemplateFile($this->tplFile);
} else {
- if (strpos($this->template, 'plugins' . DS) === 0) {
+ if (str_starts_with($this->template, 'plugins' . DS)) {
//$template = str_replace('plugins' . DS, '', $this->template);
$template = $this->tplFile;
$p = strpos($template, DS);
@@ -347,27 +425,42 @@ class View {
$this->tplFile = "$pluginName/admin/template/$nameSpace";
}*/
} else {
- if (! file_exists(DIR_ROOT . APP . DS . 'template' . DS . $this->tplFile)) {
+ if (!file_exists(DIR_ROOT . APP . DS . 'template' . DS . $this->tplFile)) {
$this->tplFile = 'common.tpl';
}
$this->templateEngine->loadTemplateFileFromPath($this->tplFile);
}
}
- list($this->template, $filename, $this->tplFile) =
- Event :: trigger(__CLASS__,__FUNCTION__ . ':after', $this->template, $filename, $this->tplFile, $this->templateEngine, $this);
+ [$this->template, $filename, $this->tplFile] =
+ Event :: trigger(__CLASS__, __FUNCTION__ . ':after', $this->template, $filename, $this->tplFile, $this->templateEngine, $this);
$this->templateEngine->saveCompiledTemplate($file);
}
- function tplFile($filename) {
+ /**
+ * Set the template file name.
+ *
+ * @param string $filename
+ *
+ * @return void
+ */
+ public function tplFile(string $filename): void {
$this->tplFile = $filename;
}
- function template($filename = null) {
+ /**
+ * Get or set the template filename.
+ *
+ * @param string|false|null $filename Template filename, false to clear, or null to get current
+ * @param string|null|null $fallback
+ *
+ * @return string|false|null Current template filename
+ */
+ public function template(string|false|null $filename = null, ?string $fallback = null): string|false|null {
if ($filename === false) {
$this->template = false;
- return;
+ return null;
}
if ($filename) {
@@ -377,10 +470,10 @@ class View {
. $this->app . '_' . (defined('SITE_ID') ? SITE_ID : '-') . '_'
. ((is_null($this->component)) ? '' : $this->component . $this->componentCount . '_')
. $this->theme . '_'
- . str_replace([DS, '/', '\\'] , '_', $filename)
+ . str_replace([DS, '/', '\\'], '_', $filename)
. ($this->isEditor ? '-edit' : '');
- list($filename, $compiledFilename) = Event :: trigger(__CLASS__,__FUNCTION__, $filename, $compiledFilename, $this);
+ [$filename, $compiledFilename] = Event :: trigger(__CLASS__, __FUNCTION__, $filename, $compiledFilename, $this);
$this->compiledTemplate = $compiledFilename;
$this->serviceTemplate = $compiledFilename;
@@ -388,28 +481,57 @@ class View {
$this->template = $filename;
}
+ $this->fallback = $fallback;
+
return $this->template;
}
- function fragment($selector, $index = 0) {
+ /**
+ * Set the component selector and index for fragment rendering.
+ *
+ * @param string $selector CSS selector
+ * @param int $index Component index
+ *
+ * @return void
+ */
+ public function fragment(string $selector, string|int $index = 0): void {
$this->component = $selector;
$this->componentCount = $index;
}
- function setType($type) {
+ /**
+ * Set the output type (html, json, text).
+ *
+ * @param string $type
+ *
+ * @return void
+ */
+ public function setType(string $type): void {
$this->_type = $type;
}
- function getType() {
+ /**
+ * Get the current output type.
+ */
+ public function getType(): string {
return $this->_type;
}
- function render($useComponent = true, $output = true, $service = false) {
- Event :: trigger(__CLASS__,__FUNCTION__, $this->template, $this->tplFile, $this->templateEngine, $this);
+ /**
+ * Render the template.
+ *
+ * @param bool $useComponent Whether to use component rendering
+ * @param bool $output Whether to echo output or return it
+ * @param bool $service Whether this is a service template render
+ *
+ * @return mixed|string|null Rendered output string or void if outputting directly
+ */
+ public function render(bool $useComponent = true, bool $output = true, bool $service = false): mixed {
+ Event :: trigger(__CLASS__, __FUNCTION__, $this->template, $this->tplFile, $this->templateEngine, $this);
$this->useComponent = $useComponent;
- if ($useComponent && ! defined('CLI')) {
+ if ($useComponent && !defined('CLI')) {
if ($service) {
$service = new Component($this, $this->componentContent ? true : false, $this->componentContent);
} else {
@@ -417,29 +539,22 @@ class View {
}
}
- /*
- if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && ! isset($_REQUEST['_component_ajax'])) {
- $this->_type = 'json';
- }*/
+ if ($this->_type === 'text') {
+ if (!isset($this->text)) {
+ return null;
+ }
- if ($this->_type == 'text') {
- if (isset($this->text)) {
- if ($output) {
- echo $this->text;
- } else {
- return $this->text;
- }
+ if ($output) {
+ echo $this->text;
+
+ return null;
}
- return;
+ return $this->text;
}
- if ($this->_type == 'json') {
- $jsonFlags = 0;
-
- //if (defined('CLI')) {
+ if ($this->_type === 'json') {
$jsonFlags = JSON_PRETTY_PRINT;
- //}
ob_start();
if (isset($this->json)) {
@@ -454,22 +569,24 @@ class View {
return $json;
}
} else { //html
- if (! $this->template) {
+ if (!$this->template) {
self::template();
}
$this->checkNeedRecompile($service);
if ($this->compiledTemplate) {
- if (! file_exists($this->compiledTemplate)) {
+ if (!file_exists($this->compiledTemplate)) {
return FrontController::notFound(true, [
'message' => __('Compiled template not found!'),
- 'file' => $templatePath . $template,
+ 'file' => $this->template,
]);
}
try {
if ($output) {
include $this->compiledTemplate;
+
+ return '';
} else {
ob_start();
@@ -479,23 +596,26 @@ class View {
return $return;
}
- } catch (\ParseError | \Error $e) {
+ } catch (\ParseError|\Error $e) {
static $handled;
if ($handled) {
if (DEBUG) {
echo $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine();
} else {
- die('Server error, enable debug for more info');
+ exit('Server error, enable debug for more info');
}
- return;
+
+ return null;
}
$handled = true;
$data = \Vvveb\System\Core\exceptionToArray($e, $this->compiledTemplate);
- return FrontController :: notFound(false, $data, 500);
+ FrontController :: notFound(false, $data, 500);
}
}
}
+
+ return '';
}
}
diff --git a/system/cron.php b/system/cron.php
old mode 100755
new mode 100644
index 2e60dba..c96ac18
--- a/system/cron.php
+++ b/system/cron.php
@@ -23,34 +23,144 @@
namespace Vvveb\System;
class Cron {
- private static $crons;
+ /**
+ * @var array<int, array<int, array<string, array{0: callable, 1: mixed, 2: ?string}>>>
+ * Registered cron jobs grouped by interval (seconds) and priority.
+ * Each job entry is [callback, start, description].
+ */
+ private static array $crons = [];
- public static function getInstance() {
+ /**
+ * Get singleton instance of the Cron class.
+ *
+ * @return self
+ */
+ public static function getInstance(): self {
static $inst = null;
if ($inst === null) {
- $inst = new Cron();
+ $inst = new self();
}
return $inst;
}
- public function __construct() {
- }
+ /**
+ * Constructor.
+ */
+ public function __construct() {}
- public static function getCrons() {
- return self :: $crons;
+ /**
+ * Get all registered cron jobs.
+ *
+ * @return array<int, array<int, array<string, array{0: callable, 1: mixed, 2: ?string}>>>
+ * Cron jobs grouped by interval (seconds) and priority.
+ */
+ public static function getCrons(): array {
+ return self::$crons;
}
- public static function runAll() {
+ /**
+ * Run all registered cron jobs.
+ *
+ * @return array<string, array<int, mixed>> Cron name => result data.
+ */
+ public static function runAll(): array {
+ $results = [];
+
+ foreach (self::$crons as $priorities) {
+ foreach ($priorities as $jobs) {
+ foreach (array_keys($jobs) as $cron) {
+ $results[$cron] = self::run($cron);
+ }
+ }
+ }
+
+ return $results;
}
- public static function run($cron) {
+ /**
+ * Run a single cron job by name.
+ *
+ * @param string $cron Cron job name (namespace-name).
+ *
+ * @return array<array-key, mixed> Result data.
+ */
+ public static function run(string $cron): array {
+ foreach (self::$crons as $priorities) {
+ foreach ($priorities as $jobs) {
+ if (!isset($jobs[$cron])) {
+ continue;
+ }
+
+ [$callback, $start] = $jobs[$cron];
+
+ if (!self::isDue($start)) {
+ return [];
+ }
+
+ try {
+ return (array)$callback($cron);
+ } catch (\Throwable $e) {
+ \Vvveb\logError(sprintf('Cron job "%s" failed: %s', $cron, $e->getMessage()));
+
+ try {
+ Notifications::trigger('cronjob.fail', [
+ 'subject' => sprintf('Cron job "%s" failed', $cron),
+ 'message' => $e->getMessage(),
+ 'cron' => $cron,
+ 'error' => $e->getMessage(),
+ ]);
+ } catch (\Throwable $ignored) {
+ // notifications must never break cron execution
+ }
+
+ return ['error' => $e->getMessage()];
+ }
+ }
+ }
+
return [];
}
- public static function registerCron($cron, $class, $description) {
- self :: $crons[$cron] = $class;
+ /**
+ * Check whether a cron job start time has been reached.
+ *
+ * @param mixed $start Timestamp, datetime string or null (run immediately).
+ *
+ * @return bool
+ */
+ private static function isDue($start): bool {
+ if (!$start) {
+ return true;
+ }
+
+ $time = is_numeric($start) ? (int)$start : strtotime((string)$start);
+
+ return $time === false || $time <= time();
+ }
+
+ /**
+ * Register a cron job.
+ *
+ * @param string $namespace Plugin name
+ * @param string $name Action name
+ * @param callable $callback Code to run
+ * @param int $priority Priority
+ * @param int $interval Default every minute
+ * @param int|string|null $start Start timestamp or datetime string, null = immediately
+ * @param string|null $description Human-readable description.
+ *
+ * @return bool Always returns true.
+ */
+ public static function registerCron(string $namespace, string $name, callable $callback, int $priority = 1, int $interval = 60, $start = null, ?string $description = null): bool {
+ $key = $namespace . '-' . $name;
+ if (empty(self::$crons[$interval])) {
+ self::$crons[$interval][$priority] = [];
+ }
+
+ self::$crons[$interval][$priority][$key] = [$callback, $start, $description];
+ ksort(self::$crons[$interval], SORT_NUMERIC);
return true;
}
diff --git a/system/custom-field.php b/system/custom-field.php
deleted file mode 100755
index ab625ed..0000000
--- a/system/custom-field.php
+++ /dev/null
@@ -1,31 +0,0 @@
-<?php
-
-/**
- * Vvveb
- *
- * Copyright (C) 2022 Ziadin Givan
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <https://www.gnu.org/licenses/>.
- *
- */
-
-namespace Vvveb\System;
-
-class CustomField {
- function __construct($options) {
- }
-
- function results() {
- }
-}
diff --git a/system/data/capabilities.php b/system/data/capabilities.php
index 7c3200f..b05c9c8 100755
--- a/system/data/capabilities.php
+++ b/system/data/capabilities.php
@@ -23,8 +23,8 @@
use function Vvveb\__;
return [
- 'view_other_posts' => __('View other users posts'),
- 'edit_other_posts' => __('Edit other users posts'),
+ 'view_other_posts' => __('View other users posts'),
+ 'edit_other_posts' => __('Edit other users posts'),
'view_other_products' => __('View other users products'),
'edit_other_products' => __('Edit other users products'),
'view_other_sites' => __('View other users sites'),
diff --git a/system/data/languages-list.php b/system/data/languages-list.php
old mode 100755
new mode 100644
index 57dab8a..9474001
--- a/system/data/languages-list.php
+++ b/system/data/languages-list.php
@@ -24,11 +24,11 @@ return
[
//languages with translations first
'zh_CN' => [
- 'name' => '简体中文 (Chinese)',
- 'charset' => 'UTF-8',
- 'code' => 'zh-cn',
- 'emoji' => '🇨🇳',
- 'pack' => true,
+ 'name' => '简体中文 (Chinese)',
+ 'charset' => 'UTF-8',
+ 'code' => 'zh-cn',
+ 'emoji' => '🇨🇳',
+ 'pack' => true,
],
'ar' => [
'name' => 'Arabic',
@@ -36,69 +36,77 @@ return
'code' => 'ar',
'rtl' => true,
'emoji' => '🇦🇷',
- 'pack' => true,
+ 'pack' => true,
],
'de_DE' => [
'name' => 'German (Germany)',
'charset' => 'ISO-8859-1',
'code' => 'de-de',
'emoji' => '🇩🇪',
- 'pack' => true,
+ 'pack' => true,
+ ],
+ 'nl_NL' => [
+ 'name' => 'Dutch (Netherlands)',
+ 'charset' => 'ISO-8859-15',
+ 'code' => 'nl-nl',
+ 'emoji' => '🇳🇱',
+ 'pack' => true,
],
'en_US' => [
'name' => 'English (United States)',
'charset' => 'UTF-8',
'code' => 'en-us',
'emoji' => '🇺🇸',
+ 'pack' => true,
],
'fr_FR' => [
'name' => 'French (France)',
'charset' => 'UTF-8',
'code' => 'fr-fr',
'emoji' => '🇫🇷',
- 'pack' => true,
+ 'pack' => true,
],
'it_IT' => [
'name' => 'Italian (Italy)',
'charset' => 'ISO-8859-1',
'code' => 'it-it',
'emoji' => '🇮🇹',
- 'pack' => true,
+ 'pack' => true,
],
'pt_BR' => [
- 'name' => 'Portuguese (Brazil)',
- 'charset' => 'ISO-8859-1',
- 'code' => 'pt-br',
- 'emoji' => '🇵🇹',
- 'pack' => true,
+ 'name' => 'Portuguese (Brazil)',
+ 'charset' => 'ISO-8859-1',
+ 'code' => 'pt-br',
+ 'emoji' => '🇵🇹',
+ 'pack' => true,
],
'ro_RO' => [
'name' => 'Romanian (Romania)',
'charset' => 'UTF-8',
'code' => 'ro-ro',
'emoji' => '🇷🇴',
- 'pack' => true,
+ 'pack' => true,
],
'ru_RU' => [
'name' => 'Russian (Russia)',
'charset' => 'UTF-8',
'code' => 'ru-ru',
'emoji' => '🇷🇺',
- 'pack' => true,
+ 'pack' => true,
],
'es_ES' => [
'name' => 'Spanish (Spain)',
'charset' => 'UTF-8',
'code' => 'es-es',
'emoji' => '🇪🇸',
- 'pack' => true,
+ 'pack' => true,
],
'tr_TR' => [
'name' => 'Turkish (Turkey)',
'charset' => 'ISO-8859-9',
'code' => 'tr-tr',
'emoji' => '🇹🇷',
- 'pack' => true,
+ 'pack' => true,
],
//---
'af_NA' => [
@@ -539,22 +547,22 @@ return
'code' => 'zh-hant-tw',
],
'zh' => [
- 'name' => 'Chinese',
- 'charset' => 'UTF-8',
- 'code' => 'zh',
- 'emoji' => '🇨🇳',
+ 'name' => 'Chinese',
+ 'charset' => 'UTF-8',
+ 'code' => 'zh',
+ 'emoji' => '🇨🇳',
],
'zh_TW' => [
- 'name' => '繁體中文 (Chinese)',
- 'charset' => 'UTF-8',
- 'code' => 'zh-tw',
- 'emoji' => '🇨🇳',
+ 'name' => '繁體中文 (Chinese)',
+ 'charset' => 'UTF-8',
+ 'code' => 'zh-tw',
+ 'emoji' => '🇨🇳',
],
'zh_HK' => [
- 'name' => '香港中文 (Chinese)',
- 'charset' => 'UTF-8',
- 'code' => 'zh-hk',
- 'emoji' => '🇨🇳',
+ 'name' => '香港中文 (Chinese)',
+ 'charset' => 'UTF-8',
+ 'code' => 'zh-hk',
+ 'emoji' => '🇨🇳',
],
'kw_GB' => [
'name' => 'Cornish (United Kingdom)',
@@ -606,12 +614,6 @@ return
'code' => 'nl-be',
'emoji' => '🇳🇱',
],
- 'nl_NL' => [
- 'name' => 'Dutch (Netherlands)',
- 'charset' => 'ISO-8859-15',
- 'code' => 'nl-nl',
- 'emoji' => '🇳🇱',
- ],
'nl' => [
'name' => 'Dutch',
'charset' => 'ISO-8859-15',
@@ -638,31 +640,31 @@ return
'name' => 'English (Australia)',
'charset' => 'UTF-8',
'code' => 'en-au',
- 'emoji' => '🇺🇸',
+ 'emoji' => '🇬🇧',
],
'en_BE' => [
'name' => 'English (Belgium)',
'charset' => 'UTF-8',
'code' => 'en-be',
- 'emoji' => '🇺🇸',
+ 'emoji' => '🇬🇧',
],
'en_BZ' => [
'name' => 'English (Belize)',
'charset' => 'UTF-8',
'code' => 'en-bz',
- 'emoji' => '🇺🇸',
+ 'emoji' => '🇬🇧',
],
'en_BW' => [
'name' => 'English (Botswana)',
'charset' => 'UTF-8',
'code' => 'en-bw',
- 'emoji' => '🇺🇸',
+ 'emoji' => '🇬🇧',
],
'en_CA' => [
'name' => 'English (Canada)',
'charset' => 'UTF-8',
'code' => 'en-ca',
- 'emoji' => '🇺🇸',
+ 'emoji' => '🇬🇧',
],
'en_GU' => [
'name' => 'English (Guam)',
@@ -674,37 +676,37 @@ return
'name' => 'English (Hong Kong SAR China)',
'charset' => 'UTF-8',
'code' => 'en-hk',
- 'emoji' => '🇺🇸',
+ 'emoji' => '🇬🇧',
],
'en_IN' => [
'name' => 'English (India)',
'charset' => 'UTF-8',
'code' => 'en-in',
- 'emoji' => '🇺🇸',
+ 'emoji' => '🇬🇧',
],
'en_IE' => [
'name' => 'English (Ireland)',
'charset' => 'UTF-8',
'code' => 'en-ie',
- 'emoji' => '🇺🇸',
+ 'emoji' => '🇬🇧',
],
'en_IL' => [
'name' => 'English (Israel)',
'charset' => 'UTF-8',
'code' => 'en-il',
- 'emoji' => '🇺🇸',
+ 'emoji' => '🇬🇧',
],
'en_JM' => [
'name' => 'English (Jamaica)',
'charset' => 'UTF-8',
'code' => 'en-jm',
- 'emoji' => '🇺🇸',
+ 'emoji' => '🇬🇧',
],
'en_MT' => [
'name' => 'English (Malta)',
'charset' => 'UTF-8',
'code' => 'en-mt',
- 'emoji' => '🇺🇸',
+ 'emoji' => '🇬🇧',
],
'en_MH' => [
'name' => 'English (Marshall Islands)',
@@ -716,55 +718,55 @@ return
'name' => 'English (Mauritius)',
'charset' => 'UTF-8',
'code' => 'en-mu',
- 'emoji' => '🇺🇸',
+ 'emoji' => '🇬🇧',
],
'en_NA' => [
'name' => 'English (Namibia)',
'charset' => 'UTF-8',
'code' => 'en-na',
- 'emoji' => '🇺🇸',
+ 'emoji' => '🇬🇧',
],
'en_NZ' => [
'name' => 'English (New Zealand)',
'charset' => 'UTF-8',
'code' => 'en-nz',
- 'emoji' => '🇺🇸',
+ 'emoji' => '🇬🇧',
],
'en_MP' => [
'name' => 'English (Northern Mariana Islands)',
'charset' => 'UTF-8',
'code' => 'en-mp',
- 'emoji' => '🇺🇸',
+ 'emoji' => '🇬🇧',
],
'en_PK' => [
'name' => 'English (Pakistan)',
'charset' => 'UTF-8',
'code' => 'en-pk',
- 'emoji' => '🇺🇸',
+ 'emoji' => '🇬🇧',
],
'en_PH' => [
'name' => 'English (Philippines)',
'charset' => 'UTF-8',
'code' => 'en-ph',
- 'emoji' => '🇺🇸',
+ 'emoji' => '🇬🇧',
],
'en_SG' => [
'name' => 'English (Singapore)',
'charset' => 'UTF-8',
'code' => 'en-sg',
- 'emoji' => '🇺🇸',
+ 'emoji' => '🇬🇧',
],
'en_ZA' => [
'name' => 'English (South Africa)',
'charset' => 'UTF-8',
'code' => 'en-za',
- 'emoji' => '🇺🇸',
+ 'emoji' => '🇬🇧',
],
'en_TT' => [
'name' => 'English (Trinidad and Tobago)',
'charset' => 'UTF-8',
'code' => 'en-tt',
- 'emoji' => '🇺🇸',
+ 'emoji' => '🇬🇧',
],
'en_UM' => [
'name' => 'English (U.S. Minor Outlying Islands)',
@@ -782,19 +784,19 @@ return
'name' => 'English (United Kingdom)',
'charset' => 'UTF-8',
'code' => 'en-gb',
- 'emoji' => '🇺🇸',
+ 'emoji' => '🇬🇧',
],
'en_ZW' => [
'name' => 'English (Zimbabwe)',
'charset' => 'UTF-8',
'code' => 'en-zw',
- 'emoji' => '🇺🇸',
+ 'emoji' => '🇬🇧',
],
'en' => [
'name' => 'English',
'charset' => 'UTF-8',
'code' => 'en',
- 'emoji' => '🇺🇸',
+ 'emoji' => '🇬🇧',
],
'eo' => [
'name' => 'Esperanto',
diff --git a/system/db.php b/system/db.php
old mode 100755
new mode 100644
index ed1a920..fa878f2
--- a/system/db.php
+++ b/system/db.php
@@ -23,21 +23,29 @@
namespace Vvveb\System;
class Db {
- public static function getInstance($engine = DB_ENGINE) {
+ /**
+ * Get or create a database driver instance for the given engine.
+ *
+ * @param string $engine The database engine identifier (e.g. 'Mysql').
+ *
+ * @return static|null The driver instance, or null when $engine is falsy.
+ */
+ public static function getInstance(string $engine = DB_ENGINE): ?object {
static $inst = [];
- if (! $engine) {
- return;
+ if (!$engine) {
+ return null;
}
-
- if (! isset($inst[$engine]) || $inst[$engine] === null) {
+
+ if (!isset($inst[$engine])) {
$driverName = "\Vvveb\System\Db\\$engine";
- if (class_exists($driverName)) {
- $inst[$engine] = new $driverName();
+ //if (class_exists($driverName)) {
+ $inst[$engine] = new $driverName();
+ /*
} else {
throw new \Exception("Error loading db driver '$driverName'!");
- }
+ }*/
}
return $inst[$engine];
diff --git a/system/email.php b/system/email.php
old mode 100755
new mode 100644
index 11d0b05..9b09d9f
--- a/system/email.php
+++ b/system/email.php
@@ -23,26 +23,51 @@
namespace Vvveb\System;
class Email {
- private $driver;
-
- protected $option;
-
- protected $attachments = [];
-
- public static function getInstance() {
+ /** @var object The mail driver instance. */
+ private object $driver;
+
+ /** @var array<string, mixed> Mail configuration options. */
+ protected array $option = [];
+
+ /** @var list<string> Attached file paths. */
+ protected array $attachments = [];
+
+ /**
+ * Get singleton instance of the Email class.
+ *
+ * @param array<array-key, mixed> $additionalOptions
+ *
+ * @return self
+ */
+ public static function getInstance(array $additionalOptions = []): self {
static $inst = null;
if ($inst === null) {
$driver = \Vvveb\config('mail.driver', 'mail');
$options = \Vvveb\config("mail.$driver", []);
+ $options += $additionalOptions;
$inst = new self($driver, $options);
}
return $inst;
}
- public function __construct($driver = 'mail', &$option = []) {
- $class = '\\Vvveb\\System\\Mail\\' . $driver;
+ /**
+ * Initialize the mail driver.
+ *
+ * @param string $driver Mail driver name or fully-qualified class name.
+ * @param array<string, mixed> &$option Mail options passed by reference.
+ *
+ * @throws \Exception If the driver class does not exist.
+ *
+ * @return object The instantiated mail driver.
+ */
+ public function __construct(string $driver = 'mail', array &$option = []) {
+ if (strpos($driver, '\\')) {
+ $class = $driver;
+ } else {
+ $class = '\Vvveb\System\\Mail\\' . $driver;
+ }
if (class_exists($class)) {
$this->option = &$option;
@@ -50,66 +75,127 @@ class Email {
} else {
throw new \Exception("Could not load mail driver '$driver'");
}
-
- return $this->driver;
}
- public function setTo($to) {
+ /**
+ * Set the recipient email address.
+ *
+ * @param array<array-key, mixed>|string $to Recipient email.
+ *
+ * @return void
+ */
+ public function setTo(array|string $to): void {
$this->option['to'] = $to;
}
- public function setFrom($from) {
+ /**
+ * Set the sender email address.
+ *
+ * @param string $from Sender email.
+ *
+ * @return void
+ */
+ public function setFrom(string $from): void {
$this->option['from'] = $from;
}
- public function setSender($sender) {
+ /**
+ * Set the sender display name.
+ *
+ * @param string $sender Sender name.
+ *
+ * @return void
+ */
+ public function setSender(string $sender): void {
$this->option['sender'] = $sender;
}
- public function setReplyTo($reply_to) {
+ /**
+ * Set the reply-to email address.
+ *
+ * @param string $reply_to Reply-to email.
+ *
+ * @return void
+ */
+ public function setReplyTo(string $reply_to): void {
$this->option['reply_to'] = $reply_to;
}
- public function setSubject($subject) {
+ /**
+ * Set the email subject.
+ *
+ * @param string $subject Email subject.
+ *
+ * @return void
+ */
+ public function setSubject(string $subject): void {
$this->option['subject'] = $subject;
}
- public function setText($text) {
+ /**
+ * Set the plain text body.
+ *
+ * @param string $text Plain text content.
+ *
+ * @return void
+ */
+ public function setText(string $text): void {
$this->option['text'] = $text;
}
- public function setHtml($html) {
+ /**
+ * Set the HTML body.
+ *
+ * @param string $html HTML content.
+ *
+ * @return void
+ */
+ public function setHtml(string $html): void {
$this->option['html'] = $html;
}
- public function addAttachment($filename) {
+ /**
+ * Add an attachment file path.
+ *
+ * @param string $filename Path to the file to attach.
+ *
+ * @return void
+ */
+ public function addAttachment(string $filename): void {
$this->option['attachments'][] = $filename;
}
- public function send() {
- if (! $this->option['to']) {
+ /**
+ * Validate required fields and send the email.
+ *
+ * @throws \Exception If a required field is missing.
+ *
+ * @return bool
+ */
+ public function send(): bool {
+ if (!$this->option['to']) {
throw new \Exception('Email to required!');
}
- if (! $this->option['from']) {
+ if (!$this->option['from']) {
throw new \Exception('Email from required!');
}
- if (! $this->option['sender']) {
+ if (!$this->option['sender']) {
throw new \Exception('Email sender required!');
}
- if (! $this->option['subject']) {
+ if (!$this->option['subject']) {
throw new \Exception('Email subject required!');
}
- if (! $this->option['html']) {
+ if (!$this->option['html']) {
throw new \Exception('Email message required!');
}
$option = &$this->option;
- list($option, $this->driver) = Event::trigger(__CLASS__, __FUNCTION__, $option, $this->driver);
+ [$option, $this->driver] = Event::trigger(__CLASS__, __FUNCTION__, $option, $this->driver);
return $this->driver->send();
}
diff --git a/system/event.php b/system/event.php
index 9161f11..2e0a367 100755
--- a/system/event.php
+++ b/system/event.php
@@ -22,30 +22,24 @@
namespace Vvveb\System;
-trait EventTrait {
- static function trigger($method, $params = NULL) {
- if ($params === NULL) {
- return $params = \Vvveb\System\Event::trigger(__CLASS__, $method);
- } else {
- return $params = \Vvveb\System\Event::trigger(__CLASS__, $method, $params);
- }
- }
-
- public static function on($namespace, $name, $id, $callback, $priority = 0) {
- return $params = \Vvveb\System\Event::on($namespace, $name, __CLASS__ . '::' . $id, $callback, $priority);
- }
-}
-
class Event {
- private static $events = [];
-
- private function __construct() {
- }
-
- private function __clone() {
- }
-
- public static function on($namespace, $name, $id, $callback, $priority = 1000) {
+ /** @var array<string, array<string, array<int, array<string, callable>>>> */
+ private static array $events = [];
+
+ private function __construct() {}
+
+ private function __clone() {}
+
+ /**
+ * @param string $namespace
+ * @param string $name
+ * @param string $id
+ * @param callable $callback
+ * @param int $priority
+ *
+ * @return void
+ */
+ public static function on(string $namespace, string $name, string $id, callable $callback, int $priority = 1000): void {
if (empty(self::$events[$namespace][$name][$priority])) {
self::$events[$namespace][$name][$priority] = [];
}
@@ -54,32 +48,39 @@ class Event {
ksort(self::$events[$namespace][$name], SORT_NUMERIC);
}
- public static function trigger($namespace, $name) {
+ /**
+ * Trigger all callbacks registered for the given namespace and name.
+ * Additional arguments are passed to each callback.
+ *
+ * @param string $namespace
+ * @param string $name
+ * @param mixed ...$args
+ *
+ * @return mixed
+ */
+ public static function trigger(string $namespace, string $name, mixed ...$args): mixed {
$hasParams = false;
- $params = func_get_args();
- $params = array_slice($params, 2);
+ $params = $args;
if (empty(self::$events[$namespace][$name])) {
return $params;
}
//$params can be changed by events and be empty, set flag so that we know to return it
- if ($params || isset($params[0])) {
+ if ($params) {
$hasParams = true;
}
foreach (self::$events[$namespace][$name] as $priority => $events) {
foreach ($events as $id => $event) {
- if (is_callable($event)) {
- if ($hasParams) {
- $ret = call_user_func_array($event, $params);
- //if event does not filter parameters or someone forgot to return them keep previous parameters
- if ($ret !== null) {
- $params = $ret;
- }
- } else {
- call_user_func($event);
+ if ($hasParams) {
+ $ret = $event(...$params);
+ //if event does not filter parameters or someone forgot to return them keep previous parameters
+ if ($ret !== null) {
+ $params = $ret;
}
+ } else {
+ $event();
}
}
}
@@ -87,45 +88,68 @@ class Event {
if ($hasParams) {
return $params;
}
+
+ return null;
}
- public static function off($namespace, $name = false, $eventId = false) {
- if ($eventId && ! empty(self::$events[$namespace][$name])) {
+ /**
+ * @param string $namespace
+ * @param string|false $name
+ * @param string|false $eventId
+ *
+ * @return bool
+ */
+ public static function off(string $namespace, string|false $name = false, string|false $eventId = false): bool {
+ if ($eventId && $name && !empty(self::$events[$namespace][$name])) {
foreach (self::$events[$namespace][$name] as $priority => &$events) {
foreach ($events as $id => $event) {
if ($id == $eventId) {
unset($events[$id]);
- break 2;
-
return true;
}
}
}
- } else {
- if ($name && ! empty(self::$events[$namespace][$name])) {
- unset(self::$events[$namespace][$name]);
-
- return true;
- } else {
- if ($namespace && ! empty(self::$events[$namespace])) {
- unset(self::$events[$namespace]);
-
- return true;
+ } elseif ($eventId && !empty(self::$events[$namespace])) {
+ //no name given, remove the event id from all names
+ $removed = false;
+
+ foreach (self::$events[$namespace] as &$priorities) {
+ foreach ($priorities as &$events) {
+ if (isset($events[$eventId])) {
+ unset($events[$eventId]);
+ $removed = true;
+ }
}
}
+
+ return $removed;
+ } elseif ($name && !empty(self::$events[$namespace][$name])) {
+ unset(self::$events[$namespace][$name]);
+
+ return true;
+ } elseif ($namespace && !empty(self::$events[$namespace])) {
+ unset(self::$events[$namespace]);
+
+ return true;
}
return false;
}
- public static function getEvents($namespace = false, $name = false) {
+ /**
+ * @param string|false $namespace
+ * @param string|false $name
+ *
+ * @return array<array-key, mixed>
+ */
+ public static function getEvents(string|false $namespace = false, string|false $name = false): array {
if ($name) {
return self::$events[$namespace][$name] ?? [];
- } else {
- if ($namespace) {
- return self::$events[$namespace] ?? [];
- }
+ }
+
+ if ($namespace) {
+ return self::$events[$namespace] ?? [];
}
return self::$events;
diff --git a/system/extensions/extensions.php b/system/extensions/extensions.php
index e29abce..0b90337 100755
--- a/system/extensions/extensions.php
+++ b/system/extensions/extensions.php
@@ -28,30 +28,57 @@ use function Vvveb\getUrl;
use Vvveb\System\Event;
use Vvveb\System\Functions\Str;
use Vvveb\System\Import\Rss;
-use function Vvveb\unzip;
abstract class Extensions {
- static protected $extensions = [];
-
- static protected $categories = [];
-
- static protected $extension = 'extension';
-
- static protected $baseDir = 'extension';
-
- static protected $url;
-
- static protected $feedUrl;
-
- const KEY_VALUE_REGEX = '/^([\w ]+):\s+(.+)$/m';
-
- static function getParams($comments) {
+ /**
+ * @var array<array-key, mixed>
+ */
+ protected static array $extensions = [];
+
+ /**
+ * @var array<array-key, mixed>
+ */
+ protected static array $categories = [];
+
+ /**
+ * @var string
+ */
+ protected static string $extension = 'extension';
+
+ /**
+ * @var string
+ */
+ protected static string $baseDir = 'extension';
+
+ /**
+ * @var string
+ */
+ protected static string $url = '';
+
+ /**
+ * @var string
+ */
+ protected static string $feedUrl = '';
+
+ /**
+ * @var string
+ */
+ protected static string $categoriesFeedUrl = '';
+
+ public const KEY_VALUE_REGEX = '/^([\w -]+):\s+(.+?)\s*$/m';
+
+ /**
+ * @param string $comments
+ *
+ * @return array<array-key, mixed>
+ */
+ public static function getParams(string $comments): array {
$results = [];
- if (preg_match_all(static :: KEY_VALUE_REGEX, $comments, $matches)) {
- $matches[1] = array_map(function ($key) {
- return str_replace(' ','-',strtolower(trim($key)));
- }, $matches[1]);
+ if (preg_match_all(static::KEY_VALUE_REGEX, $comments, $matches)) {
+ $matches[1] = array_map(fn ($key) => str_replace(' ', '-', strtolower(trim($key))), $matches[1]);
+
+ $matches[2] = array_map('trim', $matches[2]);
$results = array_combine($matches[1], $matches[2]);
}
@@ -59,47 +86,51 @@ abstract class Extensions {
return $results;
}
- static function getComments($content) {
- //$content = file_get_contents($file);
- if (function_exists('token_get_all')) {
- $docComments = [];
-
- foreach (token_get_all($content) as $entry) {
- if ($entry[0] == T_DOC_COMMENT || $entry[0] == T_COMMENT) {
- $docComments[] = $entry[1];
- }
- }
-
- return implode("\n", $docComments);
- } else {
- if (preg_match_all('@(?s)/\*.*?\*/@', $content, $matches, PREG_PATTERN_ORDER)) {
- return implode("\n", $matches[0] ?? []);
- }
+ /**
+ * @param string $content
+ *
+ * @return string
+ */
+ public static function getComments(string $content): string {
+ //extract block comments; line comments are not used for extension info headers
+ if (preg_match_all('@(?s)/\*.*?\*/@', $content, $matches, PREG_PATTERN_ORDER)) {
+ return implode("\n", $matches[0]);
}
return '';
}
- static function getInfo($content, $name = false) {
- $comments = static :: getComments($content);
- $params = static :: getParams($comments);
+ /**
+ * @param string $content
+ * @param string|false $name
+ *
+ * @return array<array-key, mixed>
+ */
+ public static function getInfo(string $content, string|false $name = false): array {
+ $comments = static::getComments($content);
+ $params = static::getParams($comments);
if (isset($params['status'])) {
unset($params['status']);
}
if (isset($params['category']) && $name) {
- static :: $categories[$params['category']][] = $name;
+ static::$categories[$params['category']][] = $name;
}
return $params;
}
- static function getListInfo($path) {
- if (isset(static :: $extensions[static :: $extension])) {
- return static :: $extensions[static :: $extension];
+ /**
+ * @param string $path
+ *
+ * @return array<array-key, mixed>
+ */
+ public static function getListInfo(string $path): array {
+ if (isset(static::$extensions[static::$extension])) {
+ return static::$extensions[static::$extension];
} else {
- static :: $extensions[static :: $extension] = [];
+ static::$extensions[static::$extension] = [];
}
$adminPath = \Vvveb\adminPath();
@@ -107,92 +138,115 @@ abstract class Extensions {
foreach ($list as $file) {
$content = file_get_contents($file);
- $dir = Str::match('@(.+)/[a-z]+.\w+$@', $file);
- $folder = Str::match('@/([^/]+)/[a-z]+.\w+$@', $file);
+ $dir = Str::match('@(.+)[\\/][a-z]+.\w+$@', $file);
+ $folder = Str::match('@[\\/]([^\\/]+)[\\/][a-z]+.\w+$@', $file);
$info = static::getInfo($content, $folder);
$info['file'] = $file;
$info['folder'] = $folder;
$info['import'] = file_exists($dir . DS . 'import');
if (isset($info['settings'])) {
- $info['settings']= str_replace('/admin/', $adminPath, $info['settings']);
+ $info['settings'] = str_replace('/admin/', $adminPath, $info['settings']);
}
// plugin folder does not match slug
- if (! isset($info['slug']) || ($info['slug'] != $info['folder'])) {
+ if (!isset($info['slug']) || ($info['slug'] !== $info['folder'])) {
$info['status'] = 'slug_folder_mismatch';
$info['slug'] = $info['folder'];
}
- static :: $extensions[static :: $extension][$folder] = $info;
+ static::$extensions[static::$extension][$folder] = $info;
}
- return static :: $extensions[static :: $extension];
+ return static::$extensions[static::$extension];
}
- static function getCategories() {
- return static :: $categories;
+ /**
+ * @return array<array-key, mixed>
+ */
+ public static function getCategories(): array {
+ return static::$categories;
}
- static function download($url) {
- $f = false;
+ /**
+ * @param string $url
+ *
+ * @return string|false
+ */
+ public static function download(string $url): string|false {
$temp = @tempnam(sys_get_temp_dir(), 'vvveb_plugin');
- if (! $temp) {
- $temp = @tmpfile();
+ if (!$temp && ($handle = @tmpfile())) {
+ //tmpfile() returns a stream, not a path: resolve it via metadata.
+ //fclose() deletes the file, the path is recreated by file_put_contents below.
+ $meta = stream_get_meta_data($handle);
+ $temp = $meta['uri'] ?? false;
+ fclose($handle);
}
//if temp still fails use cache dir, some shared hosting have this issue
- if (! $temp) {
+ if (!$temp) {
$temp = DIR_CACHE . APP . '.extension.' . md5($url) . '.zip';
}
- if ($content = download($url)) {
- $f = file_put_contents($temp, $content, LOCK_EX);
- if ($f) {
- return $temp;
- }
+ if (($content = download($url)) && @file_put_contents($temp, $content, LOCK_EX) !== false) {
+ return $temp;
}
- return $f;
+ return false;
}
- static function validFile($file) {
- if (strpos($file, '..') !== false) {
+ /**
+ * @param string $file
+ *
+ * @return bool
+ */
+ public static function validFile(string $file): bool {
+ if (str_contains($file, '..')) {
return false;
}
- if (strpos($file, 'htaccess') !== false) {
+ if (str_contains($file, 'htaccess')) {
return false;
}
-
+
//for public folder don't allow php and htaccess files
- if (strpos($file, 'public') !== false) {
+ if (str_contains($file, 'public')) {
$extension = strtolower(substr($file, strrpos($file, '.') + 1));
if (in_array($extension, ['php', 'htaccess'])) {
return false;
}
}
-
-
+
return true;
}
-
- static function install($extensionZipFile, $slug = false, $validate = true) {
- $extension = static :: $extension;
+
+ /**
+ * @param string $extensionZipFile
+ * @param string|false $slug
+ * @param bool $validate
+ *
+ * @return string|bool
+ */
+ public static function install(string $extensionZipFile, string|false $slug = false, bool $validate = true): string|bool {
+ $extension = static::$extension;
$success = true;
- $extractTo = static :: $baseDir;
+ $extractTo = static::$baseDir;
$fileCheck = "$extension.php";
$valid = false;
$zip = new \ZipArchive();
if ($zip->open($extensionZipFile/*, \ZipArchive::OVERWRITE*/) === true) {
+ if ($zip->numFiles === 0) {
+ throw new \Exception(__('File is not a valid zip archive!'));
+ }
+
$info = false;
$folderName = $zip->getNameIndex(0);
//check if first entry is a directory
- if (substr($folderName, -1, 1) != '/') {
+ if (substr($folderName, -1, 1) !== '/') {
if ($validate) {
throw new \Exception(sprintf('%s zip must have only %s folder!', $extensionZipFile, ucfirst($extension)));
}
@@ -200,33 +254,31 @@ abstract class Extensions {
$slug = trim($folderName, '/');
}
- for ($i = $zip->numFiles - 1; ($i > 0 && $success == true); $i--) {
+ for ($i = $zip->numFiles - 1; ($i > 0 && $success === true); $i--) {
$file = $zip->getNameIndex($i);
- if (!self :: validFile($file)) {
+ if (!self::validFile($file)) {
throw new \Exception(sprintf(__('Zip contains invalid file "%s"'), $file));
}
-
+
if ($validate) {
//check if all files inside the extension folder
- if (strpos($file, $folderName) === false) {
+ if (!str_contains($file, $folderName)) {
$extractTo .= DS . $slug;
- if ($validate) {
- throw new \Exception(sprintf(__('%s zip should not have other files than %s folder!'), $extension, $extension));
- }
+ throw new \Exception(sprintf(__('%s zip should not have other files than %s folder!'), $extension, $extension));
}
}
// plugin.php must be in the top most folder
- if (strpos($file, $fileCheck) !== false && substr_count($file, '/') < 2) {
+ if (str_contains($file, $fileCheck) && substr_count($file, '/') < 2) {
$content = $zip->getFromName($file);
$info = static::getInfo($content);
if (isset($info['slug']) && ($folderName == ($info['slug'] . '/'))) {
// Unzip Path
$success = $info['slug'];
- $valid = true;
+ $valid = true;
} else {
if ($validate) {
throw new \Exception(sprintf(__('%s slug `%s` does not match folder %s!'), $extension, $info['slug'] ?? '', $folderName));
@@ -236,8 +288,6 @@ abstract class Extensions {
$success = $info['slug'];
}
}
-
- //break;
}
}
@@ -246,7 +296,7 @@ abstract class Extensions {
if (!is_writable($extractTo)) {
throw new \Exception(sprintf(__('%s folder not writable!'), str_replace(DIR_ROOT, '', $extractTo)));
}
-
+
if ($zip->extractTo($extractTo)) {
$success = $slug;
$info = ['slug' => $slug];
@@ -257,30 +307,40 @@ abstract class Extensions {
$zip->close();
- if (! $info) {
+ if (!$info) {
throw new \Exception(sprintf(__('No `%s.php` info found inside zip!'), $extension));
}
} else {
throw new \Exception(__('File is not a valid zip archive!'));
}
- Event :: trigger(__CLASS__, __FUNCTION__, $extensionZipFile, $success);
+ Event::trigger(__CLASS__, __FUNCTION__, $extensionZipFile, $success);
return $success;
}
- static function marketUrl() {
- return static :: $url;
+ /**
+ * @return ?string
+ */
+ public static function marketUrl(): ?string {
+ return static::$url;
}
- static function getMarketUrl($url, $params = [], $key = null) {
+ /**
+ * @param string $url
+ * @param array<array-key, mixed> $params
+ * @param ?string $key
+ *
+ * @return array<array-key, mixed>
+ */
+ public static function getMarketUrl(string $url, array $params = [], ?string $key = null): array {
$query = http_build_query($params);
$content = getUrl($url . '?' . $query);
if ($content) {
$rss = new Rss($content);
- $key = $key ?? static :: $extension . 's';
+ $key ??= static::$extension . 's';
$result[$key] = $rss->get($params['start'] ?? 1, $params['limit'] ?? 10);
$result['count'] = $rss->value('count');
@@ -290,11 +350,23 @@ abstract class Extensions {
return [];
}
- static function getMarketCategories($params = [], $key = null) {
- return static :: getMarketUrl(static :: $categoriesFeedUrl, $params, $key);
+ /**
+ * @param array<array-key, mixed> $params
+ * @param ?string $key
+ *
+ * @return array<array-key, mixed>
+ */
+ public static function getMarketCategories(array $params = [], ?string $key = null): array {
+ return static::getMarketUrl(static::$categoriesFeedUrl, $params, $key);
}
- static function getMarketList($params = [], $key = null) {
- return static :: getMarketUrl(static :: $feedUrl, $params, $key);
+ /**
+ * @param array<array-key, mixed> $params
+ * @param ?string $key
+ *
+ * @return array<array-key, mixed>
+ */
+ public static function getMarketList(array $params = [], ?string $key = null): array {
+ return static::getMarketUrl(static::$feedUrl, $params, $key);
}
}
diff --git a/system/extensions/plugins.php b/system/extensions/plugins.php
index f402368..da7d5ad 100755
--- a/system/extensions/plugins.php
+++ b/system/extensions/plugins.php
@@ -22,35 +22,79 @@
namespace Vvveb\System\Extensions;
-use \Vvveb\System\Cache;
use function Vvveb\rcopy;
use function Vvveb\rrmdir;
+use Vvveb\System\Cache;
use Vvveb\System\Event;
+use Vvveb\System\Notifications;
class Plugins extends Extensions {
- static protected $url = 'https://www.vvveb.com';
-
- static protected $feedUrl = 'https://plugins.vvveb.com/feed/plugins';
-
- static protected $categoriesFeedUrl = 'https://plugins.vvveb.com/feed/categories';
-
- static protected $extension = 'plugin';
-
- static protected $loaded = false;
-
- static protected $baseDir = DIR_PLUGINS;
-
- static protected $plugins = [];
-
- static protected $categories = [];
+ /**
+ * @var string
+ */
+ protected static string $url = 'https://www.vvveb.com';
+
+ /**
+ * @var string
+ */
+ protected static string $feedUrl = 'https://plugins.vvveb.com/feed/plugins';
+
+ /**
+ * @var string
+ */
+ protected static string $categoriesFeedUrl = 'https://plugins.vvveb.com/feed/categories';
+
+ /**
+ * @var string
+ */
+ protected static string $extension = 'plugin';
+
+ /**
+ * @var bool
+ */
+ protected static bool $loaded = false;
+
+ /**
+ * @var string
+ */
+ protected static string $baseDir = DIR_PLUGINS;
+
+ /**
+ * @var array<array-key, mixed>
+ */
+ protected static array $plugins = [];
+
+ /**
+ * @var array<array-key, mixed>
+ */
+ protected static array $categories = [];
+
+ /**
+ * @param string $pluginName
+ * @param int $site_id
+ *
+ * @return void
+ */
+ /**
+ * Validate a plugin name to prevent path traversal.
+ */
+ protected static function sanitizeName(string $pluginName): string {
+ return preg_replace('/[^a-zA-Z0-9_\\-]/', '', trim($pluginName, '/\\'));
+ }
- static function clearPluginsCache($site_id = SITE_ID) {
- $cacheDriver = Cache :: getInstance();
+ public static function clearPluginsCache(int $site_id = SITE_ID): void {
+ $cacheDriver = Cache::getInstance();
$cacheKey = "plugins_list_$site_id";
$cacheDriver->delete('vvveb', $cacheKey);
}
- static function getInfo($content, $name = false) {
+ /**
+ * @param string $content
+ * @param string|false $name
+ *
+ * @return array<array-key, mixed>
+ */
+ public static function getInfo(string $content, string|false $name = false): array {
$params = parent::getInfo($content, $name);
$params['status'] = 'inactive';
@@ -64,8 +108,14 @@ class Plugins extends Extensions {
return $params;
}
- static function loadPlugin($pluginName) {
- $file = DIR_PLUGINS . $pluginName . '/plugin.php';
+ /**
+ * @param string $pluginName
+ *
+ * @return mixed
+ */
+ public static function loadPlugin(string $pluginName): mixed {
+ $pluginName = self::sanitizeName($pluginName);
+ $file = DIR_PLUGINS . $pluginName . '/plugin.php';
if (file_exists($file)) {
return include $file;
@@ -74,9 +124,16 @@ class Plugins extends Extensions {
return false;
}
- static function activate($pluginName, $site_id = SITE_ID) {
- if (! $pluginName) {
- return;
+ /**
+ * @param string $pluginName
+ * @param int $site_id
+ *
+ * @return mixed
+ */
+ public static function activate(string $pluginName, int $site_id = SITE_ID): mixed {
+ $pluginName = self::sanitizeName($pluginName);
+ if (!$pluginName) {
+ return null;
}
$file = DIR_PLUGINS . $pluginName . '/plugin.php';
@@ -85,16 +142,20 @@ class Plugins extends Extensions {
$key = "plugins.$site_id.$pluginName.status";
$status = \Vvveb\getConfig($key);
- if (! $status) {
+ if (!$status) {
//if no plugin info then this is first activation, run plugin setup
- Event :: trigger(__CLASS__, 'setup', $pluginName, $site_id);
+ Event::trigger(__CLASS__, 'setup', $pluginName, $site_id);
}
$return = \Vvveb\setConfig($key, 'active');
- Event :: trigger(__CLASS__, __FUNCTION__, $pluginName, $site_id);
+ Event::trigger(__CLASS__, __FUNCTION__, $pluginName, $site_id);
+
+ if ($return) {
+ Notifications::trigger('plugin.activate', ['subject' => sprintf('Plugin activated: %s', $pluginName), 'message' => sprintf('Plugin "%s" was activated.', $pluginName), 'plugin' => $pluginName]);
+ }
- self :: clearPluginsCache($site_id);
- self :: copyPublicDir($pluginName);
+ self::clearPluginsCache($site_id);
+ self::copyPublicDir($pluginName);
return $return;
}
@@ -102,58 +163,87 @@ class Plugins extends Extensions {
return false;
}
- static function deactivate($pluginName, $site_id = SITE_ID) {
- if (! $pluginName) {
- return;
+ /**
+ * @param string $pluginName
+ * @param int $site_id
+ *
+ * @return mixed
+ */
+ public static function deactivate(string $pluginName, int $site_id = SITE_ID): mixed {
+ $pluginName = self::sanitizeName($pluginName);
+ if (!$pluginName) {
+ return null;
}
$key = "plugins.$site_id.$pluginName.status";
$return = \Vvveb\setConfig($key, 'inactive');
- /*
- $key = "plugins.$site_id.$pluginName";
- $return = \Vvveb\unsetConfig($key, []);
- */
- Event :: trigger(__CLASS__, __FUNCTION__, $pluginName, $site_id);
+ Event::trigger(__CLASS__, __FUNCTION__, $pluginName, $site_id);
+
+ if ($return) {
+ Notifications::trigger('plugin.deactivate', ['subject' => sprintf('Plugin deactivated: %s', $pluginName), 'message' => sprintf('Plugin "%s" was deactivated.', $pluginName), 'plugin' => $pluginName]);
+ }
- self :: clearPluginsCache($site_id);
+ self::clearPluginsCache($site_id);
return $return;
}
//copy plugin public folder to public/plugins folder
- static function copyPublicDir($pluginName) {
- if ($pluginName) {
- $publicSrc = DIR_PLUGINS . "$pluginName/public";
- $publicDest = DIR_PUBLIC . "plugins/$pluginName";
- if (is_link($publicDest)) {
- return true;
- }
+ /**
+ * @param string $pluginName
+ *
+ * @return bool
+ */
+ public static function copyPublicDir(string $pluginName): bool {
+ if (!$pluginName) {
+ return false;
+ }
- if (! file_exists($publicDest)) {
- //try symlink first
- if (function_exists('symlink') && \symlink($publicSrc, $publicDest)) {
- return true;
- } else {
- return rcopy($publicSrc, $publicDest);
- }
- } else {
- return rcopy($publicSrc, $publicDest);
- }
+ $publicSrc = DIR_PLUGINS . "$pluginName/public";
+ $publicDest = DIR_PUBLIC . "plugins/$pluginName";
+
+ if (is_link($publicDest)) {
+ return true;
}
+
+ if (!file_exists($publicDest) && function_exists('symlink') && \symlink($publicSrc, $publicDest)) {
+ //try symlink first
+ return true;
+ }
+
+ return rcopy($publicSrc, $publicDest);
}
- static function install($zipFile, $slug = false, $validate = true) {
- if ($pluginName = parent :: install($zipFile, $validate)) {
- if (self :: copyPublicDir($pluginName)) {
- self :: clearPluginsCache();
+ /**
+ * @param string $zipFile
+ * @param string|false $slug
+ * @param bool $validate
+ *
+ * @return string|bool
+ */
+ public static function install(string $zipFile, string|false $slug = false, bool $validate = true): string|bool {
+ if ($pluginName = parent::install($zipFile, $slug, $validate)) {
+ if (self::copyPublicDir($pluginName)) {
+ self::clearPluginsCache();
+
+ Notifications::trigger('plugin.add', ['subject' => sprintf('Plugin installed: %s', $pluginName), 'message' => sprintf('Plugin "%s" was installed.', $pluginName), 'plugin' => $pluginName]);
return $pluginName;
}
}
+
+ return false;
}
- static function uninstall($pluginName, $site_id = SITE_ID) {
- $success = false;
+ /**
+ * @param string $pluginName
+ * @param int $site_id
+ *
+ * @return bool
+ */
+ public static function uninstall(string $pluginName, int $site_id = SITE_ID): bool {
+ $pluginName = self::sanitizeName($pluginName);
+ $success = false;
//remove public folder from public/plugins/$pluginName
$pluginDir = DIR_PLUGINS . "$pluginName";
$publicDir = DIR_PUBLIC . "plugins/$pluginName";
@@ -171,22 +261,33 @@ class Plugins extends Extensions {
$success = rrmdir($pluginDir);
$key = "plugins.$site_id.$pluginName";
- \Vvveb\unsetConfig($key, []);
- self :: clearPluginsCache($site_id);
+ \Vvveb\unsetConfig($key);
+ self::clearPluginsCache($site_id);
+
+ Event::trigger(__CLASS__, __FUNCTION__, $pluginName, $success);
- Event :: trigger(__CLASS__, __FUNCTION__, $pluginName, $success);
+ if ($success) {
+ Notifications::trigger('plugin.delete', ['subject' => sprintf('Plugin uninstalled: %s', $pluginName), 'message' => sprintf('Plugin "%s" was uninstalled.', $pluginName), 'plugin' => $pluginName]);
+ }
return $success;
}
- static function getList($site_id = SITE_ID, $category = false, $cache = true) {
- $cacheDriver = Cache :: getInstance();
+ /**
+ * @param int $site_id
+ * @param string|false $category
+ * @param bool $cache
+ *
+ * @return array<array-key, mixed>
+ */
+ public static function getList(int $site_id = SITE_ID, string|false $category = false, bool $cache = true): array {
+ $cacheDriver = Cache::getInstance();
$cacheKey = "plugins_list_$site_id";
- if (! $category && $cache && $result = $cacheDriver->get('vvveb', $cacheKey)) {
+ if (!$category && $cache && $result = $cacheDriver->get('vvveb', $cacheKey)) {
return $result;
} else {
- $pluginList = parent :: getListInfo(DIR_PLUGINS . '/*/plugin.php');
+ $pluginList = parent::getListInfo(DIR_PLUGINS . '/*/plugin.php');
$pluginConfig = [];
if ($site_id) {
@@ -198,47 +299,57 @@ class Plugins extends Extensions {
}
//set default name to show the plugin as broken if is missing
- array_walk($pluginList, function (&$val, $key) use (&$pluginList, $category) {
- if (! isset($val['name'])) {
- $val['slug'] = $key;
- $val['name'] = sprintf('[%s]', $key);
+ array_walk($pluginList, function(&$val, $key) use (&$pluginList, $category): void {
+ if (!isset($val['name'])) {
+ $val['slug'] = $key;
+ $val['name'] = sprintf('[%s]', $key);
$val['status'] = 'broken';
}
- if ($category && (! isset($val['category']) || ($val['category'] != $category))) {
+ if ($category && (!isset($val['category']) || ($val['category'] !== $category))) {
unset($pluginList[$key]);
}
});
- if (! $category && $cache) {
+ if (!$category && $cache) {
$cacheDriver->set('vvveb', $cacheKey, $pluginList);
- $cacheDriver->set('vvveb', "{$cacheKey}_categories", static :: $categories);
+ $cacheDriver->set('vvveb', "{$cacheKey}_categories", static::$categories);
}
return $pluginList;
}
}
- static function getCategories($site_id = SITE_ID) {
- if (! static :: $categories) {
- $cacheDriver = Cache :: getInstance();
+ /**
+ * @param int $site_id
+ *
+ * @return array<array-key, mixed>
+ */
+ public static function getCategories(int $site_id = SITE_ID): array {
+ if (!static::$categories) {
+ $cacheDriver = Cache::getInstance();
$cacheKey = "plugins_list_{$site_id}_categories";
- static :: $categories = $cacheDriver->get('vvveb', $cacheKey);
+ static::$categories = $cacheDriver->get('vvveb', $cacheKey) ?? [];
}
- return static :: $categories;
+ return static::$categories;
}
- static function loadPlugins($site_id = SITE_ID) {
- if (static :: $loaded) {
+ /**
+ * @param int $site_id
+ *
+ * @return void
+ */
+ public static function loadPlugins(int $site_id = SITE_ID): void {
+ if (static::$loaded) {
return;
}
- static :: $loaded = true;
+ static::$loaded = true;
$plugins = static::getList($site_id);
foreach ($plugins as $name => $plugin) {
- if ((isset($plugin['status']) && $plugin['status'] == 'active')
+ if ((isset($plugin['status']) && $plugin['status'] === 'active')
&& file_exists($plugin['file'])) {
include $plugin['file'];
}
diff --git a/system/extensions/themes.php b/system/extensions/themes.php
index 60e08c2..a1c47a7 100755
--- a/system/extensions/themes.php
+++ b/system/extensions/themes.php
@@ -22,48 +22,74 @@
namespace Vvveb\System\Extensions;
-use \Vvveb\System\Cache;
-use \Vvveb\System\Event;
-use \Vvveb\System\Sites;
use function Vvveb\__;
use function Vvveb\getDefaultTemplateList;
use function Vvveb\slugify;
+use Vvveb\System\Cache;
+use Vvveb\System\Event;
use Vvveb\System\Functions\Str;
+use Vvveb\System\Notifications;
+use Vvveb\System\Sites;
class Themes extends Extensions {
- static protected $extension = 'theme';
+ /** @var string */
+ protected static string $extension = 'theme';
- static protected $baseDir = DIR_THEMES;
+ /** @var string */
+ protected static string $baseDir = DIR_THEMES;
- static protected $url = 'https://themes.vvveb.com';
+ /** @var string */
+ protected static string $url = 'https://themes.vvveb.com';
- static protected $feedUrl = 'https://themes.vvveb.com/feed/themes';
+ /** @var string */
+ protected static string $feedUrl = 'https://themes.vvveb.com/feed/themes';
- static protected $categoriesFeedUrl = 'https://themes.vvveb.com/feed/categories';
+ /** @var string */
+ protected static string $categoriesFeedUrl = 'https://themes.vvveb.com/feed/categories';
- static protected $themes = [];
+ /** @var array<array-key, mixed> */
+ protected static array $themes = [];
- static protected $imageExtensions = ['png', 'jpg', 'webp', 'jpeg'];
+ /** @var array<array-key, mixed> */
+ protected static array $imageExtensions = ['png', 'jpg', 'webp', 'jpeg'];
- static protected $categories = [];
+ /** @var array<array-key, mixed> */
+ protected static array $categories = [];
- static function getInfo($content, $name = false) {
+ /**
+ * @param string $content
+ * @param string|false $name
+ *
+ * @return array<array-key, mixed>
+ */
+ public static function getInfo(string $content, string|false $name = false): array {
$params = parent::getInfo($content, $name);
$params['screenshot'] = PUBLIC_PATH . 'themes/' . $name . '/screenshot.png';
return $params;
}
- static function clearThemesCache($site_id = SITE_ID) {
- $cacheDriver = Cache :: getInstance();
+ /**
+ * @param int $site_id
+ *
+ * @return void
+ */
+ public static function clearThemesCache(int $site_id = SITE_ID): void {
+ $cacheDriver = Cache::getInstance();
$cacheKey = "themes_list_$site_id";
$cacheDriver->delete('vvveb', $cacheKey);
}
- static function getList($site_id = false, $cache = true) {
- $cacheDriver = Cache :: getInstance();
+ /**
+ * @param int|false $site_id
+ * @param bool $cache
+ *
+ * @return array<array-key, mixed>
+ */
+ public static function getList(int|false $site_id = false, bool $cache = true): array {
+ $cacheDriver = Cache::getInstance();
$cacheKey = "themes_list_$site_id";
- $activeTheme = Sites::getTheme($site_id) ?? 'default';
+ $activeTheme = Sites::getTheme($site_id);
if ($cache && $themes = $cacheDriver->get('vvveb', $cacheKey)) {
} else {
@@ -74,9 +100,9 @@ class Themes extends Extensions {
foreach ($list as $file) {
$folder = Str::match('@/([^/]+)/[a-z]+.\w+$@', $file);
$dir = Str::match('@(.+)/[a-z]+.\w+$@', $file);
- $themeConfig = $dir . DS . 'theme.php';
+ $themeConfig = $dir . DS . 'theme.json';
- if ($folder == 'default') {
+ if ($folder === 'default') {
continue;
}
$theme = [];
@@ -92,15 +118,14 @@ class Themes extends Extensions {
$theme['import'] = file_exists($dir . DS . 'import');
}
- $theme['name'] = $theme['name'] ?? ucfirst($theme['folder']);
+ $theme['name'] ??= ucfirst($theme['folder']);
$theme['screenshot'] = $theme['screenshot'] ?? (file_exists($dir . DS . 'screenshot.png') ? PUBLIC_PATH . 'themes/' . $folder . '/screenshot.png' : null);
- if (! isset($theme['screenshot'])) {
+ if (!isset($theme['screenshot'])) {
$theme['screenshot'] = PUBLIC_PATH . 'media/extension.svg';
if ($h = opendir($dir)) {
while (($file = readdir($h)) !== false) {
- $extension = strtolower(substr($file, strrpos($file, '.') + 1));
- if (in_array($extension, self :: $imageExtensions)) {
+ if (in_array(strtolower(pathinfo($file, PATHINFO_EXTENSION)), self::$imageExtensions, true)) {
$theme['screenshot'] = PUBLIC_PATH . 'themes/' . $folder . '/' . $file;
break;
}
@@ -119,11 +144,11 @@ class Themes extends Extensions {
$cacheDriver->set('vvveb', $cacheKey, $themes);
}
- static :: $extensions[static :: $extension] = $themes;
+ static::$extensions[static::$extension] = $themes;
}
if (isset($themes[$activeTheme])) {
- $theme = $themes[$activeTheme];
+ $theme = $themes[$activeTheme];
$theme['active'] = true;
unset($themes[$activeTheme]);
$themes = [$activeTheme => $theme] + $themes;
@@ -132,10 +157,14 @@ class Themes extends Extensions {
return $themes;
}
- /*
- * Add missing templates by copying from available template
- */
- static function fixIfMissingTemplates($slug) {
+ // Add missing templates by copying from available template
+
+ /**
+ * @param string $slug
+ *
+ * @return void
+ */
+ public static function fixIfMissingTemplates(string $slug): void {
//check templates in order
$defaultTemplate = '';
@@ -153,11 +182,11 @@ class Themes extends Extensions {
foreach ($templates as $template) {
$file = DIR_THEMES . $slug . DS . $template;
- if (! file_exists($file)) {
- $dir = dirname($template);
+ if (!file_exists($file)) {
+ $dir = DIR_THEMES . $slug . DS . dirname($template);
- if ($dir && ! file_exists($dir)) {
- @mkdir(DIR_THEMES . $slug . DS . $dir);
+ if (!is_dir($dir)) {
+ @mkdir($dir, 0777, true);
}
@copy(DIR_THEMES . $slug . DS . $defaultTemplate, $file);
@@ -168,7 +197,7 @@ class Themes extends Extensions {
//create missing folders
foreach (['backup', 'css'] as $folder) {
$dir = DIR_THEMES . $slug . DS . $folder;
- if (! is_dir($dir)) {
+ if (!is_dir($dir)) {
@mkdir($dir);
}
}
@@ -176,34 +205,25 @@ class Themes extends Extensions {
//create missing files
foreach (['css' . DS . 'custom.css', 'css' . DS . 'fonts.css'] as $file) {
$path = DIR_THEMES . $slug . DS . $file;
- if (! file_exists($path)) {
+ if (!file_exists($path)) {
@touch($path);
}
}
}
- static function validFile($file) {
- if (strpos($file, '..') !== false) {
- return false;
- }
-
- if (strpos($file, 'htaccess') !== false) {
- return false;
- }
-
- $extension = strtolower(substr($file, strrpos($file, '.') + 1));
- if ($extension == 'php' && strpos($file, '/theme.php') === false) {
- return false;
- }
-
- return true;
- }
-
- static function install($extensionZipFile, $slug = false, $validate = false) {
- $success = true;
- $extractTo = static :: $baseDir;
- $fileCheck = 'index.html';
- $folder = false;
+ /**
+ * @param string $extensionZipFile
+ * @param string|false $slug
+ * @param bool $validate
+ *
+ * @return string|bool
+ */
+ public static function install(string $extensionZipFile, string|false $slug = false, bool $validate = false): string|bool {
+ $success = true;
+ $extractTo = static::$baseDir;
+ $fileCheck = 'index.html';
+ $folder = false;
+ $invalidFiles = [];
$zip = new \ZipArchive();
@@ -212,27 +232,33 @@ class Themes extends Extensions {
for ($i = 0; (($i < $zip->numFiles) && $success == true); $i++) {
$file = $zip->getNameIndex($i);
- if (!self :: validFile($file)) {
- throw new \Exception(sprintf(__('Zip contains invalid file "%s"'), $file));
+ if (!self::validFile($file)) {
+ $invalidFiles[] = $file;
}
- if (strpos($file, $fileCheck) !== false) {
- if (! $folder || (strlen($file) < strlen($folder))) {
+ if (str_contains($file, $fileCheck)) {
+ if (!$folder || (strlen($file) < strlen($folder))) {
$folder = $file;
}
}
}
if ($folder) {
- if ($folder == 'index.html') {
+ if ($folder === 'index.html') {
$extractTo .= $slug;
}
$extractTo = preg_replace('@[\\\/]([^\\\/]+?)\.\w+$@', '', $extractTo);
if ($zip->extractTo($extractTo)) {
+ if ($invalidFiles) {
+ foreach ($invalidFiles as $file) {
+ unlink($extractTo . DS . $file);
+ }
+ }
+
if ($folder !== 'index.html') {
$folder = preg_replace('@[\\\/]([^\\\/]+?)\.\w+$@', '', $folder);
- $slug = slugify($folder);
+ $slug = slugify($folder);
rename($extractTo . $folder, $extractTo . $slug);
}
@@ -248,7 +274,11 @@ class Themes extends Extensions {
throw new \Exception(__('File is not a valid zip archive!'));
}
- Event :: trigger(__CLASS__, __FUNCTION__, $extensionZipFile, $slug, $success);
+ Event::trigger(__CLASS__, __FUNCTION__, $extensionZipFile, $slug, $success);
+
+ if ($success) {
+ Notifications::trigger('theme.add', ['subject' => sprintf('Theme installed: %s', $slug ?: $extensionZipFile), 'message' => sprintf('Theme "%s" was installed.', $slug ?: $extensionZipFile), 'theme' => $slug ?: $extensionZipFile]);
+ }
return $success;
}
diff --git a/system/images.php b/system/images.php
old mode 100755
new mode 100644
index 421be78..2167e11
--- a/system/images.php
+++ b/system/images.php
@@ -20,43 +20,60 @@
*
*/
-/**
- * Manages image retrival and saving.
- *
- * @package Vvveb
- * @subpackage System
- * @since 0.0.1
- */
-
namespace Vvveb\System;
use function Vvveb\siteSettings;
use Vvveb\System\Media\Image;
class Images {
- static public function resize($src, $dest, $width, $height, $method, $quality = 80, $format = '') {
+ /**
+ * Resize an image and save it to the destination path.
+ *
+ * @param string $src Source image path.
+ * @param string $dest Destination image path.
+ * @param int $width Target width.
+ * @param int $height Target height.
+ * @param string $method Resize method (e.g. 'cs' for crop-scale).
+ * @param int $quality JPEG quality (0-100).
+ * @param string $format Output format (e.g. 'webp', '' for auto).
+ *
+ * @return bool True on success, false on failure.
+ */
+ public static function resize(string $src, string $dest, int $width, int $height, string $method, int $quality = 80, string $format = ''): bool {
$destDir = dirname($dest);
- if (! file_exists($destDir)) {
+ if (!file_exists($destDir)) {
@mkdir(dirname($dest), (0755 & ~umask()), true);
}
$img = new Image($src);
- $result = $img->resize($width,$height, $method);
+ $result = $img->resize($width, $height, $method);
return $img->save($dest, $quality, $format);
}
- static public function image($image, $type = '', $size = '', $method = 'cs', $format = '', $quality = 80) {
+ /**
+ * Get the URL for an image, resizing and caching as needed.
+ *
+ * @param string $image Image path relative to media folder.
+ * @param string $type Image type context (e.g. 'product', 'blog').
+ * @param string|array<array-key, mixed> $size Size name from site settings or [width, height] array.
+ * @param string $method Resize method.
+ * @param string $format Output format override.
+ * @param int $quality JPEG quality.
+ *
+ * @return string The resolved image URL.
+ */
+ public static function image(string $image, string $type = '', string|array $size = '', string $method = 'cs', string $format = '', int $quality = 80): string {
$publicPath = \Vvveb\publicUrlPath();
- list($publicPath, $type, $image, $size) =
+ [$publicPath, $type, $image, $size] =
Event :: trigger(__CLASS__, 'publicPath', $publicPath, $type, $image, $size);
if ($publicPath == null) {
$publicPath = \Vvveb\publicUrlPath();
//if absolute path include subdir
- if ($image[0] == '/') {
- $publicPath = (V_SUBDIR_INSTALL ? V_SUBDIR_INSTALL : '') . $publicPath;
+ if ($image !== '' && $image[0] == '/') {
+ $publicPath = V_SUBDIR_INSTALL . $publicPath;
}
}
@@ -67,6 +84,9 @@ class Images {
$src = $image;
if ($size) {
+ $width = 0;
+ $height = 0;
+
if (is_array($size)) {
$width = $size[0];
$height = $size[1];
@@ -79,7 +99,7 @@ class Images {
$quality = $site['image_quality'] ?? 80;
}
- $image = self::size($image,"{$width}x{$height}_$method");
+ $image = self::size($image, "{$width}x{$height}_$method");
if ($format) {
$image = self::extension($image, $format);
@@ -105,13 +125,21 @@ class Images {
//return $public . 'media/placeholder.png';
}
- list($image, $type, $size) =
- Event :: trigger(__CLASS__,__FUNCTION__, $image, $type, $size);
+ [$image, $type, $size] =
+ Event :: trigger(__CLASS__, __FUNCTION__, $image, $type, $size);
return $image;
}
- static public function size($image, $size) {
+ /**
+ * Append a size suffix to an image filename before the extension.
+ *
+ * @param string $image Image filename.
+ * @param string $size Size suffix (e.g. '300x200_cs').
+ *
+ * @return string Image filename with size suffix.
+ */
+ public static function size(string $image, string $size): string {
$pos = strrpos($image, '.');
if ($pos) {
@@ -121,37 +149,62 @@ class Images {
return $image;
}
- static public function extension($image, $extension) {
- $dot = strrpos($image , '.');
+ /**
+ * Replace the file extension of an image filename.
+ *
+ * @param string $image Image filename.
+ * @param string $extension New extension (e.g. 'webp').
+ *
+ * @return string Image filename with new extension.
+ */
+ public static function extension(string $image, string $extension): string {
+ $dot = strrpos($image, '.');
if ($dot) {
- return substr_replace($image , $extension, $dot + 1);
+ return substr_replace($image, $extension, $dot + 1);
}
return $image;
}
- static public function images($images, $type, $size = '', $method = 'cs') {
+ /**
+ * Process an array of images, resolving each image URL.
+ *
+ * @param array<int, array{image: string}> $images Array of image data with 'image' key.
+ * @param string $type Image type context.
+ * @param string $size Size name or dimensions.
+ * @param string $method Resize method.
+ *
+ * @return array<int, array{image: string}> The processed images array<array-key, mixed>.
+ */
+ public static function images(array $images, string $type, string $size = '', string $method = 'cs'): array {
foreach ($images as $key => &$image) {
- $image['image'] = Images::image($image['image'], $type, $size);
+ $image['image'] = self::image($image['image'], $type, $size);
}
- /*
- uasort($images, function ($a, $b) {
- if ($a['sort_order'] == $b['sort_order']) {
- return 0;
- }
-
- return ($a['sort_order'] < $b['sort_order']) ? -1 : 1;
- });
- */
-
return $images;
}
- public function get($type, $id, $size, $attrs) {
- }
-
- public function save($type, $path, $attrs) {
- }
+ /**
+ * Get an image by type, id, size and attributes.
+ *
+ * @param string $type Image type.
+ * @param int|string $id Image identifier.
+ * @param string|array<array-key, mixed> $size Size specification.
+ * @param array<string, mixed> $attrs Additional attributes.
+ *
+ * @return void
+ */
+ public function get(string $type, int|string $id, string|array $size, array $attrs): void {}
+
+ /**
+ * Save an image to the given path.
+ *
+ * @param string $type Image type.
+ * @param string $path File path to save to.
+ * @param array<string, mixed> $attrs Additional attributes.
+ *
+ * @return void
+ */
+ public function save(string $type, string $path, array $attrs): void {}
}
diff --git a/system/import/rss.php b/system/import/rss.php
index 2b616b1..0230018 100755
--- a/system/import/rss.php
+++ b/system/import/rss.php
@@ -24,13 +24,25 @@ namespace Vvveb\System\Import;
#[\AllowDynamicProperties]
class Rss {
- private $dom;
-
- private $xpath;
-
- private $rss;
-
- private $importXMLOptions = LIBXML_NOBLANKS |
+ /**
+ * @var \DOMDocument
+ */
+ private \DOMDocument $dom;
+
+ /**
+ * @var \DOMXPath
+ */
+ private \DOMXPath $xpath;
+
+ /**
+ * @var string
+ */
+ private string $rss;
+
+ /**
+ * @var int
+ */
+ private int $importXMLOptions = LIBXML_NOBLANKS |
LIBXML_COMPACT |
LIBXML_NOCDATA |
LIBXML_PARSEHUGE |
@@ -39,7 +51,12 @@ class Rss {
// |
//LIBXML_BIGLINES;
- function __construct($rss) {
+ /**
+ * @param string $rss
+ *
+ * @return void
+ */
+ public function __construct(string $rss) {
$this->rss = $rss;
$this->dom = new \DOMDocument('1.0', 'utf-8');
$this->dom->formatOutput = false;
@@ -47,10 +64,15 @@ class Rss {
$this->dom->loadXML($this->rss, $this->importXMLOptions);
$this->dom->normalize();
- $this->xpath = new \DOMXpath($this->dom);
+ $this->xpath = new \DOMXPath($this->dom);
}
- function buildXPath($attributes = []) {
+ /**
+ * @param array<array-key, mixed> $attributes
+ *
+ * @return string
+ */
+ public function buildXPath(array $attributes = []): string {
$list = '';
foreach ($attributes as $attribute) {
@@ -65,43 +87,65 @@ class Rss {
$list .= "[$name $operator '$value']";
}
- $xpath = "//channel/item$list";
-
- return $xpath;
+ return "//channel/item$list";
}
- function value($nodeName) {
+ /**
+ * @param string $nodeName
+ *
+ * @return string|false
+ */
+ public function value(string $nodeName): string|false {
$xpath = "//channel/$nodeName";
$item = $this->xpath->query($xpath);
if ($item && isset($item[0])) {
return $item[0]->nodeValue ?? false;
}
+
+ return false;
}
- function count($attributes = []) {
+ /**
+ * @param array<array-key, mixed> $attributes
+ *
+ * @return int
+ */
+ public function count(array $attributes = []): int {
$items = $this->xpath->query($this->buildXPath($attributes));
- return $items->length ?? 0;
+ return $items ? $items->length : 0;
}
- function get($start = 1, $limit = 10, $attributes = []) {
+ /**
+ * @param int $start
+ * @param int $limit
+ * @param array<array-key, mixed> $attributes
+ *
+ * @return array<array-key, mixed>
+ */
+ public function get(int $start = 1, int $limit = 10, array $attributes = []): array {
if ($start) {
- $attributes[] = ['position()'=> [$start, '>=']];
+ $attributes[] = ['position()' => [$start, '>=']];
}
if ($limit) {
- $attributes[] = ['position()'=> [$limit, '<=']];
+ $attributes[] = ['position()' => [$limit, '<=']];
}
$items = $this->xpath->query($this->buildXPath($attributes));
$rows = [];
+ if (!$items) {
+ return $rows;
+ }
+
foreach ($items as $item) {
$columns = $item->childNodes;
+ $row = [];
foreach ($columns as $column) {
- if ($column->nodeName == '#text') {
+ if ($column->nodeName === '#text') {
continue;
}
$columnName = $column->nodeName;
diff --git a/system/import/table-order.php b/system/import/table-order.php
old mode 100644
new mode 100755
index bb92731..a64e0cd
--- a/system/import/table-order.php
+++ b/system/import/table-order.php
@@ -78,6 +78,19 @@ return [
'attribute_group',
'attribute_group_content',
+ //fields
+ 'field_group_content',
+ 'field_content',
+ 'field_value_content',
+ 'field_group',
+ 'taxonomy_item_field_value',
+ 'user_field_value',
+ 'order_field_value',
+ 'field_value',
+ 'post_field_value',
+ 'product_field_value',
+ 'field',
+
//product related
'vendor',
'manufacturer',
@@ -146,7 +159,7 @@ return [
'return_reason',
'return_status',
'review',
- 'shipping_courier',
+ 'shipping_status',
'stock_status',
'tax_type',
'tax_rate',
diff --git a/system/import/xml.php b/system/import/xml.php
index 9b7fe74..7ede9a0 100755
--- a/system/import/xml.php
+++ b/system/import/xml.php
@@ -24,48 +24,76 @@ namespace Vvveb\System\Import;
#[\AllowDynamicProperties]
class Xml {
- private $db;
-
- private $dom;
-
- private $xpath;
+ /**
+ * @var mixed Database driver object
+ */
+ private mixed $db;
- private $sqlPath;
+ /**
+ * @var \DOMDocument
+ */
+ private \DOMDocument $dom;
- private $prefix;
+ /**
+ * @var \DOMXPath
+ */
+ private \DOMXPath $xpath;
- private $idsMap;
+ /**
+ * @var array<array-key, mixed>
+ */
+ private array $idsMap;
- private $importXMLOptions = LIBXML_NOBLANKS |
+ /**
+ * @var int
+ */
+ private int $importXMLOptions = LIBXML_NOBLANKS |
LIBXML_COMPACT |
LIBXML_NOCDATA |
LIBXML_PARSEHUGE |
LIBXML_NOWARNING |
LIBXML_BIGLINES;
- private $tableOrder = [];
+ /**
+ * @var array<array-key, mixed>
+ */
+ private array $tableOrder = [];
- private $cDataColumns = ['content', 'excerpt', 'name', 'title', 'description', 'meta_title', 'meta_description', 'slug'];
+ /**
+ * @var array<array-key, mixed>
+ */
+ private array $cDataColumns = ['content', 'excerpt', 'name', 'title', 'description', 'meta_title', 'meta_description', 'slug'];
- function __construct($driver = DB_ENGINE, $host = DB_HOST, $dbname = DB_NAME, $user = DB_USER, $pass = DB_PASS, $port = DB_PORT, $prefix = DB_PREFIX) {
- $this->sqlPath = DIR_ROOT . "install/sql/$driver/";
+ /**
+ * @param string $driver
+ *
+ * @return void
+ */
+ public function __construct(string $driver = DB_ENGINE) {
$engine = '\Vvveb\System\Db\\' . ucfirst($driver);
- $this->prefix = $prefix;
-
- $this->db = new $engine($host, $dbname, $user, $pass, $port, $prefix);
+ $this->db = new $engine();
$this->tableOrder = include 'table-order.php';
}
- /*
- * Get all table names for the database
+ /**
+ * Get all table names for the database.
+ *
+ * @param string $db
+ *
+ * @return array<array-key, mixed>
*/
- function getTableNames($db = DB_NAME) {
+ public function getTableNames(string $db = DB_NAME): array {
return $this->db->getTableNames();
}
- function export($tables = []) {
+ /**
+ * @param array<array-key, mixed> $tables
+ *
+ * @return string
+ */
+ public function export(array $tables = []): string {
$this->dom = new \DOMDocument('1.0', 'utf-8');
$this->dom->formatOutput = true;
$this->dom->preserveWhiteSpace = false;
@@ -79,14 +107,9 @@ class Xml {
foreach ($tables as $tableName) {
$table = $this->dom->createElement($tableName);
- $q = '`';
-
- if (DB_ENGINE == 'pgsql') {
- $q = '"';
- }
+ $q = $this->db->quote;
$stmt = $this->db->query("SELECT * FROM $q$tableName$q");
- //$result = $stmt->get_result();
while ($row = $this->db->fetchArray($stmt)) {
$item = $this->dom->createElement('item');
@@ -94,7 +117,7 @@ class Xml {
foreach ($row as $key => $value) {
$isString = is_string($value);
- if ($value === NULL) {
+ if ($value === null) {
$value = 'NULL';
}
@@ -102,11 +125,11 @@ class Xml {
$value = '0';
}
- if (! $value) {
+ if (!$value && $value !== '0') {
$value = '';
}
- if (in_array($key,$this->cDataColumns) || $isString) {
+ if (in_array($key, $this->cDataColumns) || $isString) {
//$element = $this->dom->createElement($key, $value);
$cdata = $this->dom->createCDataSection($value);
@@ -132,8 +155,14 @@ class Xml {
return $this->dom->saveXML();
}
- function display_xml_error($error, $xml) {
- $return = $xml[$error->line - 1] . "\n";
+ /**
+ * @param \LibXMLError $error
+ * @param array<array-key, mixed> $xml
+ *
+ * @return string
+ */
+ public function displayXmlError(\LibXMLError $error, array $xml): string {
+ $return = ($xml[$error->line - 1] ?? '') . "\n";
$return .= str_repeat('-', $error->column) . "^\n";
switch ($error->level) {
@@ -164,13 +193,17 @@ class Xml {
return "$return\n\n--------------------------------------------\n\n";
}
- function import($xml, $tables = []) {
+ /**
+ * @param string $xml
+ * @param array<array-key, mixed> $tables
+ *
+ * @return bool
+ */
+ public function import(string $xml, array $tables = []): bool {
if ($tables) {
- //sort tables by table order
+ //sort tables by table order, unknown tables go last
$tableOrder = array_flip($this->tableOrder);
- usort($tables, function ($left, $right) use ($tableOrder) {
- return $tableOrder[$left] <=> $tableOrder[$right];
- });
+ usort($tables, fn ($left, $right) => ($tableOrder[$left] ?? PHP_INT_MAX) <=> ($tableOrder[$right] ?? PHP_INT_MAX));
} else {
$tables = $this->tableOrder;
}
@@ -182,32 +215,34 @@ class Xml {
libxml_use_internal_errors(true);
$result = $this->dom->loadXML($xml, $this->importXMLOptions);
- if (! $result) {
- $error = libxml_get_last_error();
- $message = $this->display_xml_error($error, explode("\n", $xml));
+ if (!$result) {
+ $error = libxml_get_last_error();
- throw new \Exception(sprintf("Unable to load XML content, check if valid XML!\n\t%s", $message), 1);
+ if ($error === false) {
+ throw new \Exception('Unable to load XML content, check if valid XML!', 1);
+ }
+
+ $message = $this->displayXmlError($error, explode("\n", $xml));
- return;
+ throw new \Exception(sprintf("Unable to load XML content, check if valid XML!\n\t%s", $message), 1);
}
$this->dom->normalize();
- $this->xpath = new \DOMXpath($this->dom);
+ $this->xpath = new \DOMXPath($this->dom);
$domTables = $this->xpath->query('//root/database/*');
//map ids
foreach ($domTables as $table) {
$tableName = $table->nodeName;
- //continue;
- $rows = $table->childNodes;
+ $rows = $table->childNodes;
- if (! is_null($rows)) {
+ if ($rows->length) {
foreach ($rows as $row) {
$columns = $row->childNodes;
- if ($columns) {
+ if ($columns->length) {
foreach ($columns as $column) {
//if ($column->nodeName == '#text') continue;
$columnName = $column->nodeName;
@@ -217,7 +252,6 @@ class Xml {
$idColumn = $tableName . '_id';
if ($columnName == $idColumn) {
- //$this->idsMap[$idColumn][$columnValue] = 0;
$this->idsMap[$idColumn][$columnValue] = $columnValue;
}
}
@@ -230,32 +264,28 @@ class Xml {
$stmt = $this->db->execute('SET sql_mode = "";');
}
- $q = '`';
-
- if (DB_ENGINE == 'pgsql') {
- $q = '"';
- }
+ $q = $this->db->quote;
foreach ($tables as $tableName) {
$rows = $this->xpath->query("//root/database/$tableName/item");
- if (! is_null($rows)) {
+ if ($rows) {
foreach ($rows as $row) {
$columns = $row->childNodes;
$update = '';
$data = [];
$idColumn = $tableName . '_id';
+ $idValue = null;
foreach ($columns as $column) {
- //if ($column->nodeName == '#text') continue;
$columnName = $column->nodeName;
$columnValue = $column->nodeValue;
if ($columnName == 'parent_id' && $columnValue > 0) {
//self refrence table id
$oldId = $columnValue;
- $columnValue = $this->idsMap[$idColumn][$columnValue];
+ $columnValue = $this->idsMap[$idColumn][$columnValue] ?? $columnValue;
}
if ($columnName == $idColumn) {
@@ -281,8 +311,8 @@ class Xml {
}
}
- $cols = implode("$q, $q",array_keys($data));
- $values = implode(', :',array_keys($data));
+ $cols = implode("$q, $q", array_keys($data));
+ $values = implode(', :', array_keys($data));
$duplicate = "ON DUPLICATE KEY UPDATE $update\n\n";
@@ -296,7 +326,7 @@ class Xml {
$stmt = $this->db->execute($sql, $data);
$lastId = $this->db->insert_id;
- if ($idColumn != 'site_id' && $idColumn != 'language_id') {
+ if ($idValue !== null && $idColumn != 'site_id' && $idColumn != 'language_id') {
$this->idsMap[$idColumn][$idValue] = $lastId;
}
diff --git a/system/locale.php b/system/locale.php
index cfe57ea..b0863c7 100644
--- a/system/locale.php
+++ b/system/locale.php
@@ -20,32 +20,30 @@
*
*/
-/**
- * Manages image retrival and saving.
- *
- * @package Vvveb
- * @subpackage System
- * @since 0.0.1
- */
-
namespace Vvveb\System;
use function Vvveb\rrmdir;
use function Vvveb\session;
class Locale {
- static private $code;
+ /** @var string|null Current language code. */
+ private static ?string $code = null;
- static function availableLanguages() {
+ /**
+ * Get all available languages from the database.
+ *
+ * @return array<string, array<string, mixed>> List of language records keyed by slug.
+ */
+ public static function availableLanguages(): array {
static $languages = [];
if ($languages != []) {
return $languages;
}
$cache = Cache::getInstance();
- $languages = $cache->cache(APP,'languages',static function () {
+ $languages = $cache->cache(APP, 'languages', static function() {
$languages = new \Vvveb\Sql\LanguageSQL();
- $result = $languages->getAll(['status' => 1]);
+ $result = $languages->getAll(['status' => 1]);
if ($result && isset($result['language'])) {
return $result['language'];
@@ -57,16 +55,21 @@ class Locale {
return $languages;
}
- static function availableCurrencies() {
+ /**
+ * Get all available currencies from the database.
+ *
+ * @return array<string, array<string, mixed>> List of currency records keyed by code.
+ */
+ public static function availableCurrencies(): array {
static $currencies = [];
if ($currencies != []) {
return $currencies;
}
- $cache = Cache::getInstance();
- $currencies = $cache->cache(APP,'currency',static function () {
+ $cache = Cache::getInstance();
+ $currencies = $cache->cache(APP, 'currency', static function() {
$currency = new \Vvveb\Sql\CurrencySQL();
- $result = $currency->getAll(['status' => 1]);
+ $result = $currency->getAll(['status' => 1]);
if ($result && isset($result['currency'])) {
return $result['currency'];
@@ -78,7 +81,12 @@ class Locale {
return $currencies;
}
- static function installedLanguages() {
+ /**
+ * Get list of installed language directories.
+ *
+ * @return list<string> Language folder names.
+ */
+ public static function installedLanguages(): array {
$languages = glob(DIR_ROOT . 'locale/*', GLOB_ONLYDIR);
foreach ($languages as &$language) {
@@ -88,7 +96,14 @@ class Locale {
return $languages;
}
- static function userPreferedLanguages() {
+ /**
+ * Parse the user's preferred languages from the Accept-Language header.
+ *
+ * @return list<string> List of preferred language codes.
+ */
+ public static function userPreferedLanguages(): array {
+ $languages = [];
+
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$languages = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
@@ -98,20 +113,25 @@ class Locale {
}
}
- return $languages ?? [];
+ return $languages;
}
- static function userPreferedLanguage() {
+ /**
+ * Find the best matching installed language from the user's preferences.
+ *
+ * @return string|false The matched language code, or false if none found.
+ */
+ public static function userPreferedLanguage(): string|false {
$languages = self :: userPreferedLanguages();
$installed = self :: installedLanguages();
foreach ($languages as $language) {
- if (isset($installed[$language])) {
+ if (in_array($language, $installed, true)) {
return $language;
}
foreach ($installed as $lang) {
- if (strpos($lang, $language) === 0) {
+ if (str_starts_with($lang, $language)) {
//return $language;
return $lang;
}
@@ -123,17 +143,13 @@ class Locale {
/**
* Change locale language for gettext.
- *
- * @param string $langCode ['en_US']
- * @param string $domain ['vvveb']
*
- * @return mixed
+ * @param string $langCode Language code (e.g. 'en_US').
+ * @param string $domain Gettext domain (e.g. 'vvveb').
+ *
+ * @return void
*/
- static function setLanguage($langCode = 'en_US', $domain = 'vvveb') {
- //global $vvvebTranslationDomains;
- //setlocale(LC_TIME, "");
- //\putenv('LOCPATH=' . DIR_ROOT. "locale");
-
+ public static function setLanguage(string $langCode = 'en_US', string $domain = 'vvveb'): void {
//translating theme text will change theme texts and break translation
if (\Vvveb\isEditor()) {
return;
@@ -142,16 +158,11 @@ class Locale {
self :: $code = $langCode;
if (function_exists('bindtextdomain')) {
- /*
- foreach ($vvvebTranslationDomains as $tdomain) {
- bindtextdomain($tdomain, DIR_ROOT . 'locale');
- }
- */
bindtextdomain($domain, DIR_ROOT . 'locale');
textdomain($domain);
bind_textdomain_codeset($domain, 'UTF-8');
- setlocale(LC_ALL,'C.UTF-8');
+ setlocale(LC_ALL, 'C.UTF-8');
if (function_exists('putenv')) {
@\putenv("LC_ALL=$langCode");
@@ -162,16 +173,24 @@ class Locale {
if (defined('LC_MESSAGES')) {
setlocale(LC_MESSAGES, "$langCode.UTF-8");
- setlocale(LC_CTYPE,"$langCode.UTF-8");
+ setlocale(LC_CTYPE, "$langCode.UTF-8");
} else {
setlocale(5, "$langCode.UTF-8");
- setlocale(6,"$langCode.UTF-8");
+ setlocale(6, "$langCode.UTF-8");
setlocale(LC_ALL, "$langCode.UTF-8");
}
}
}
- static function clearLanguageCache($langCode = 'en_US', $domain = 'vvveb') {
+ /**
+ * Clear compiled language cache files and reset opcache.
+ *
+ * @param string $langCode Language code to clear cache for.
+ * @param string $domain Gettext domain.
+ *
+ * @return void
+ */
+ public static function clearLanguageCache(string $langCode = 'en_US', string $domain = 'vvveb'): void {
if (function_exists('bindtextdomain')) {
$locale = DIR_ROOT . 'locale';
$nocache = DIR_CACHE . 'nocache';
@@ -195,20 +214,43 @@ class Locale {
}
}
- static function getLanguage() {
+ /**
+ * Get the current language code.
+ *
+ * @return string The active language code.
+ */
+ public static function getLanguage(): string {
return self :: $code ?? session('code') ?? 'en_US';
}
- static function setLanguageCode($code) {
+ /**
+ * Set the language code in the session.
+ *
+ * @param string $code Language code to set.
+ *
+ * @return mixed Result of session set.
+ */
+ public static function setLanguageCode(string $code): mixed {
self :: $code = $code;
+
return session(['code' => $code]);
}
- static function getLanguageId() {
+ /**
+ * Get the current language ID from the session.
+ *
+ * @return int The language ID, defaults to 1.
+ */
+ public static function getLanguageId(): int {
return session('language_id') ?? 1;
}
- static function getCurrency() {
+ /**
+ * Get the current currency code from the session.
+ *
+ * @return string The currency code, defaults to 'USD'.
+ */
+ public static function getCurrency(): string {
return session('currency') ?? 'USD';
}
}
diff --git a/system/mail/mail.php b/system/mail/mail.php
old mode 100755
new mode 100644
index 0ae8ae9..5734c9c
--- a/system/mail/mail.php
+++ b/system/mail/mail.php
@@ -20,55 +20,101 @@
*
*/
-/*
- * Code adapted from Opencart 2, GPL 2 license.
- */
+// Code adapted from Opencart 2, GPL 2 license.
namespace Vvveb\System\Mail;
class Mail {
- protected $option = [];
-
- public function __construct(&$option = []) {
+ /** @var array<array-key, mixed> */
+ protected array $option = [];
+
+ /**
+ * @param array<array-key, mixed> &$option
+ *
+ * @return void
+ */
+ public function __construct(array &$option = []) {
$option = $this->option + $option;
$this->option = &$option;
- $this->option['boundary'] = '----=_NextPart_' . md5(time());
+ $this->option['boundary'] = '----=_NextPart_' . md5(time() . '');
- if (! defined('EOL')) {
+ if (!defined('EOL')) {
define('EOL', "\r\n");
}
}
- private function header() {
+ /**
+ * Remove characters that allow header injection (CR, LF, NUL).
+ *
+ * @param mixed $value
+ *
+ * @return string
+ */
+ protected function sanitizeHeaderValue($value): string {
+ return str_replace(["\r", "\n", "\0"], '', (string)$value);
+ }
+
+ /**
+ * Apply configured address overrides (mail.sender_override,
+ * mail.from_address, mail.reply_to), same as the smtp driver.
+ *
+ * @return void
+ */
+ protected function resolveAddresses(): void {
+ if (!empty($this->option['from_address'])) {
+ $this->option['from'] = $this->option['from_address'];
+ }
+
+ if (!empty($this->option['sender_override'])) {
+ $this->option['sender'] = $this->option['sender_override'];
+ }
+
+ //guard against header injection through user supplied fields
+ foreach (['from', 'sender', 'reply_to', 'to'] as $key) {
+ if (isset($this->option[$key])) {
+ $this->option[$key] = is_array($this->option[$key])
+ ? array_map([$this, 'sanitizeHeaderValue'], $this->option[$key])
+ : $this->sanitizeHeaderValue($this->option[$key]);
+ }
+ }
+ }
+
+ /**
+ * @return string
+ */
+ private function header(): string {
$date = date('D, d M Y H:i:s O');
$sender = base64_encode($this->option['sender']);
- $reply_to = base64_encode($this->option['reply_to']);
+ $reply_to = base64_encode($this->option['reply_to'] ?? '');
$header = 'MIME-Version: 1.0' . EOL;
$header .= "Date: $date" . EOL;
$header .= "From: =?UTF-8?B?$sender?= <{$this->option['from']}>" . EOL;
- if (! $this->option['reply_to']) {
+ if (!($this->option['reply_to'] ?? '')) {
$header .= "Reply-To: =?UTF-8?B?$sender?= <{$this->option['from']}>" . EOL;
} else {
$header .= "Reply-To: =?UTF-8?B?$reply_to?= <{$this->option['reply_to']}>" . EOL;
}
$header .= 'Return-Path: ' . $this->option['from'] . EOL;
- $header .= 'X-Mailer: Vvveb PHP/' . phpversion() . EOL;
+ $header .= 'X-Mailer: Vvveb PHP/' . PHP_VERSION . EOL;
$header .= 'Content-Type: multipart/mixed; boundary="' . $this->option['boundary'] . '"' . EOL . EOL;
return $this->option['header'] = $header;
}
- private function attachments() {
+ /**
+ * @return string
+ */
+ private function attachments(): string {
$attachments = '';
if (isset($this->option['attachments'])) {
foreach ($this->option['attachments'] as $attachment) {
if (is_file($attachment)) {
- $name = basename($attachment);
- $id = urlencode(basename($attachment));
+ $name = $this->sanitizeHeaderValue(basename($attachment));
+ $id = urlencode($name);
$content = file_get_contents($attachment);
$attachments .= '--' . $this->option['boundary'] . EOL;
@@ -85,27 +131,29 @@ class Mail {
return $attachments;
}
- private function message() {
- if (! isset($this->option['html'])) {
- $message = '--' . $this->option['boundary'] . EOL;
+ /**
+ * @return string
+ */
+ private function message(): string {
+ $message = '--' . $this->option['boundary'] . EOL;
+
+ if (!isset($this->option['html'])) {
$message .= 'Content-Type: text/plain; charset="utf-8"' . EOL;
$message .= 'Content-Transfer-Encoding: base64' . EOL . EOL;
- $message .= chunk_split(base64_encode($this->option['text']),950) . EOL;
+ $message .= chunk_split(base64_encode($this->option['text'] ?? ''), 950) . EOL;
} else {
- $message = '--' . $this->option['boundary'] . EOL;
+ //$message = '--' . $this->option['boundary'] . EOL;
$message .= 'Content-Type: multipart/alternative; boundary="' . $this->option['boundary'] . '_alt"' . EOL . EOL;
$message .= '--' . $this->option['boundary'] . '_alt' . EOL;
$message .= 'Content-Type: text/plain; charset="utf-8"' . EOL;
$message .= 'Content-Transfer-Encoding: base64' . EOL . EOL;
- if ($this->option['text']) {
+ if ($this->option['text'] ?? false) {
$message .= chunk_split(base64_encode($this->option['text']), 950) . EOL;
} else {
- $message .= chunk_split(base64_encode(strip_tags($this->option['html']), 950), '<a>') . EOL;
+ $message .= chunk_split(base64_encode(strip_tags($this->option['html'])), 950) . EOL;
}
- $message .= $this->attachments();
-
$message .= '--' . $this->option['boundary'] . '_alt' . EOL;
$message .= 'Content-Type: text/html; charset="utf-8"' . EOL;
$message .= 'Content-Transfer-Encoding: base64' . EOL . EOL;
@@ -113,10 +161,18 @@ class Mail {
$message .= '--' . $this->option['boundary'] . '_alt--' . EOL;
}
+ //attachments are top-level parts, appended after the body
+ $message .= $this->attachments();
+
return $message .= '--' . $this->option['boundary'] . '--' . EOL;
}
- public function send() {
+ /**
+ * @return bool
+ */
+ public function send(): bool {
+ $this->resolveAddresses();
+
if (is_array($this->option['to'])) {
$to = implode(',', $this->option['to']);
} else {
@@ -129,6 +185,36 @@ class Mail {
ini_set('sendmail_from', $this->option['from']);
$subject = '=?UTF-8?B?' . base64_encode($this->option['subject']) . '?=';
- return \mail($to, $subject, $message, $header, $this->option['parameter'] ?? '');
+ //no sendmail binary → mail() emits "Sendmail exited with non-zero
+ //exit code" warning; fail cleanly with a logged error instead
+ $sendmail = trim((string)ini_get('sendmail_path'));
+ $binary = $sendmail !== '' ? strtok($sendmail, ' ') : '';
+
+ if ($binary === '' || !is_executable($binary)) {
+ \Vvveb\logError("Mail driver: sendmail binary '$binary' not found or not executable, email to $to not sent. Install sendmail or switch the mail driver to smtp.");
+
+ return false;
+ }
+
+ //capture mail() warnings (e.g. sendmail exit code) into the error
+ //log instead of leaking them to the output
+ $warning = null;
+ set_error_handler(function($no, $str) use (&$warning) {
+ $warning = $str;
+
+ return true;
+ });
+
+ try {
+ $result = \mail($to, $subject, $message, $header, $this->option['parameter'] ?? '');
+ } finally {
+ restore_error_handler();
+ }
+
+ if (!$result) {
+ \Vvveb\logError('Mail driver: ' . ($warning ?? 'mail() failed') . " (to $to).");
+ }
+
+ return $result;
}
}
diff --git a/system/mail/smtp.php b/system/mail/smtp.php
old mode 100755
new mode 100644
index 18f2766..d791283
--- a/system/mail/smtp.php
+++ b/system/mail/smtp.php
@@ -20,14 +20,29 @@
*
*/
-/*
- * Code adapted from Opencart 2, GPL 2 license.
- */
+// Code adapted from Opencart 2, GPL 2 license.
namespace Vvveb\System\Mail;
+/**
+ * Minimal SMTP client: plain, TLS (via STARTTLS), SSL (implicit TLS) and AUTH LOGIN support.
+ *
+ * Security notes:
+ * - address/subject fields are sanitized against header injection (CR/LF/NUL)
+ * - when the server advertises STARTTLS the negotiation is mandatory; a failed
+ * handshake aborts the send instead of falling back to plaintext (which would
+ * leak AUTH LOGIN credentials)
+ * - message lines starting with "." are dot-stuffed per RFC 5321
+ */
class Smtp {
- protected $socketOptions = [
+ /** @var bool */
+ protected bool $debug = false;
+
+ /** @var array<array-key, mixed> */
+ protected array $log = [];
+
+ /** @var array<array-key, mixed> */
+ protected array $socketOptions = [
/*
'ssl' => [
'allow_self_signed' => true,
@@ -40,45 +55,149 @@ class Smtp {
*/
];
- protected $option = [
- 'port' => 25,
- 'timeout' => 5,
- 'max_attempts' => 3,
- 'verp' => false,
+ /** @var array<array-key, mixed> */
+ protected array $option = [
+ 'port' => 25,
+ 'timeout' => 5,
+ 'max_attempts' => 3,
+ 'verp' => false,
+ 'encryption' => 'tls',
];
+ /**
+ * @param array<array-key, mixed> &$option
+ *
+ * @return void
+ */
public function __construct(array &$option = []) {
- $option = $option + $this->option;
+ $option += $this->option;
$this->option = &$option;
- if (! defined('EOL')) {
+ if (isset($this->option['debug'])) {
+ $this->debug = $this->option['debug'];
+ }
+
+ if (!defined('EOL')) {
define('EOL', "\r\n");
}
}
- public function attachments() {
+ /**
+ * Remove characters that allow SMTP header injection (CR, LF, NUL).
+ *
+ * @param mixed $value
+ *
+ * @return string
+ */
+ protected function sanitizeHeaderValue($value): string {
+ return str_replace(["\r", "\n", "\0"], '', (string)$value);
+ }
+
+ /**
+ * Format one or more addresses for a header value ("Name"less form):
+ * each address is angle-bracketed and multiple addresses are comma separated.
+ *
+ * @param string|array<array-key, mixed> $addresses
+ *
+ * @return string
+ */
+ protected function formatAddressList($addresses): string {
+ return implode(', ', array_map(
+ fn ($address) => '<' . $this->sanitizeHeaderValue($address) . '>',
+ (array)$addresses
+ ));
+ }
+
+ /**
+ * Resolve SMTP connection parameters from host and encryption option.
+ *
+ * Supports an explicit $encryption mode ('tls' for STARTTLS, 'ssl' for
+ * implicit TLS) with fallback to legacy 'tls://'/'ssl://' URL prefixes
+ * in $host for backward compatibility with stored settings.
+ *
+ * @param string $host Hostname, optionally with tls:// or ssl:// prefix.
+ * @param string $encryption Explicit mode: '', 'none', 'tls' or 'ssl'.
+ *
+ * @throws \Exception If no hostname remains after parsing.
+ *
+ * @return array{hostname: string, scheme: string, transport: string, starttls: bool}
+ */
+ public static function parseHost(string $host, string $encryption = ''): array {
+ $hostOption = trim($host);
+ $encryption = strtolower(trim($encryption));
+
+ if ($encryption === 'none') {
+ $encryption = '';
+ }
+
+ $scheme = '';
+
+ if ($encryption === 'tls' || $encryption === 'ssl') {
+ $scheme = $encryption;
+ } elseif (preg_match('#^([a-z][a-z0-9+.-]*)://#i', $hostOption, $m)) {
+ $scheme = strtolower($m[1]);
+ }
+
+ if ($scheme === 'tls' || $scheme === 'ssl') {
+ $hostname = (string)preg_replace('#^[a-z][a-z0-9+.-]*://#i', '', $hostOption);
+ } else {
+ $scheme = '';
+ $hostname = $hostOption;
+ }
+
+ $hostname = trim($hostname, " \t\n\r\0\x0B/");
+
+ if ($hostname === '') {
+ throw new \Exception('Smtp host required!');
+ }
+
+ return [
+ 'hostname' => $hostname,
+ 'scheme' => $scheme,
+ 'transport' => $scheme === 'ssl' ? 'ssl' : 'tcp',
+ 'starttls' => $scheme === 'tls',
+ ];
}
- public function send() {
- foreach (['host', 'user', 'password', 'port', 'timeout'] as $key) {
- if (! isset($this->option[$key])) {
+ /**
+ * @throws \Exception
+ *
+ * @return bool
+ */
+ public function send(): bool {
+ foreach (['host', 'port', 'timeout', 'to', 'from', 'sender', 'subject'] as $key) {
+ if (!isset($this->option[$key])) {
throw new \Exception("Smtp $key required!");
}
}
- if (is_array($this->option['to'])) {
- $to = implode(',', $this->option['to']);
- } else {
- $to = $this->option['to'];
+ if (!empty($this->option['from_address'])) {
+ $this->option['from'] = $this->option['from_address'];
+ }
+
+ if (!empty($this->option['sender_override'])) {
+ $this->option['sender'] = $this->option['sender_override'];
+ }
+
+ //guard against header injection through user supplied fields
+ foreach (['from', 'sender', 'reply_to', 'to'] as $key) {
+ if (isset($this->option[$key])) {
+ $this->option[$key] = is_array($this->option[$key])
+ ? array_map([$this, 'sanitizeHeaderValue'], $this->option[$key])
+ : $this->sanitizeHeaderValue($this->option[$key]);
+ }
}
- $serverName = ($_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? getenv('SERVER_NAME'));
- $messageId = base_convert(str_replace(['.', ' '], '', microtime()), 10, 36) . '.' . base_convert(bin2hex(openssl_random_pseudo_bytes(8)), 16, 36) . substr($this->option['from'], strrpos($this->option['from'], '@'));
+ $recipients = (array)$this->option['to'];
- $boundary = '----=_NextPart_' . md5(time());
+ $serverName = ($_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? getenv('SERVER_NAME')) ?: 'localhost';
+ $fromDomain = strrchr($this->option['from'], '@') ?: '@localhost';
+ $messageId = base_convert(str_replace(['.', ' '], '', microtime()), 10, 36) . '.' . base_convert(bin2hex(random_bytes(8)), 16, 36) . $fromDomain;
+
+ $boundary = '----=_NextPart_' . md5(time() . '');
$header = 'MIME-Version: 1.0' . EOL;
- $header .= 'To: <' . $to . '>' . EOL;
+ $header .= 'To: ' . $this->formatAddressList($recipients) . EOL;
$header .= 'Subject: =?UTF-8?B?' . base64_encode($this->option['subject']) . '?=' . EOL;
$header .= 'Date: ' . date('D, d M Y H:i:s O') . EOL;
$header .= 'From: =?UTF-8?B?' . base64_encode($this->option['sender']) . '?= <' . $this->option['from'] . '>' . EOL;
@@ -89,9 +208,9 @@ class Smtp {
$header .= 'Reply-To: =?UTF-8?B?' . base64_encode($this->option['reply_to']) . '?= <' . $this->option['reply_to'] . '>' . EOL;
}
- $header .= 'Message-ID: <' . $messageId . '>' . PHP_EOL;
+ $header .= 'Message-ID: <' . $messageId . '>' . EOL;
$header .= 'Return-Path: ' . $this->option['from'] . EOL;
- $header .= 'X-Mailer: PHP/' . phpversion() . EOL;
+ $header .= 'X-Mailer: PHP/' . PHP_VERSION . EOL;
$header .= 'Content-Type: multipart/mixed; boundary="' . $boundary . '"' . EOL . EOL;
$message = '--' . $boundary . EOL;
@@ -99,41 +218,38 @@ class Smtp {
if (empty($this->option['html'])) {
$message .= 'Content-Type: text/plain; charset="utf-8"' . EOL;
$message .= 'Content-Transfer-Encoding: base64' . EOL . EOL;
- $message .= chunk_split(base64_encode($this->option['text'])) . EOL;
+ $message .= chunk_split(base64_encode($this->option['text'] ?? ''), 950) . EOL;
} else {
$message .= 'Content-Type: multipart/alternative; boundary="' . $boundary . '_alt"' . EOL . EOL;
$message .= '--' . $boundary . '_alt' . EOL;
$message .= 'Content-Type: text/plain; charset="utf-8"' . EOL;
$message .= 'Content-Transfer-Encoding: base64' . EOL . EOL;
- if ($this->option['text']) {
- $message .= chunk_split(base64_encode($this->option['text'])) . EOL;
+ if ($this->option['text'] ?? false) {
+ $message .= chunk_split(base64_encode($this->option['text']), 950) . EOL;
} else {
- $message .= chunk_split(base64_encode(strip_tags($this->option['html'])), '<a>') . EOL;
+ $message .= chunk_split(base64_encode(strip_tags($this->option['html'])), 950) . EOL;
}
$message .= '--' . $boundary . '_alt' . EOL;
$message .= 'Content-Type: text/html; charset="utf-8"' . EOL;
$message .= 'Content-Transfer-Encoding: base64' . EOL . EOL;
- $message .= chunk_split(base64_encode($this->option['html'])) . EOL;
+ $message .= chunk_split(base64_encode($this->option['html']), 950) . EOL;
$message .= '--' . $boundary . '_alt--' . EOL;
}
- if (! empty($this->option['attachments'])) {
+ if (!empty($this->option['attachments'])) {
foreach ($this->option['attachments'] as $attachment) {
if (is_file($attachment)) {
- $handle = fopen($attachment, 'r');
-
- $content = fread($handle, filesize($attachment));
-
- fclose($handle);
+ $content = file_get_contents($attachment);
+ $name = $this->sanitizeHeaderValue(basename($attachment));
$message .= '--' . $boundary . EOL;
- $message .= 'Content-Type: application/octet-stream; name="' . basename($attachment) . '"' . EOL;
+ $message .= 'Content-Type: application/octet-stream; name="' . $name . '"' . EOL;
$message .= 'Content-Transfer-Encoding: base64' . EOL;
- $message .= 'Content-Disposition: attachment; filename="' . basename($attachment) . '"' . EOL;
- $message .= 'Content-ID: <' . urlencode(basename($attachment)) . '>' . EOL;
- $message .= 'X-Attachment-Id: ' . urlencode(basename($attachment)) . EOL . EOL;
+ $message .= 'Content-Disposition: attachment; filename="' . $name . '"' . EOL;
+ $message .= 'Content-ID: <' . urlencode($name) . '>' . EOL;
+ $message .= 'X-Attachment-Id: ' . urlencode($name) . EOL . EOL;
$message .= chunk_split(base64_encode($content));
}
}
@@ -141,145 +257,174 @@ class Smtp {
$message .= '--' . $boundary . '--' . EOL;
- if (substr($this->option['host'], 0, 3) == 'tls') {
- $hostname = substr($this->option['host'], 6);
- } else {
- $hostname = $this->option['host'];
+ $parsed = self::parseHost(
+ (string)$this->option['host'],
+ (string)$this->option['encryption']
+ );
+
+ $hostname = $parsed['hostname'];
+ $transport = $parsed['transport'];
+ $useStartTls = $parsed['starttls'];
+
+ $port = trim((string)$this->option['port']);
+
+ if (!ctype_digit($port) || (int)$port < 1 || (int)$port > 65535) {
+ throw new \Exception('Smtp port invalid!');
}
- //$handle = fsockopen($hostname, $this->option['port'], $errno, $errstr, $this->option['timeout']);
$context = stream_context_create();
if ($this->socketOptions) {
stream_context_set_options($context, $this->socketOptions);
}
- $handle = stream_socket_client("tcp://$hostname:{$this->option['port']}", $errno, $errstr, $this->option['timeout'], STREAM_CLIENT_CONNECT, $context);
+ $handle = stream_socket_client("$transport://$hostname:$port", $errno, $errstr, $this->option['timeout'], STREAM_CLIENT_CONNECT, $context);
- if ($handle) {
- if (substr(PHP_OS, 0, 3) != 'WIN') {
- stream_set_timeout($handle, $this->option['timeout'], 0);
- }
+ if (!$handle) {
+ throw new \Exception("Could not connect to $hostname:$port - $errstr ($errno)");
+ }
- while ($line = fgets($handle, 515)) {
- if (substr($line, 3, 1) == ' ') {
- break;
- }
+ if (substr(PHP_OS, 0, 3) != 'WIN') {
+ stream_set_timeout($handle, $this->option['timeout'], 0);
+ }
+
+ while ($line = fgets($handle, 515)) {
+ if (substr($line, 3, 1) == ' ') {
+ break;
}
+ }
- fputs($handle, 'EHLO ' . $serverName . EOL);
+ fwrite($handle, 'EHLO ' . $serverName . EOL);
- $reply = '';
+ $reply = '';
- while ($line = fgets($handle, 515)) {
- $reply .= $line;
+ while ($line = fgets($handle, 515)) {
+ $reply .= $line;
- if (substr($reply, 0, 3) == 220 && substr($line, 3, 1) == ' ') {
- $reply = '';
+ if (substr($reply, 0, 3) == 220 && substr($line, 3, 1) == ' ') {
+ $reply = '';
- continue;
- } elseif (substr($line, 3, 1) == ' ') {
- break;
- }
- }
-
- if (substr($reply, 0, 3) != 250) {
- throw new \Exception('EHLO not accepted from server!' . $reply);
+ continue;
+ } elseif (substr($line, 3, 1) == ' ') {
+ break;
}
+ }
- if (substr($this->option['host'], 0, 3) == 'tls') {
- fputs($handle, 'STARTTLS' . EOL);
+ if (substr($reply, 0, 3) != 250) {
+ throw new \Exception('EHLO not accepted from server!' . $reply);
+ }
- $this->handleReply($handle, 220, 'STARTTLS not accepted from server!');
+ if ($useStartTls) {
+ fwrite($handle, 'STARTTLS' . EOL);
- stream_socket_enable_crypto($handle, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
- }
+ $this->handleReply($handle, 220, 'STARTTLS not accepted from server!');
- if (! empty($this->option['user']) && ! empty($this->option['password'])) {
- fputs($handle, 'EHLO ' . $serverName . EOL);
+ //abort rather than continue unencrypted; AUTH LOGIN credentials
+ //must never be sent over plaintext
+ if (!stream_socket_enable_crypto($handle, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
+ fclose($handle);
- $this->handleReply($handle, 250, 'EHLO not accepted from server!');
+ throw new \Exception('TLS negotiation failed!');
+ }
+ }
- fputs($handle, 'AUTH LOGIN' . EOL);
+ if (!empty($this->option['user']) && !empty($this->option['password'])) {
+ fwrite($handle, 'EHLO ' . $serverName . EOL);
- $this->handleReply($handle, 334, 'AUTH LOGIN not accepted from server!');
+ $this->handleReply($handle, 250, 'EHLO not accepted from server!');
- fputs($handle, base64_encode($this->option['user']) . EOL);
+ fwrite($handle, 'AUTH LOGIN' . EOL);
- $this->handleReply($handle, 334, 'Username not accepted from server!');
+ $this->handleReply($handle, 334, 'AUTH LOGIN not accepted from server!');
- fputs($handle, base64_encode($this->option['password']) . EOL);
+ fwrite($handle, base64_encode($this->option['user']) . EOL);
- $this->handleReply($handle, 235, 'Password not accepted from server!' . $reply);
- } else {
- fputs($handle, 'HELO ' . $serverName . EOL);
+ $this->handleReply($handle, 334, 'Username not accepted from server!');
- $this->handleReply($handle, 250, 'HELO not accepted from server!');
- }
+ fwrite($handle, base64_encode($this->option['password']) . EOL);
- if ($this->option['verp']) {
- fputs($handle, 'MAIL FROM: <' . $this->option['from'] . '>XVERP' . EOL);
- } else {
- fputs($handle, 'MAIL FROM: <' . $this->option['from'] . '>' . EOL);
- }
+ $this->handleReply($handle, 235, 'Password not accepted from server!' . $reply);
+ } else {
+ fwrite($handle, 'HELO ' . $serverName . EOL);
- $this->handleReply($handle, 250, 'MAIL FROM not accepted from server!');
+ $this->handleReply($handle, 250, 'HELO not accepted from server!');
+ }
- if (! is_array($this->option['to'])) {
- fputs($handle, 'RCPT TO: <' . $this->option['to'] . '>' . EOL);
+ if ($this->option['verp']) {
+ //XVERP is an ESMTP parameter, separated from the address by a space
+ fwrite($handle, 'MAIL FROM: <' . $this->option['from'] . '> XVERP' . EOL);
+ } else {
+ fwrite($handle, 'MAIL FROM: <' . $this->option['from'] . '>' . EOL);
+ }
- $reply = $this->handleReply($handle, false, 'RCPT TO [!array]');
+ $this->handleReply($handle, 250, 'MAIL FROM not accepted from server!');
- if ((substr($reply, 0, 3) != 250) && (substr($reply, 0, 3) != 251)) {
- throw new \Exception('RCPT TO not accepted from server!');
- }
- } else {
- foreach ($this->option['to'] as $recipient) {
- fputs($handle, 'RCPT TO: <' . $recipient . '>' . EOL);
+ foreach ($recipients as $recipient) {
+ fwrite($handle, 'RCPT TO: <' . $recipient . '>' . EOL);
- $reply = $this->handleReply($handle, false, 'RCPT TO [array]');
+ $reply = $this->handleReply($handle, false, 'RCPT TO');
- if ((substr($reply, 0, 3) != 250) && (substr($reply, 0, 3) != 251)) {
- throw new \Exception('RCPT TO not accepted from server!');
- }
- }
+ if ((substr($reply, 0, 3) != 250) && (substr($reply, 0, 3) != 251)) {
+ throw new \Exception('RCPT TO not accepted from server!');
}
+ }
- fputs($handle, 'DATA' . EOL);
+ fwrite($handle, 'DATA' . EOL);
- $this->handleReply($handle, 354, 'DATA not accepted from server!' . $reply);
+ $this->handleReply($handle, 354, 'DATA not accepted from server!' . $reply);
- // According to rfc 821 we should not send more than 1000 including the CRLF
- $message = str_replace(EOL, "\n", $header . $message);
- $message = str_replace("\r", "\n", $message);
+ // According to rfc 821 we should not send more than 1000 including the CRLF
+ $message = str_replace(EOL, "\n", $header . $message);
+ $message = str_replace("\r", "\n", $message);
- $lines = explode("\n", $message);
+ $lines = explode("\n", $message);
- foreach ($lines as $line) {
- $results = (empty($line)) ? [''] : str_split($line, 998);
+ foreach ($lines as $line) {
+ $results = (empty($line)) ? [''] : str_split($line, 998);
- foreach ($results as $result) {
- fputs($handle, $result . EOL);
+ foreach ($results as $result) {
+ //dot-stuffing per rfc 5321: lines starting with "." get an extra dot
+ if ($result && $result[0] === '.') {
+ $result = '.' . $result;
}
+
+ fwrite($handle, $result . EOL);
}
+ }
- fputs($handle, '.' . EOL);
- $this->handleReply($handle, 250, 'DATA not accepted from server!' . $reply);
- /*
- fputs($handle, 'QUIT' . EOL);
- $this->handleReply($handle, 221, 'QUIT not accepted from server!');
- */
- fclose($handle);
+ fwrite($handle, '.' . EOL);
+ $this->handleReply($handle, 250, 'DATA not accepted from server!' . $reply);
+ /*
+ fputs($handle, 'QUIT' . EOL);
+ $this->handleReply($handle, 221, 'QUIT not accepted from server!');
+ */
+ fclose($handle);
+
+ if ($this->debug && $this->log) {
+ $this->log += $lines;
+ file_put_contents(DIR_STORAGE . 'logs/mail_log', implode(EOL, $this->log), FILE_APPEND);
+ }
- return true;
- } else {
- throw new \Exception('' . $errstr . ' (' . $errno . ')');
+ return true;
+ }
- return false;
+ /**
+ * Read a (possibly multi line) server reply and optionally validate its status code.
+ *
+ * @param mixed $handle
+ * @param int|false $status_code Expected status code or false to skip validation.
+ * @param string|false $error_text Exception message on status mismatch.
+ * @param int $counter Retry counter for empty reads.
+ *
+ * @throws \Exception
+ *
+ * @return string
+ */
+ private function handleReply(mixed $handle, int|false $status_code = false, string|false $error_text = false, int $counter = 0): string {
+ if (!is_resource($handle)) {
+ throw new \InvalidArgumentException('SMTP reply requires a stream resource.');
}
- }
- private function handleReply($handle, $status_code = false, $error_text = false, $counter = 0) {
$reply = '';
while (($line = fgets($handle, 515)) !== false) {
@@ -291,7 +436,7 @@ class Smtp {
}
// Wait for response
- if (! $line && empty($reply) && $counter < $this->option['max_attempts']) {
+ if (!$line && !feof($handle) && $counter < $this->option['max_attempts']) {
sleep(1);
$counter++;
@@ -305,6 +450,10 @@ class Smtp {
}
}
+ if ($this->debug) {
+ $this->log[] = $reply;
+ }
+
return $reply;
}
}
diff --git a/system/mcp.php b/system/mcp.php
new file mode 100644
index 0000000..d98c8f2
--- /dev/null
+++ b/system/mcp.php
@@ -0,0 +1,275 @@
+<?php
+
+/**
+ * Vvveb
+ *
+ * Copyright (C) 2022 Ziadin Givan
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+namespace Vvveb\System;
+
+use Vvveb\System\Extensions\Extensions;
+
+class MCP {
+ /**
+ * Check whether native shell execution is available.
+ * Inspects disable_functions and function_exists for shell_exec/proc_open/exec.
+ */
+ public static function isShellAvailable(): bool {
+ $disabled = array_filter(array_map('trim', explode(',', (string)ini_get('disable_functions'))));
+ $disabled = array_map('strtolower', $disabled);
+ if (in_array('shell_exec', $disabled, true) && in_array('proc_open', $disabled, true) && in_array('exec', $disabled, true)) {
+ return false;
+ }
+ // proc_open is the primary mechanism used by toolBash
+ if (!function_exists('proc_open') || !function_exists('shell_exec')) {
+ return false;
+ }
+
+ return !(in_array('proc_open', $disabled, true) || in_array('shell_exec', $disabled, true));
+ }
+
+ /**
+ * Check whether native shell execution is available.
+ * Inspects disable_functions and function_exists for shell_exec/proc_open/exec.
+ *
+ * @return list<string>
+ */
+ public static function disabledTools(): array {
+ $tools = [];
+ if (self::isShellAvailable()) {
+ array_push($tools, 'glob', 'grep', 'bash_sub');
+ if (PHP_OS_FAMILY == 'Windows' || DIRECTORY_SEPARATOR === '\\') {
+ //no bash on windows
+ $tools[] = 'bash';
+ } else {
+ //no powershell on linux
+ $tools[] = 'powershell';
+ }
+ } else {
+ $tools = ['bash', 'powershell'];
+ }
+
+ return $tools;
+ }
+
+ /**
+ * Whether mutating tool operations are currently allowed.
+ */
+ public static function writesEnabled(): bool {
+ try {
+ return \Vvveb\config('mcp.tools.db_write', false) === true;
+ } catch (\Throwable $e) {
+ return false;
+ }
+ }
+
+ public const WRITES_DISABLED_NOTE = ' Writes are disabled (enable mcp.tools.db_write to allow them).';
+
+ /**
+ * Append the writes-disabled note to descriptions of tools that can
+ * mutate (readOnlyHint === false) when writes are off. No-op when
+ * writes are enabled, so enabled agents never see the warning.
+ *
+ * @param array<array-key, mixed> $tools
+ *
+ * @return array<array-key, mixed>
+ */
+ public static function annotateTools(array $tools): array {
+ if (self::writesEnabled()) {
+ return $tools;
+ }
+
+ foreach ($tools as &$tool) {
+ if (($tool['annotations']['readOnlyHint'] ?? null) === false && isset($tool['description'])) {
+ $tool['description'] .= self::WRITES_DISABLED_NOTE;
+ }
+ }
+ unset($tool);
+
+ return $tools;
+ }
+
+ /**
+ * Get system prompt
+ *
+ * $format api, mcp defaults to mcp
+ *
+ * @param int $roleId
+ * @param array<array-key, mixed> $append
+ *
+ * @return string System prompt.
+ */
+ public static function systemPrompt(int $roleId, array $append = []): string {
+ $toolsDesc = [
+ 'read' => 'Read file contents',
+ 'write' => 'Create or overwrite files',
+ 'grep' => 'Search file contents recursively with a regular expression',
+ 'glob' => 'Find files by matching a glob pattern',
+ 'crud' => 'Add/edit/delete CMS content records (posts, products, ...) via data models',
+ 'crud_models' => 'Discover data model names and exact IN parameters per crud operation (call before writing data calls); params flag required vs omittable and record columns',
+ 'media' => 'Media library files and metadata (list/get/save/delete/upload/fetch/mkdir/scan)',
+ 'admin' => 'Manage themes, plugins, cron jobs and caches',
+ 'powershell' => 'Execute a PowerShell command inside the site root directory',
+ 'database_query' => 'SQL against the site database (SELECT/SHOW/DESCRIBE preferred)',
+ 'bash' => 'Execute bash commands (ls, grep, find, etc.)',
+ 'bash_sub' => 'Pure-PHP sandboxed bash fallback when native shell functions are disabled',
+ 'str_replace_editor' => 'Viewing, creating and editing files',
+ //'page' => 'Run javascript in page builder edited page',
+ //'ui' => 'Run javascript in user window'
+ ];
+
+ $disable = self::disabledTools();
+ $toolsText = '';
+ foreach ($toolsDesc as $name => $desc) {
+ if (in_array($name, $disable)) {
+ continue;
+ }
+ $toolsText .= "- $name: $desc\n";
+ }
+
+ $prompt = 'You are an expert assistant operating inside a CMS'
+. (($append['instructions'] ?? '') ? ', ' . $append['instructions'] : '')
+
+. '.
+
+Available tools:
+'
+. $toolsText
+. (($append['tools'] ?? '') ? "\n" . $append['tools'] : '')
+
+. '
+In addition to the tools above, you may have access to other custom tools depending on the project.
+
+Guidelines:
+- Use crud for editing or adding content
+- Use admin for managing themes, plugins, media or cron
+- Use media for image and media upload and insert
+- Use str_replace_editor view command to examine files instead of cat or sed.
+- Use str_replace_editor edit command for precise changes (edits[].oldText must match exactly)
+- When changing multiple separate locations in one file, use one edit call with multiple entries in edits[] instead of multiple edit calls
+- Each edits[].oldText is matched against the original file, not after earlier edits are applied. Do not emit overlapping or nested edits. Merge nearby changes into one edit.
+- Keep edits[].oldText as small as possible while still being unique in the file. Do not pad with large unchanged regions.
+- Don\'t save page without asking.
+- Use dedicated tools before falling back to general purpose.
+- Don\'t execute destructive or bulk operations without user confirmation.
+- Be concise in your responses'
+. (($append['guidelines'] ?? '') ? "\n" . $append['guidelines'] : '') . "\n";
+
+ $agents = @file_get_contents(DIR_ROOT . 'AGENTS.md') ?: '';
+ $context = "\n<project_context>\nProject-specific instructions and guidelines:\n";
+ $context .= "<project_instructions path=\"/AGENTS.md\">\n{$agents}\n</project_instructions>";
+
+ $skills = self::skills();
+ $skillsText = '';
+ if ($skills) {
+ $skillsText = "The following skills provide specialized instructions for specific tasks.
+Use the read tool to load a skill's file when the task matches its description.
+When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.\n";
+ $skillsText = "<available_skills>\n";
+ foreach ($skills as $file => $desc) {
+ $skillsText .= "\t<skill>\n";
+ $skillsText .= "\t\t<name>{$desc['name']}</name>\n";
+ $skillsText .= "\t\t<description>{$desc['description']}</description>\n";
+ $skillsText .= "\t\t<location>{$desc['location']}</location>\n";
+ $skillsText .= "\t</skill>\n";
+ }
+ $skillsText .= "</available_skills>\n";
+ }
+
+ $context .= "</project_context>\n";
+
+ $prompt .= $context . $skillsText;
+ $prompt .= 'Current working directory: ' . DIR_ROOT;
+
+ return $prompt;
+ }
+
+ /**
+ * Get all available tools .
+ *
+ * $format api, mcp defaults to mcp
+ *
+ * @param ?int $roleId
+ * @param ?string $format
+ *
+ * @return array<array-key, mixed> List of tools.
+ */
+ public static function tools(?int $roleId = null, ?string $format = null): array {
+ $tools = self::annotateTools(include DIR_ROOT . 'mcp' . DS . 'tools.php');
+
+ $disable = self::disabledTools();
+
+ if ($format === 'api') {
+ $api = [];
+ foreach ($tools as $tool) {
+ if (in_array($tool['name'], $disable)) {
+ continue;
+ }
+ $parameters = [];
+
+ if (isset($tool['inputSchema']['properties'])) {
+ $parameters = [
+ 'type' => 'object',
+ 'properties' => $tool['inputSchema']['properties'],
+ 'required' => $tool['inputSchema']['required'] ?? []];
+ }
+
+ $api[] = [
+ 'type' => 'function',
+ 'function' => [
+ 'name' => $tool['name'],
+ 'description' => $tool['description'],
+ 'parameters' => $parameters
+ ]
+ ];
+ }
+
+ return $api;
+ }
+
+ return $tools;
+ }
+
+ /** Get all available tools from the database.
+ *
+ * @return array<array-key, mixed> list of tools
+ */
+ public static function skills(): array {
+ $path = DIR_ROOT . 'skills';
+ $files = scandir($path);
+ $skills = [];
+ foreach ($files as $file) {
+ if ($file[0] === '.') {
+ continue;
+ }
+ $location = DS . 'skills' . DS . $file . DS . 'SKILL.md';
+
+ $markdown = file_get_contents(DIR_ROOT . $location, false, null, 0, 500);
+ $params = [];
+ if ($markdown && strncmp($markdown, '---', 3) === 0) {
+ if (preg_match('@^\s*---.+?---\s*@ms', $markdown, $matches)) {
+ $params = Extensions::getParams($matches[0]);
+ }
+ }
+
+ $skills[$file] = ['name' => $params['name'] ?? $file, 'description' => $params['description'] ?? $file, 'location' => $location];
+ }
+
+ return $skills;
+ }
+}
diff --git a/system/media/font.php b/system/media/font.php
index 63efcfc..2140349 100644
--- a/system/media/font.php
+++ b/system/media/font.php
@@ -23,17 +23,24 @@
namespace Vvveb\System\Media;
class Font {
- const KEY_VALUE_REGEX = '/\s*(.+?)\s*:\s*([^;$]+)[;$]?/ms';
-
- const FONT_FACE_REGEX = '/@font-face\s*{([^}]+)}/ms';
-
- static function getParams($comments) {
+ /** @var string */
+ public const KEY_VALUE_REGEX = '/\s*(.+?)\s*:\s*([^;$]+)[;$]?/ms';
+
+ /** @var string */
+ public const FONT_FACE_REGEX = '/@font-face\s*{([^}]+)}/ms';
+
+ /**
+ * Parse key-value pairs from a CSS comment block.
+ *
+ * @param string $comments The CSS comments to parse.
+ *
+ * @return array<string, string> Associative array<array-key, mixed> of key-value pairs.
+ */
+ public static function getParams(string $comments): array {
$results = [];
- if (preg_match_all(static :: KEY_VALUE_REGEX, $comments, $matches)) {
- $matches[1] = array_map(function ($key) {
- return trim($key);
- }, $matches[1]);
+ if (preg_match_all(static::KEY_VALUE_REGEX, $comments, $matches)) {
+ $matches[1] = array_map(fn ($key) => trim($key), $matches[1]);
$results = array_combine($matches[1], $matches[2]);
}
@@ -41,7 +48,14 @@ class Font {
return $results;
}
- static function arrayToFontFaces($fonts = []) {
+ /**
+ * Convert an array of font definitions to CSS @font-face declarations.
+ *
+ * @param array<int, array<string, string>> $fonts Array of font property maps.
+ *
+ * @return string CSS @font-face rules.
+ */
+ public static function arrayToFontFaces(array $fonts = []): string {
$css = '';
if ($fonts) {
@@ -55,8 +69,8 @@ class Font {
}
if (isset($font['src'])) {
- if (strncmp($font['src'], 'url(', 4) === 0) {
- $font['src']= substr($font['src'], 4);
+ if (str_starts_with($font['src'], 'url(')) {
+ $font['src'] = substr($font['src'], 4);
}
$src = trim($font['src'], '\'")(');
@@ -66,47 +80,58 @@ class Font {
$properties = '';
foreach ($font as $property => $value) {
- if ($value) {
- $properties .= "$property: $value;";
- }
+ $properties .= "$property: $value;";
}
if ($properties) {
$css .= '@font-face {' . $properties . "}\n";
}
}
+ unset($font);
}
return $css;
}
- static function removeFontFaces($css) {
- return preg_replace(static :: FONT_FACE_REGEX, '', $css) ?? $css;
+ /**
+ * Remove all @font-face declarations from a CSS string.
+ *
+ * @param string $css The CSS string to process.
+ *
+ * @return string CSS string without @font-face rules.
+ */
+ public static function removeFontFaces(string $css): string {
+ return preg_replace(static::FONT_FACE_REGEX, '', $css) ?? $css;
}
- static function parseFontFaces($css, $allFonts = true, $variants = true) {
- $fontFaceRegex = '/@font-face\s*{([^}]+)}/ms';
- //$css = file_get_contents($cssFile);
- $fonts = [];
- $matches = [];
-
- if (preg_match_all(static:: FONT_FACE_REGEX, $css, $matches)) {
+ /**
+ * Parse @font-face declarations from a CSS string.
+ *
+ * @param string $css The CSS string to parse.
+ * @param bool $allFonts Whether to include all font weights/styles.
+ * @param bool $variants Whether to group fonts by family with variants.
+ *
+ * @return array<int|string, mixed> Parsed font data, keyed by family name if variants is true.
+ */
+ public static function parseFontFaces(string $css, bool $allFonts = true, bool $variants = true): array {
+ $fonts = [];
+ $matches = [];
+
+ if (preg_match_all(static::FONT_FACE_REGEX, $css, $matches)) {
foreach ($matches[1] as $match) {
- //var_dump($match);
$properties = $match;
- //var_dump($match);
- $props = self::getParams($properties);
+ $props = self::getParams($properties);
if (isset($props['font-family'])) {
$props['font-family'] = trim($props['font-family'], '\'"');
}
if (isset($props['src'])) {
- if (strncmp($props['src'], 'url(', 4) === 0) {
- $props['src']= substr($props['src'], 4);
+ if (str_starts_with($props['src'], 'url(')) {
+ $props['src'] = substr($props['src'], 4);
}
- $props['src']= trim($props['src'], '\'")(');
+ $props['src'] = trim($props['src'], '\'")(');
}
$font = [];
@@ -114,14 +139,14 @@ class Font {
if ($allFonts) {
$font = $props;
} else {
- if ((! isset($props['font-weight']) || $props['font-weight'] == '400' || $props['font-weight'] == 'normal' || strpos($props['font-weight'], ' ') !== false)
- && (! isset($props['font-style']) || $props['font-style'] == 'normal')) {
+ if ((!isset($props['font-weight']) || $props['font-weight'] === '400' || $props['font-weight'] === 'normal' || str_contains($props['font-weight'], ' '))
+ && (!isset($props['font-style']) || $props['font-style'] === 'normal')) {
$font = $props;
}
}
if ($variants) {
- $family = $props['font-family'];
+ $family = $props['font-family'] ?? '';
if ($family) {
$fonts[$family]['variants'][] = $font;
@@ -137,7 +162,15 @@ class Font {
return $fonts;
}
- static function themeFonts($theme, $variants = false) {
+ /**
+ * Get fonts defined in a theme's CSS files.
+ *
+ * @param string $theme Theme directory name.
+ * @param bool $variants Whether to group fonts by family with variants.
+ *
+ * @return array<int|string, mixed> Parsed font data from theme CSS.
+ */
+ public static function themeFonts(string $theme, bool $variants = false): array {
$fonts = [];
if ($theme && is_dir($themeCssDir = DIR_THEMES . $theme . DS . 'css' . DS)) {
@@ -145,11 +178,11 @@ class Font {
$fontsCss = $themeCssDir . 'fonts.css';
if (file_exists($styleCss) && ($css = file_get_contents($styleCss))) {
- $fonts = Font::parseFontFaces($css, false, $variants);
+ $fonts = self::parseFontFaces($css, false, $variants);
}
if (file_exists($fontsCss) && ($css = file_get_contents($fontsCss))) {
- $fonts = array_merge($fonts, Font::parseFontFaces($css, false, $variants));
+ $fonts = array_merge($fonts, self::parseFontFaces($css, false, $variants));
}
}
diff --git a/system/media/gd.php b/system/media/gd.php
old mode 100644
new mode 100755
index 90ac576..e7b4bec
--- a/system/media/gd.php
+++ b/system/media/gd.php
@@ -23,17 +23,27 @@
namespace Vvveb\System\Media;
class Image {
- private $file;
+ /** @var string */
+ private string $file = '';
- private $image;
+ /** @var mixed Image handle of the active driver. */
+ private mixed $image = false;
- private $width;
+ /** @var int */
+ private int $width = 0;
- private $height;
+ /** @var int */
+ private int $height = 0;
- private $mime;
+ /** @var string */
+ private string $mime = '';
- public function __construct($file) {
+ /**
+ * Load an image file and initialize GD image resource.
+ *
+ * @param string $file Path to the image file.
+ */
+ public function __construct(string $file) {
if (is_file($file)) {
$this->file = $file;
@@ -42,120 +52,190 @@ class Image {
if ($info) {
$this->width = $info[0];
$this->height = $info[1];
- $this->mime = $info['mime'] ?? '';
+ $this->mime = $info['mime'];
- if ($this->mime == 'image/gif') {
- $this->image = imagecreatefromgif($file);
- } elseif ($this->mime == 'image/png') {
- $this->image = imagecreatefrompng($file);
+ $this->image = match ($this->mime) {
+ 'image/gif' => imagecreatefromgif($file),
+ 'image/png' => imagecreatefrompng($file),
+ 'image/jpeg' => imagecreatefromjpeg($file),
+ 'image/webp' => imagecreatefromwebp($file),
+ default => false,
+ };
+ if ($this->mime === 'image/png' && $this->image) {
imageinterlace($this->image, false);
- } elseif ($this->mime == 'image/jpeg') {
- $this->image = imagecreatefromjpeg($file);
- } elseif ($this->mime == 'image/webp') {
- $this->image = imagecreatefromwebp($file);
}
+
+ //preserve transparency for png/webp sources
+ if ($this->image && in_array($this->mime, ['image/png', 'image/webp'])) {
+ imagesavealpha($this->image, true);
+ }
+ /*
+ if (STRIP_EXIF) {
+ $profiles = $this->image->getImageProfiles('icc', true);
+ $this->image->stripImage();
+
+ if (! empty($profiles)) {
+ $this->image->profileImage('icc', $profiles['icc']);
+ }
+ }
+ */
}
} else {
//throw new \Exception("Could not load image $file");
}
}
- public function getFile() {
+ /**
+ * Get the file path.
+ *
+ * @return string
+ */
+ public function getFile(): string {
return $this->file;
}
- public function getImage() {
+ /**
+ * Get the GD image resource.
+ *
+ * @return \GdImage|false
+ */
+ public function getImage(): \GdImage|false {
return $this->image;
}
- public function getWidth() {
+ /**
+ * Get the image width.
+ *
+ * @return int
+ */
+ public function getWidth(): int {
return $this->width;
}
- public function getHeight() {
+ /**
+ * Get the image height.
+ *
+ * @return int
+ */
+ public function getHeight(): int {
return $this->height;
}
- public function getMime() {
+ /**
+ * Get the image MIME type.
+ *
+ * @return string
+ */
+ public function getMime(): string {
return $this->mime;
}
- public function save($file, $quality = 80, $extension = false) {
- if (! $this->image) {
- return;
+ /**
+ * Save the image to a file.
+ *
+ * @param string $file Output file path.
+ * @param int $quality Compression quality (0-100).
+ * @param string|false $extension File extension override, or false to detect from path.
+ *
+ * @return bool
+ */
+ public function save(string $file, int $quality = 80, string|false $extension = false): bool {
+ if (!$this->image) {
+ return false;
}
$info = pathinfo($file);
- $extension = $extension ?: strtolower($info['extension']);
-
- $result = false;
-
- if (is_object($this->image) || is_resource($this->image)) {
- if ($extension == 'jpeg' || $extension == 'jpg') {
- $result = @imagejpeg($this->image, $file, $quality);
- } elseif ($extension == 'png') {
- $result = @imagepng($this->image, $file, 8, PNG_ALL_FILTERS);
- } elseif ($extension == 'gif') {
- $result = @imagegif($this->image, $file);
- } elseif ($extension == 'webp') {
- $result = @imagewebp($this->image, $file, $quality);
- }
-
- if (PHP_MAJOR_VERSION < 8) {
- imagedestroy($this->image);
- }
+ $extension = $extension ?: strtolower($info['extension'] ?? '');
- return $result;
- }
+ return match ($extension) {
+ 'jpeg', 'jpg' => @imagejpeg($this->image, $file, $quality),
+ 'png' => @imagepng($this->image, $file, 8, PNG_ALL_FILTERS),
+ 'gif' => @imagegif($this->image, $file),
+ 'webp' => @imagewebp($this->image, $file, $quality),
+ default => false,
+ };
}
- public function resize($width, $height = 0, $method = 's') {
+ /**
+ * Resize the image using the specified method.
+ *
+ * @param int $width Target width.
+ * @param int $height Target height (0 to auto-calculate).
+ * @param string $method Resize method: 'r' (ratio), 's' (stretch), 'c' (crop), 'cs' (cropsize).
+ *
+ * @return bool
+ */
+ public function resize(int $width, int $height = 0, string $method = 's'): bool {
switch ($method) {
case 'r':
- return $this->_resize($width, $height);
+ return $this->resizeRatio($width, $height);
case 's':
return $this->stretch($width, $height);
case 'c':
- return $this->crop($width, $height);
+ $this->crop(0, 0, $width, $height);
+
+ return true;
case 'cs':
- return $this->cropsize($width, $height);
+ $this->cropsize($width, $height);
+
+ return true;
}
+
+ return false;
}
- public function stretch($width, $height = 0) {
- if (! $this->width || ! $this->height || ! $this->image) {
- return;
+ /**
+ * Stretch the image to the specified dimensions.
+ *
+ * @param int $width Target width.
+ * @param int $height Target height (0 to auto-calculate from ratio).
+ *
+ * @return bool
+ */
+ public function stretch(int $width, int $height = 0): bool {
+ if (!$this->width || !$this->height || !$this->image) {
+ return false;
}
- $ratio = $newRatio = $this->width / $this->height;
+ $newRatio = $this->width / $this->height;
if ($width && $height) {
$newRatio = $width / $height;
}
- if (! $height) {
- $height = ceil($width / $newRatio);
- }
-
- $this->image = imagescale($this->image, $width, $height, IMG_BICUBIC_FIXED);
- }
-
- public function _resize($width, $height = 0) {
- if (! $this->width || ! $this->height || ! $this->image) {
- return;
+ if (!$height) {
+ $height = (int)ceil($width / $newRatio);
}
- $ratio = $newRatio = $this->width / $this->height;
+ $scaled = imagescale($this->image, $width, $height, IMG_BICUBIC_FIXED);
- if ($width && $height) {
- $newRatio = $width / $height;
+ if (!$scaled) {
+ return false;
}
+ $this->image = $scaled;
+ imagesavealpha($scaled, true);
+
+ return true;
+ }
+
+ /**
+ * Resize the image while preserving aspect ratio.
+ *
+ * @param int $width Target width.
+ * @param int $height Target height (0 to auto-calculate from ratio).
+ *
+ * @return bool
+ */
+ public function resizeRatio(int $width, int $height = 0): bool {
+ if (!$this->width || !$this->height || !$this->image) {
+ return false;
+ }
if ($width && $height) {
$scaleW = $width / $this->width;
@@ -167,25 +247,44 @@ class Image {
$height = (int)($this->height * $scale);
} else {
if ($width) {
- $height = ceil($this->height / ($this->width / $width));
- } else {
- if ($height) {
- $width = ceil($this->width / ($this->height / $height));
- }
+ $height = (int)ceil($this->height / ($this->width / $width));
+ } elseif ($height) {
+ $width = (int)ceil($this->width / ($this->height / $height));
}
}
- $this->image = imagescale($this->image, $width, $height, IMG_BICUBIC_FIXED);
+ $scaled = imagescale($this->image, $width, $height, IMG_BICUBIC_FIXED);
+
+ if (!$scaled) {
+ return false;
+ }
+ $this->image = $scaled;
$this->width = $width;
$this->height = $height;
+ imagesavealpha($scaled, true);
+
+ return true;
}
- public function crop($topX, $topY, $bottomX, $bottomY) {
- if (! $this->width || ! $this->height || ! $this->image) {
+ /**
+ * Crop the image from given coordinates.
+ *
+ * @param int $topX Top-left X coordinate.
+ * @param int $topY Top-left Y coordinate.
+ * @param int $bottomX Bottom-right X coordinate (0 for image width).
+ * @param int $bottomY Bottom-right Y coordinate (0 for image height).
+ *
+ * @return void
+ */
+ public function crop(int $topX, int $topY, int $bottomX = 0, int $bottomY = 0): void {
+ if (!$this->width || !$this->height || !$this->image) {
return;
}
+ $bottomX = $bottomX ?: $this->width;
+ $bottomY = $bottomY ?: $this->height;
+
$imageOld = $this->image;
$this->image = imagecreatetruecolor($bottomX - $topX, $bottomY - $topY);
@@ -196,44 +295,59 @@ class Image {
$this->height = $bottomY - $topY;
}
- public function cropsize($width, $height = 0) {
- if (! $this->width || ! $this->height || ! $this->image) {
+ /**
+ * Crop and resize the image to the specified dimensions.
+ *
+ * @param int $width Target width.
+ * @param int $height Target height (0 to auto-calculate from ratio).
+ *
+ * @return void
+ */
+ public function cropsize(int $width, int $height = 0): void {
+ if (!$this->width || !$this->height || !$this->image) {
return;
}
- $ratio = $newRatio = $this->width / $this->height;
+ $newRatio = $this->width / $this->height;
if ($width && $height) {
$newRatio = $width / $height;
}
- if (! $height) {
- $height = $width / $newRatio;
+ if (!$height) {
+ $height = (int)($width / $newRatio);
}
+ $ratio = $this->width / $this->height;
+
if ($newRatio > $ratio) {
- $newWidth = $width;
- $newHeight = floor($width / $this->width * $this->height);
+ $newWidth = (int)$width;
+ $newHeight = (int)floor($width / $this->width * $this->height);
$crop_x = 0;
- $crop_y = intval(($newHeight - $height) / 2);
- } else if ($newRatio < $ratio) {
- $newWidth = floor($height / $this->height * $this->width);
- $newHeight = intval($height);
- $crop_x = intval(($newWidth - $width) / 2);
+ $crop_y = (int)(int)(($newHeight - $height) / 2);
+ } elseif ($newRatio < $ratio) {
+ $newWidth = (int)floor($height / $this->height * $this->width);
+ $newHeight = (int)$height;
+ $crop_x = (int)(int)(($newWidth - $width) / 2);
$crop_y = 0;
} else {
- $newWidth = intval($width);
- $newHeight = intval($height);
+ $newWidth = (int)$width;
+ $newHeight = (int)$height;
}
$image = false;
- if ($this->width != $newWidth && $this->height != $newHeight) {
+
+ if ($this->width !== $newWidth || $this->height !== $newHeight) {
$image = imagescale($this->image, $newWidth, $newHeight);
+
+ if ($image) {
+ imagesavealpha($image, true);
+ }
}
if ($image) {
- if ($width != $newWidth || $newHeight != $height) {
- $image = imagecrop($image, ['x' => 0, 'y' => 0, 'width' => $width, 'height' => $height]);
+ if ($width !== $newWidth || $newHeight !== $height) {
+ $image = imagecrop($image, ['x' => 0, 'y' => 0, 'width' => $width, 'height' => (int)$height]);
}
if ($image) {
@@ -242,26 +356,33 @@ class Image {
}
}
- public static function formats($format = false) {
+ /**
+ * Get supported image formats or check if a specific format is supported.
+ *
+ * @param string|false $format Format extension to check, or false to return all supported formats.
+ *
+ * @return array<array-key, mixed>|bool Array of supported format strings, or bool if a specific format was queried.
+ */
+ public static function formats(string|false $format = false): array|bool {
$formats = [];
$info = gd_info();
foreach ([
- 'JPEG Support' => 'jpg',
- 'PNG Support' => 'png',
- 'WebP Support' => 'webp',
- 'AVIF Support' => 'avif',
- 'WBMP Support' => 'wbmp',
+ 'JPEG Support' => 'jpg',
+ 'PNG Support' => 'png',
+ 'WebP Support' => 'webp',
+ 'AVIF Support' => 'avif',
+ 'WBMP Support' => 'wbmp',
'GIF Create Support' => 'gif',
- 'XBM Support"' => 'xbm',
+ 'XBM Support' => 'xbm',
] as $name => $extension) {
- if (isset($info[$name]) && $info[$name]) {
+ if (!empty($info[$name])) {
$formats[] = $extension;
}
}
if ($format) {
- return in_array($format, $formats);
+ return in_array($format, $formats, true);
}
return $formats;
diff --git a/system/media/image.php b/system/media/image.php
old mode 100755
new mode 100644
index 73cd95d..5e55ef5
--- a/system/media/image.php
+++ b/system/media/image.php
@@ -20,8 +20,15 @@
*
*/
-if ((extension_loaded('imagick') && $extension = 'imagick') ||
- (extension_loaded('gd') && $extension = 'gd') ||
- ($extension = 'mockup')) {
- include "$extension.php";
+/**
+ * Image driver dispatcher — loads the best available Image implementation.
+ *
+ * Priority: Imagick > GD > Mockup stub.
+ */
+if (extension_loaded('imagick')) {
+ require_once __DIR__ . '/imagick.php';
+} elseif (extension_loaded('gd')) {
+ require_once __DIR__ . '/gd.php';
+} else {
+ require_once __DIR__ . '/mockup.php';
}
diff --git a/system/media/imagick.php b/system/media/imagick.php
old mode 100644
new mode 100755
index c1624d5..c8bc100
--- a/system/media/imagick.php
+++ b/system/media/imagick.php
@@ -23,119 +23,201 @@
namespace Vvveb\System\Media;
class Image {
- private $file;
+ /** @var string */
+ private string $file = '';
- private $image;
+ /** @var mixed Image handle of the active driver. */
+ private mixed $image = false;
- private $width;
+ /** @var int */
+ private int $width = 0;
- private $height;
+ /** @var int */
+ private int $height = 0;
- private $mime;
+ /** @var string */
+ private string $mime = '';
- public function __construct($file) {
- if (file_exists($file)) {
+ /**
+ * Load an image file using Imagick.
+ *
+ * @param string $file Path to the image file.
+ */
+ public function __construct(string $file) {
+ if (!file_exists($file)) {
+ //leave the object empty like the gd driver does for missing files
+ return;
+ }
+
+ try {
$this->file = $file;
$this->image = new \Imagick();
$this->image->readImage($file);
$this->width = $this->image->getImageWidth();
$this->height = $this->image->getImageHeight();
- $this->mime = $this->image->getFormat();
- //if (STRIP_EXIF) {
- $profiles = $this->image->getImageProfiles('icc', true);
+ $this->mime = $this->image->getImageMimeType();
+ $profiles = $this->image->getImageProfiles('icc', true);
$this->image->stripImage();
- if (! empty($profiles)) {
+ if (!empty($profiles)) {
$this->image->profileImage('icc', $profiles['icc']);
}
- //}
- } else {
- //throw new \Exception("Could not load image $file");
+ } catch (\Throwable $e) {
+ //corrupt or unsupported files degrade to an empty image
+ //instead of failing construction, like the gd driver
+ $this->image = false;
+ $this->width = 0;
+ $this->height = 0;
+ $this->mime = '';
}
}
- public function getFile() {
+ /**
+ * Get the file path.
+ *
+ * @return string
+ */
+ public function getFile(): string {
return $this->file;
}
- public function getImage() {
+ /**
+ * Get the Imagick image instance.
+ *
+ * @return \Imagick|false
+ */
+ public function getImage(): \Imagick|false {
return $this->image;
}
- public function getWidth() {
+ /**
+ * Get the image width.
+ *
+ * @return int
+ */
+ public function getWidth(): int {
return $this->width;
}
- public function getHeight() {
+ /**
+ * Get the image height.
+ *
+ * @return int
+ */
+ public function getHeight(): int {
return $this->height;
}
- public function getMime() {
+ /**
+ * Get the image MIME type.
+ *
+ * @return string
+ */
+ public function getMime(): string {
return $this->mime;
}
- public function save($file, $quality = 80, $extension = false) {
- if (! $this->image) {
- return;
+ /**
+ * Save the image to a file.
+ *
+ * @param string $file Output file path.
+ * @param int $quality Compression quality (0-100).
+ * @param string|false $extension File extension override, or false to use current format.
+ *
+ * @return bool
+ */
+ public function save(string $file, int $quality = 80, string|false $extension = false): bool {
+ if (!$this->image) {
+ return false;
}
- $this->image->setImageFormat($extension ?: $this->mime);
+ try {
+ if ($extension) {
+ $this->image->setImageFormat($extension);
+ }
- $this->image->setCompressionQuality($quality);
- //$this->image->setImageCompressionQuality($quality);
+ $this->image->setCompressionQuality($quality);
- $this->image->stripImage();
+ $this->image->stripImage();
- return $this->image->writeImage($file);
+ return $this->image->writeImage($file);
+ } catch (\Throwable $e) {
+ return false;
+ }
}
- public function resize($width, $height = 0, $method = 's') {
- if (! $this->width || ! $this->height) {
- return;
+ /**
+ * Resize the image using the specified method.
+ *
+ * @param int $width Target width.
+ * @param int $height Target height (0 to auto-calculate).
+ * @param string $method Resize method: 'r' (ratio), 's' (stretch), 'c' (crop), 'cs' (cropsize).
+ *
+ * @return bool
+ */
+ public function resize(int $width, int $height = 0, string $method = 's'): bool {
+ if (!$this->width || !$this->height) {
+ return false;
}
switch ($method) {
case 'r':
- return $this->_resize($width, $height);
-
+ return $this->resizeRatio($width, $height);
+
case 's':
return $this->stretch($width, $height);
case 'c':
- return $this->crop($width, $height);
+ $this->crop(0, 0, $width, $height);
+
+ return true;
case 'cs':
- return $this->cropsize($width, $height);
+ $this->cropsize($width, $height);
+
+ return true;
}
+
+ return false;
}
- public function stretch($width, $height = 0) {
- $ratio = $newRatio = $this->width / $this->height;
+ /**
+ * Stretch the image to the specified dimensions.
+ *
+ * @param int $width Target width.
+ * @param int $height Target height (0 to auto-calculate from ratio).
+ *
+ * @return bool
+ */
+ public function stretch(int $width, int $height = 0): bool {
+ if (!$this->width || !$this->height || !$this->image) {
+ return false;
+ }
+
+ $newRatio = $this->width / $this->height;
if ($width && $height) {
$newRatio = $width / $height;
}
-
- if (! $height) {
- $height = ceil($width / $newRatio);
- }
- if (method_exists($this->image, 'adaptiveResizeImage')) {
- return $this->image->adaptiveResizeImage($width, $height);
- } else {
- //$this->image->thumbnailImage($width, $height, true, true);
- return $this->image->resizeImage($width, $height, \Imagick::FILTER_LANCZOS, 1, true);
+ if (!$height) {
+ $height = (int)ceil($width / $newRatio);
}
- }
-
- public function _resize($width, $height = 0) {
- //$this->width = $this->image->getImageWidth();
- //$this->height = $this->image->getImageHeight();
- $ratio = $newRatio = $this->width / $this->height;
+ return $this->image->adaptiveResizeImage($width, $height);
+ }
- if ($width && $height) {
- $newRatio = $width / $height;
+ /**
+ * Resize the image while preserving aspect ratio.
+ *
+ * @param int $width Target width.
+ * @param int $height Target height (0 to auto-calculate from ratio).
+ *
+ * @return bool
+ */
+ public function resizeRatio(int $width, int $height = 0): bool {
+ if (!$this->width || !$this->height || !$this->image) {
+ return false;
}
if ($width && $height) {
@@ -148,72 +230,105 @@ class Image {
$height = (int)($this->height * $scale);
} else {
if ($width) {
- $height = ceil($this->height / ($this->width / $width));
+ $height = (int)ceil($this->height / ($this->width / $width));
} else {
if ($height) {
- $width = ceil($this->width / ($this->height / $height));
+ $width = (int)ceil($this->width / ($this->height / $height));
}
}
}
- if (method_exists($this->image, 'adaptiveResizeImage')) {
- return $this->image->adaptiveResizeImage($width, $height);
- } else {
- //$this->image->thumbnailImage($width, $height, true, true);
- return $this->image->resizeImage($width, $height, \Imagick::FILTER_LANCZOS, 1, true);
- }
+ return $this->image->adaptiveResizeImage($width, $height);
}
- public function crop($top_x, $top_y, $bottom_x, $bottom_y) {
- $this->image->cropImage($bottom_x - $top_x, $bottom_y - $top_y, $top_x, $top_y);
+ /**
+ * Crop the image from given coordinates.
+ *
+ * @param int $topX Top-left X coordinate.
+ * @param int $topY Top-left Y coordinate.
+ * @param int $bottomX Bottom-right X coordinate (0 for image width).
+ * @param int $bottomY Bottom-right Y coordinate (0 for image height).
+ *
+ * @return void
+ */
+ public function crop(int $topX, int $topY, int $bottomX = 0, int $bottomY = 0): void {
+ if (!$this->width || !$this->height || !$this->image) {
+ return;
+ }
+
+ $bottomX = $bottomX ?: $this->width;
+ $bottomY = $bottomY ?: $this->height;
+ $this->image->cropImage($bottomX - $topX, $bottomY - $topY, $topX, $topY);
$this->width = $this->image->getImageWidth();
$this->height = $this->image->getImageHeight();
}
- public function cropsize($width, $height = 0) {
- $ratio = $newRatio = $this->width / $this->height;
+ /**
+ * Crop and resize the image to the specified dimensions.
+ *
+ * @param int $width Target width.
+ * @param int $height Target height (0 to auto-calculate from ratio).
+ *
+ * @return void
+ */
+ public function cropsize(int $width, int $height = 0): void {
+ if (!$this->width || !$this->height || !$this->image) {
+ return;
+ }
+
+ $newRatio = $this->width / $this->height;
if ($width && $height) {
$newRatio = $width / $height;
}
- if (! $height) {
- $height = $width / $newRatio;
+ if (!$height) {
+ $height = (int)($width / $newRatio);
}
- $ratio = $this->width / $this->height;
+ $ratio = $this->width / $this->height;
if ($newRatio > $ratio) {
- $newWidth = $width;
- $newHeight = floor($width / $this->width * $this->height);
- $crop_x = 0;
- $crop_y = intval(($newHeight - $height) / 2);
- } else if ($newRatio < $ratio) {
- $newWidth = floor($height / $this->height * $this->width);
- $newHeight = $height;
- $crop_x = intval(($newWidth - $width) / 2);
- $crop_y = 0;
+ $newWidth = (int)$width;
+ $newHeight = (int)floor($width / $this->width * $this->height);
+ $crop_x = 0;
+ $crop_y = (int)(int)(($newHeight - $height) / 2);
+ } elseif ($newRatio < $ratio) {
+ $newWidth = (int)floor($height / $this->height * $this->width);
+ $newHeight = (int)$height;
+ $crop_x = (int)(int)(($newWidth - $width) / 2);
+ $crop_y = 0;
} else {
- $newWidth = intval($width);
- $newHeight = intval($height);
- $crop_x = 0;
- $crop_y = 0;
+ $newWidth = (int)$width;
+ $newHeight = (int)$height;
+ $crop_x = 0;
+ $crop_y = 0;
}
- if ($this->width != $newWidth && $this->height != $newHeight) {
+ if ($this->width !== $newWidth || $this->height !== $newHeight) {
$this->image->resizeImage($newWidth, $newHeight, \Imagick::FILTER_LANCZOS, 1, true);
}
- if ($width != $newWidth || $newHeight != $height) {
- $this->image->cropImage($width, $height, $crop_x, $crop_y);
+ if ($width !== $newWidth || $newHeight !== $height) {
+ $this->image->cropImage($width, (int)$height, $crop_x, $crop_y);
}
}
- public static function formats($format = false) {
- $formats = \Imagick::queryformats() ?? [];
+ /**
+ * Get supported image formats or check if a specific format is supported.
+ *
+ * @param string|false $format Format extension to check, or false to return all supported formats.
+ *
+ * @return array<array-key, mixed>|bool Array of supported format strings, or bool if a specific format was queried.
+ */
+ public static function formats(string|false $format = false): array|bool {
+ $formats = array_map('strtolower', \Imagick::queryformats());
+
+ if ($format) {
+ return in_array($format, $formats, true);
+ }
- //return array_map(fn($value) => strtolower($value), $info);
- return array_map('strtolower', $formats);
+ return $formats;
}
}
diff --git a/system/media/mockup.php b/system/media/mockup.php
index a18e4b0..b5175ed 100644
--- a/system/media/mockup.php
+++ b/system/media/mockup.php
@@ -22,53 +22,128 @@
namespace Vvveb\System\Media;
+/**
+ * Stub Image class used when neither Imagick nor GD extensions are available.
+ *
+ * All methods return false or empty values to maintain interface compatibility
+ * while allowing the application to gracefully degrade.
+ */
class Image {
- private $file;
+ /** @var string */
+ private string $file = '';
- private $image;
+ /** @var mixed */
+ private mixed $image = null;
- private $width;
+ /** @var int */
+ private int $width = 0;
- private $height;
+ /** @var int */
+ private int $height = 0;
- private $mime;
+ /** @var string */
+ private string $mime = '';
- public function __construct($file) {
+ /**
+ * Stub constructor for when no image extension is available.
+ *
+ * @param string $file Path to the image file.
+ */
+ public function __construct(string $file) {
+ $this->file = $file;
}
- public function getFile() {
- return false;
+ /**
+ * Get the file path (stub).
+ *
+ * @return string
+ */
+ public function getFile(): string {
+ return $this->file;
}
- public function getImage() {
- return false;
+ /**
+ * Get the image resource (stub).
+ *
+ * @return mixed null for stub.
+ */
+ public function getImage(): mixed {
+ return $this->image;
}
- public function getWidth() {
- return false;
+ /**
+ * Get the image width (stub).
+ *
+ * @return int Always 0 for stub.
+ */
+ public function getWidth(): int {
+ return $this->width;
}
- public function getHeight() {
- return false;
+ /**
+ * Get the image height (stub).
+ *
+ * @return int Always 0 for stub.
+ */
+ public function getHeight(): int {
+ return $this->height;
}
- public function getMime() {
- return false;
- }
-
- public function save($file, $quality = 80) {
- return false;
+ /**
+ * Get the image MIME type (stub).
+ *
+ * @return string Empty string for stub.
+ */
+ public function getMime(): string {
+ return $this->mime;
}
- public function resize($width, $height, $method = 's') {
+ /**
+ * Save the image to a file (stub).
+ *
+ * @param string $file Output file path.
+ * @param int $quality Compression quality (0-100).
+ * @param string|false $extension File extension override, or false to detect from path.
+ *
+ * @return bool Always false for stub.
+ */
+ public function save(string $file, int $quality = 80, string|false $extension = false): bool {
return false;
}
- public function crop($topX, $topY, $bottomX, $bottomY) {
+ /**
+ * Resize the image (stub).
+ *
+ * @param int $width Target width.
+ * @param int $height Target height.
+ * @param string $method Resize method.
+ *
+ * @return bool Always false for stub.
+ */
+ public function resize(int $width, int $height = 0, string $method = 's'): bool {
return false;
}
- public static function formats($format = false) {
+ /**
+ * Crop the image (stub).
+ *
+ * @param int $topX Top-left X coordinate.
+ * @param int $topY Top-left Y coordinate.
+ * @param int $bottomX Bottom-right X coordinate.
+ * @param int $bottomY Bottom-right Y coordinate.
+ *
+ * @return void
+ */
+ public function crop(int $topX, int $topY, int $bottomX = 0, int $bottomY = 0): void {}
+
+ /**
+ * Get supported image formats (stub).
+ *
+ * @param string|false $format Format extension to check, or false to return all supported formats.
+ *
+ * @return array<array-key, mixed> Empty array for stub.
+ */
+ public static function formats(string|false $format = false): array {
return [];
}
}
diff --git a/system/meta/meta.php b/system/meta/meta.php
index e4f886c..80d52cb 100644
--- a/system/meta/meta.php
+++ b/system/meta/meta.php
@@ -24,31 +24,79 @@ namespace Vvveb\System\Meta;
use function Vvveb\model;
+/** @phpstan-consistent-constructor */
class Meta {
- private $setting = [];
+ /** @var array<array-key, mixed> */
+ private array $setting = [];
- protected $settingSql;
+ /** @var mixed */
+ protected mixed $settingSql;
- private static $instance;
+ /** @var array<class-string, static> Per-class instances so subclasses don't collide */
+ private static array $instances = [];
- protected $modelName;
+ /** @var string */
+ protected string $modelName;
- protected $item_id;
+ /** @var string */
+ protected string $item_id;
- public static function getInstance() {
- if (static::$instance) {
- return static::$instance;
- } else {
- return static::$instance = new static();
- }
+ /**
+ * Get singleton instance of the Meta class.
+ *
+ * @return static
+ */
+ public static function getInstance(): static {
+ //per-class storage: PostMeta::getInstance() and ProductMeta::getInstance()
+ //must return distinct instances even though they share this base class
+ $class = static::class;
+
+ return self::$instances[$class] ??= new static();
}
- function __construct() {
+ /**
+ * Constructor.
+ */
+ public function __construct() {
$this->settingSql = model($this->modelName);
}
- public function getMulti($item_id, $namespace, $key = null, $default = null, $language_id = false) {
- if ($key && ! is_array($key)) {
+ /**
+ * Decode a JSON-looking meta value ({...} or [...]) to PHP, if possible.
+ *
+ * Shared by get()/getMulti() and the setMulti() runtime-cache sync so
+ * all three interpret stored values identically. Non-strings, short
+ * strings and invalid JSON pass through unchanged.
+ *
+ * @param mixed $value Raw stored value.
+ *
+ * @return mixed Decoded value or the original.
+ */
+ private function decodeValue(mixed $value): mixed {
+ if (is_string($value) && strlen($value) > 1 && ($value[0] === '{' || $value[0] === '[')) {
+ $json = json_decode($value, true);
+
+ if ($json !== null) {
+ return $json;
+ }
+ }
+
+ return $value;
+ }
+
+ /**
+ * Get multiple meta values.
+ *
+ * @param int|string $item_id
+ * @param string $namespace
+ * @param string|array<array-key, mixed>|null $key
+ * @param mixed $default
+ * @param int|false $language_id
+ *
+ * @return array<array-key, mixed>
+ */
+ public function getMulti(int|string $item_id, string $namespace, string|array|null $key = null, mixed $default = [], int|false $language_id = false): array {
+ if ($key && !is_array($key)) {
$key = [$key];
}
@@ -58,13 +106,9 @@ class Meta {
if ($result) {
foreach ($result as &$value) {
- $val = &$value['value'];
-
- if ($val && is_string($val) && ($val[0] == '{' || $val[0] == '{')) {
- $json = json_decode($val, true);
- $val = $json ?: $val;
- }
+ $value['value'] = $this->decodeValue($value['value'] ?? null);
}
+ unset($value);
$return = $result;
} else {
@@ -82,32 +126,49 @@ class Meta {
return $return;
}
- public function get($item_id, $namespace, $key = null, $default = null, $language_id = false) {
- if (! $namespace && ! $key) {
+ /**
+ * Get a single meta value.
+ *
+ * @param int|string $item_id
+ * @param string $namespace
+ * @param string|array<array-key, mixed>|null $key
+ * @param mixed $default
+ * @param int|false $language_id
+ *
+ * @return mixed
+ */
+ public function get(int|string $item_id, string $namespace, string|array|null $key = null, mixed $default = null, int|false $language_id = false): mixed {
+ if (!$namespace && !$key) {
return $default;
}
if (is_array($key) || empty($key)) {
- $this->getMulti($item_id, $namespace, $key, $default, $language_id);
- } else {
- if (isset($this->setting[$namespace][$key])) {
- return $this->setting[$namespace][$key];
- }
+ return $this->getMulti($item_id, $namespace, $key, $default, $language_id);
+ }
- $result = $this->settingSql->get([$this->item_id => $item_id, 'namespace' => $namespace, 'key' => $key, 'language_id' => $language_id]) ?? $default;
+ if (isset($this->setting[$namespace][$key])) {
+ return $this->setting[$namespace][$key];
+ }
- if ($result && is_string($result) && ($result[0] == '{' || $result[0] == '[')) {
- $json = json_decode($result, true);
- $result = $json ?: $result;
- }
+ $result = $this->settingSql->get([$this->item_id => $item_id, 'namespace' => $namespace, 'key' => $key, 'language_id' => $language_id]) ?? $default;
- return $result;
- }
+ return $this->decodeValue($result);
}
- public function set($item_id, $namespace, $key, $value, $language_id = false) {
- if (! $namespace || ! $key) {
- return;
+ /**
+ * Set a single meta value.
+ *
+ * @param int|string $item_id
+ * @param string $namespace
+ * @param string $key
+ * @param mixed $value
+ * @param int|false $language_id
+ *
+ * @return mixed
+ */
+ public function set(int|string $item_id, string $namespace, string $key, mixed $value, int|false $language_id = false): mixed {
+ if (!$namespace || !$key) {
+ return null;
}
$this->setting[$namespace][$key] = $value;
@@ -119,36 +180,65 @@ class Meta {
return $this->settingSql->set([$this->item_id => $item_id, 'namespace' => $namespace, 'key' => $key, 'value' => $value, 'language_id' => $language_id]);
}
- public function delete($item_id, $namespace, $key, $language_id = false) {
- if (! $namespace || ! $key) {
- return;
+ /**
+ * Delete a single meta value.
+ *
+ * @param int|string $item_id
+ * @param string $namespace
+ * @param array<array-key, mixed>|string|null $key
+ * @param int|false $language_id
+ *
+ * @return mixed
+ */
+ public function delete(int|string $item_id, string $namespace, array|string|null $key = null, int|false $language_id = false): mixed {
+ if (!$namespace || !$key) {
+ return null;
}
- unset($this->setting[$namespace][$key]);
+ if (is_array($key)) {
+ foreach ($key as $k) {
+ unset($this->setting[$namespace][$k]);
+ }
+ } else {
+ unset($this->setting[$namespace][$key]);
+ }
return $this->settingSql->delete([$this->item_id => $item_id, 'namespace' => $namespace, 'key' => $key, 'language_id' => $language_id]);
}
- public function setMulti($item_id, $meta) {
- $result = false;
-
+ /**
+ * Set multiple meta values.
+ *
+ * @param int|string $item_id
+ * @param array<array-key, mixed> $meta List of meta rows, each with at least
+ * a `key` and a `value`. Rows may carry their
+ * own `namespace`, otherwise $namespace applies.
+ * @param string $namespace Namespace applied to rows that do not
+ * define their own (e.g. post/product meta).
+ * @param int|false $language_id Language applied when the meta table is
+ * language-aware, false otherwise.
+ *
+ * @return mixed
+ */
+ public function setMulti(int|string $item_id, array $meta, string $namespace = '', int|false $language_id = false): mixed {
foreach ($meta as &$item) {
- if (is_array($item['value'])) {
+ if (isset($item['value']) && is_array($item['value'])) {
$item['value'] = json_encode($item['value']);
}
}
+ unset($item);
- $result = $this->settingSql->setMulti([$this->item_id => $item_id, 'meta' => $meta]);
+ $result = $this->settingSql->setMulti([$this->item_id => $item_id, 'language_id' => $language_id, 'namespace' => $namespace, 'meta' => $meta]);
- if ($meta) {
- /*
- foreach ($meta as $key => $value) {
- if (is_array($value)) {
- $value = json_encode($value);
+ //keep the runtime cache consistent for values set through this call
+ foreach ($meta as $item) {
+ if (isset($item['key'])) {
+ $ns = $item['namespace'] ?? $namespace;
+
+ if ($ns !== '') {
+ $this->setting[$ns][$item['key']] = $this->decodeValue($item['value'] ?? '');
}
- $this->setting[$namespace][$key] = $value;
- $result = $this->settingSql->set([$this->item_id => $item_id, 'namespace' => $namespace, 'key' => $key, 'value' => $value, 'site_id' => $site_id, 'language_id' => $language_id]);
- }*/
+ }
}
return $result;
diff --git a/system/meta/post-content-meta.php b/system/meta/post-content-meta.php
old mode 100644
new mode 100755
index 8a5cc98..7a6792f
--- a/system/meta/post-content-meta.php
+++ b/system/meta/post-content-meta.php
@@ -23,7 +23,9 @@
namespace Vvveb\System\Meta;
class PostContentMeta extends Meta {
- protected $modelName = 'post_content_meta';
+ /** @var string */
+ protected string $modelName = 'post_content_meta';
- protected $item_id = 'post_id';
+ /** @var string */
+ protected string $item_id = 'post_id';
}
diff --git a/system/meta/post-meta.php b/system/meta/post-meta.php
old mode 100644
new mode 100755
index 696b3e1..fe9fab4
--- a/system/meta/post-meta.php
+++ b/system/meta/post-meta.php
@@ -23,7 +23,9 @@
namespace Vvveb\System\Meta;
class PostMeta extends Meta {
- protected $modelName = 'post_meta';
+ /** @var string */
+ protected string $modelName = 'post_meta';
- protected $item_id = 'post_id';
+ /** @var string */
+ protected string $item_id = 'post_id';
}
diff --git a/system/meta/product-content-meta.php b/system/meta/product-content-meta.php
old mode 100644
new mode 100755
index bda1fcb..d519ae2
--- a/system/meta/product-content-meta.php
+++ b/system/meta/product-content-meta.php
@@ -23,7 +23,9 @@
namespace Vvveb\System\Meta;
class ProductContentMeta extends Meta {
- protected $modelName = 'product_content_meta';
+ /** @var string */
+ protected string $modelName = 'product_content_meta';
- protected $item_id = 'product_id';
+ /** @var string */
+ protected string $item_id = 'product_id';
}
diff --git a/system/meta/product-meta.php b/system/meta/product-meta.php
old mode 100644
new mode 100755
index 559799e..a32590e
--- a/system/meta/product-meta.php
+++ b/system/meta/product-meta.php
@@ -23,7 +23,9 @@
namespace Vvveb\System\Meta;
class ProductMeta extends Meta {
- protected $modelName = 'product_meta';
+ /** @var string */
+ protected string $modelName = 'product_meta';
- protected $item_id = 'product_id';
+ /** @var string */
+ protected string $item_id = 'product_id';
}
diff --git a/system/meta/setting-content.php b/system/meta/setting-content.php
old mode 100644
new mode 100755
index ffe4505..4cd1ce2
--- a/system/meta/setting-content.php
+++ b/system/meta/setting-content.php
@@ -23,7 +23,9 @@
namespace Vvveb\System\Meta;
class SettingContent extends Meta {
- protected $modelName = 'setting_content';
+ /** @var string */
+ protected string $modelName = 'setting_content';
- protected $item_id = 'site_id';
+ /** @var string */
+ protected string $item_id = 'site_id';
}
diff --git a/system/notifications.php b/system/notifications.php
new file mode 100644
index 0000000..a2cfbda
--- /dev/null
+++ b/system/notifications.php
@@ -0,0 +1,664 @@
+<?php
+
+/**
+ * Vvveb
+ *
+ * Copyright (C) 2022 Ziadin Givan
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+namespace Vvveb\System;
+
+/**
+ * Notification system — registers events, triggers them, and routes to providers.
+ *
+ * Mirrors the Event class API pattern so core code and plugins have a familiar interface.
+ */
+class Notifications {
+ /** @var array<string, array{description: string, category: string, default_recipients?: string[]}> Registered notification events */
+ private static array $events = [];
+
+ /** @var array<string, class-string<Notifications\Providers\Provider>> Available provider classes (keyed by slug) */
+ private static array $providerClasses = [];
+
+ /** @var array<string, array{enabled: bool, ...}> Loaded provider settings from config */
+ private static array $providerSettings = [];
+
+ /** @var array<string, array{providers: string[], recipients: string[], additional_emails: string[], additional_phones: string[], additional_webhooks: string[], cooldown?: int|string}> Event routing from config */
+ private static array $eventSettings = [];
+
+ /** @var bool Whether providers have been bootstrapped */
+ private static bool $booted = false;
+
+ /** @var array<string, int> Rate-limit last-sent timestamps (event.recipient.provider => timestamp) */
+ private static array $rateLimits = [];
+
+ // ── Registration ───────────────────────────────────────────────────
+
+ /**
+ * Register a notification event so it appears in admin settings and can receive providers.
+ *
+ * @param string $event Dot-separated event name (e.g. 'order.new')
+ * @param array<array-key, mixed> $config { description, category, default_recipients }
+ */
+ public static function register(string $event, array $config = []): void {
+ if (isset(self::$events[$event])) {
+ return; // idempotent
+ }
+
+ self::$events[$event] = [
+ 'description' => $config['description'] ?? $event,
+ 'category' => $config['category'] ?? 'other',
+ 'default_recipients' => $config['default_recipients'] ?? ['site_admin'],
+ ];
+ }
+
+ /**
+ * Check a product against the global low-stock threshold and trigger
+ * product.lowstock if quantity dropped to or below it.
+ *
+ * @param array<array-key, mixed> $product Product record with at least product_id + quantity
+ */
+ public static function checkLowStock(array $product): void {
+ $threshold = \Vvveb\config('notifications.low_stock_threshold', null);
+
+ // No threshold configured (or disabled with 0? 0 means alert when out of stock)
+ if ($threshold === null || $threshold === '') {
+ return;
+ }
+
+ $quantity = (int)($product['quantity'] ?? 0);
+
+ if ($quantity > (int)$threshold) {
+ return;
+ }
+
+ $name = $product['name'] ?? ('#' . ($product['product_id'] ?? '?'));
+ $dedup = 'product.' . ($product['product_id'] ?? ($product['sku'] ?? md5(json_encode($product))));
+
+ self::trigger('product.lowstock', $product + [
+ '_dedup_key' => $dedup,
+ 'subject' => sprintf('Low stock: %s', $name),
+ 'message' => sprintf('%s stock fell to %d (threshold %d).', $name, $quantity, (int)$threshold),
+ ]);
+ }
+
+ /**
+ * Return all registered events, optionally filtered by category.
+ *
+ * @param string|false $category
+ *
+ * @return array<string, array{description: string, category: string, default_recipients?: string[]}>
+ */
+ public static function getEvents(string|false $category = false): array {
+ if ($category !== false) {
+ return array_filter(self::$events, fn ($e) => $e['category'] === $category);
+ }
+
+ return self::$events;
+ }
+
+ // ── Trigger ────────────────────────────────────────────────────────
+
+ /**
+ * Trigger a notification event, dispatching to all enabled providers for that event.
+ *
+ * @param string $event Event name
+ * @param array<array-key, mixed> $data Event-specific payload
+ */
+ public static function trigger(string $event, array $data = []): void {
+ // Always let plugins/core hook into the trigger
+ Event::trigger(self::class, 'trigger:before', $event, $data);
+
+ // Ensure built-in events are registered + config loaded before dispatching.
+ // Idempotent and cheap after the first call; makes trigger() safe as the
+ // very first entry point without a prior explicit registration.
+ self::boot();
+
+ if (!isset(self::$events[$event])) {
+ return; // unregistered event — silently skip
+ }
+
+ $eventConfig = self::$eventSettings[$event] ?? null;
+
+ if (!$eventConfig) {
+ return; // no routing configured for this event
+ }
+
+ $enabledProviders = $eventConfig['providers'];
+
+ if (empty($enabledProviders)) {
+ return;
+ }
+
+ // Build recipients list
+ $recipients = self::resolveRecipients($event, $eventConfig, $data);
+ // Optional extra dedup discriminator (e.g. "product.42") so identical events
+ // for different subjects don't suppress each other
+ $dedupKey = isset($data['_dedup_key']) ? '.' . $data['_dedup_key'] : '';
+
+ // Recipient-less routing (e.g. webhook-only events): dispatch once
+ if (!$recipients) {
+ $recipients[] = ['id' => 'none'];
+ }
+
+ foreach ($recipients as $recipient) {
+ $recipientEmail = $recipient['email'] ?? '';
+ $recipientPhone = $recipient['phone'] ?? '';
+ $recipientName = $recipient['name'] ?? '';
+ $recipientId = ($recipient['id'] ?? $recipientEmail) . $dedupKey;
+
+ // Build envelope (internal routing keys are not exposed to providers)
+ $envelopeData = $data;
+ unset($envelopeData['_dedup_key']);
+
+ $envelope = [
+ 'event' => $event,
+ 'timestamp' => time(),
+ 'recipient' => $recipient,
+ 'subject' => $data['subject'] ?? self::$events[$event]['description'],
+ 'message' => $data['message'] ?? '',
+ 'data' => $envelopeData,
+ ];
+
+ foreach ($enabledProviders as $providerSlug) {
+ // Skip disabled providers
+ if (empty(self::$providerSettings[$providerSlug]['enabled'] ?? false)) {
+ continue;
+ }
+
+ // Rate-limit check
+ if (self::isRateLimited($event, $recipientId, $providerSlug)) {
+ continue;
+ }
+
+ $providerClass = self::$providerClasses[$providerSlug] ?? null;
+
+ if (!$providerClass || !class_exists($providerClass)) {
+ continue;
+ }
+
+ try {
+ $providerSettings = array_key_exists($providerSlug, self::$providerSettings) ? self::$providerSettings[$providerSlug] : [];
+
+ // Per-event named webhook selection: pass which of the globally defined
+ // webhooks (plus any free-form URLs) apply to this event
+ if ($providerSlug === 'webhooks') {
+ $providerSettings['_selected'] = $eventConfig['additional_webhooks'];
+ }
+
+ $result = $providerClass::send($event, $envelope, $providerSettings);
+
+ if ($result) {
+ self::recordRateLimit($event, $recipientId, $providerSlug);
+ }
+ } catch (\Throwable $e) {
+ // Log but never let one provider block others
+ if (function_exists('error_log')) {
+ error_log("[Vvveb Notifications] Provider '$providerSlug' failed for event '$event': " . $e->getMessage());
+ }
+ }
+ }
+ }
+
+ Event::trigger(self::class, 'trigger:after', $event, $data);
+ }
+
+ // ── Recipient resolution ───────────────────────────────────────────
+
+ /**
+ * Resolve all recipients for an event from config + data.
+ *
+ * @param string $event
+ * @param array<array-key, mixed> $eventConfig
+ * @param array<array-key, mixed> $data
+ *
+ * @return list<array{id?: string, name?: string, email?: string, phone?: string}>
+ */
+ private static function resolveRecipients(string $event, array $eventConfig, array $data): array {
+ $recipients = [];
+
+ // Explicit "to" override replaces auto-resolved targets (additional_* still append)
+ if (!empty($data['to'])) {
+ $eventConfig['recipients'] = [];
+
+ foreach ((array)$data['to'] as $toEmail) {
+ $recipients[] = ['id' => 'to:' . $toEmail, 'email' => $toEmail];
+ }
+ }
+
+ $recipientTargets = $eventConfig['recipients'] ?? ['site_admin'];
+ $site = \Vvveb\siteSettings();
+ $siteEmail = $site['contact-email'] ?? $site['admin-email'] ?? '';
+ $siteName = is_array($site['description'] ?? null)
+ ? ($site['description']['title'] ?? '')
+ : ($site['description'] ?? '');
+
+ foreach ($recipientTargets as $target) {
+ switch ($target) {
+ case 'site_admin':
+ $recipients[] = [
+ 'id' => 'site_admin',
+ 'name' => $siteName,
+ 'email' => $siteEmail,
+ ];
+ break;
+
+ case 'user':
+ // The subject of the event (customer/user)
+ $source = self::payloadSubject($data);
+ $userEmail = $source['email'] ?? '';
+ $userName = trim(($source['first_name'] ?? '') . ' ' . ($source['last_name'] ?? ''));
+ $userName = $userName ?: ($source['username'] ?? '');
+ $userPhone = $source['phone'] ?? $source['telephone'] ?? '';
+
+ if ($userEmail) {
+ $recipients[] = [
+ 'id' => 'user:' . $userEmail,
+ 'name' => $userName,
+ 'email' => $userEmail,
+ 'phone' => $userPhone,
+ ];
+ }
+ break;
+
+ case 'admin_user':
+ // The specific admin/staff user tied to the record
+ $adminEmail = $data['admin_email'] ?? $data['author_email'] ?? '';
+ $adminName = $data['admin_name'] ?? $data['author_name'] ?? '';
+
+ if (!$adminEmail && ($admin = self::payloadSubject($data, 'admin')) && !empty($admin['email'])) {
+ $adminEmail = $admin['email'];
+ $adminName = $adminName ?: trim(($admin['first_name'] ?? '') . ' ' . ($admin['last_name'] ?? ''));
+ }
+
+ if ($adminEmail) {
+ $recipients[] = [
+ 'id' => 'admin_user:' . $adminEmail,
+ 'name' => $adminName,
+ 'email' => $adminEmail,
+ ];
+ }
+ break;
+ }
+ }
+
+ // Additional emails
+ foreach ($eventConfig['additional_emails'] ?? [] as $email) {
+ $email = trim($email);
+
+ if ($email) {
+ $recipients[] = [
+ 'id' => 'extra_email:' . $email,
+ 'name' => '',
+ 'email' => $email,
+ ];
+ }
+ }
+
+ // Additional phones
+ foreach ($eventConfig['additional_phones'] ?? [] as $phone) {
+ $phone = trim($phone);
+
+ if ($phone) {
+ $recipients[] = [
+ 'id' => 'extra_phone:' . $phone,
+ 'name' => '',
+ 'phone' => $phone,
+ ];
+ }
+ }
+
+ return $recipients;
+ }
+
+ /**
+ * Extract the subject record (user/customer/order...) from a payload.
+ * Looks into common nested keys first, falls back to top-level keys.
+ *
+ * @param array<array-key, mixed> $data Event payload
+ * @param string $kind Preferred nested key ('user', 'customer', 'admin', ...)
+ *
+ * @return array<array-key, mixed>
+ */
+ private static function payloadSubject(array $data, string $kind = 'user'): array {
+ foreach ([$kind, 'customer', 'user', 'order', 'post', 'admin'] as $key) {
+ if (isset($data[$key]) && is_array($data[$key])) {
+ return $data[$key];
+ }
+ }
+
+ return $data;
+ }
+
+ // ── Provider bootstrap ─────────────────────────────────────────────
+
+ /**
+ * Load available providers and settings from config. Called once per request on first trigger.
+ */
+ private static function boot(): void {
+ if (self::$booted) {
+ return;
+ }
+
+ self::$booted = true;
+
+ // Make sure all built-in events are registered even if trigger() is the
+ // first entry point (registration is idempotent)
+ self::registerDefaults();
+
+ // Load provider settings from config
+ $config = \Vvveb\config('notifications', []);
+
+ self::$providerSettings = $config['providers'] ?? [];
+ self::$eventSettings = $config['events'] ?? [];
+
+ // Load built-in providers
+ self::$providerClasses = [
+ 'email' => Notifications\Providers\Email::class,
+ 'sms' => Notifications\Providers\Sms::class,
+ 'slack' => Notifications\Providers\Slack::class,
+ 'whatsapp' => Notifications\Providers\Whatsapp::class,
+ 'telegram' => Notifications\Providers\Telegram::class,
+ 'webhooks' => Notifications\Providers\Webhooks::class,
+ ];
+
+ // Let plugins register additional providers (same pattern as payment gateways)
+ $availableProviders = [];
+ [$availableProviders] = Event::trigger('Vvveb\Notifications\Providers', 'register', $availableProviders);
+
+ foreach ($availableProviders as $slug => $class) {
+ if (!isset(self::$providerClasses[$slug])) {
+ self::$providerClasses[$slug] = $class;
+ }
+ }
+ }
+
+ /**
+ * Get all available provider classes (built-in + plugin-registered).
+ *
+ * @return array<string, class-string<Notifications\Providers\Provider>>
+ */
+ public static function getProviderClasses(): array {
+ self::boot();
+
+ return self::$providerClasses;
+ }
+
+ /**
+ * Get provider settings from config.
+ *
+ * @return array<string, array{enabled: bool, ...}>
+ */
+ public static function getProviderSettings(): array {
+ self::boot();
+
+ return self::$providerSettings;
+ }
+
+ /**
+ * Get event routing settings from config.
+ *
+ * @return array<string, array{providers: string[], recipients: string[], ...}>
+ */
+ public static function getEventSettings(): array {
+ self::boot();
+
+ return self::$eventSettings;
+ }
+
+ // ── Rate limiting ──────────────────────────────────────────────────
+
+ /**
+ * Check whether an event should be suppressed due to rate limiting.
+ *
+ * @param string $event
+ * @param string $recipientId
+ * @param string $provider
+ */
+ private static function isRateLimited(string $event, string $recipientId, string $provider): bool {
+ $key = "$event.$recipientId.$provider";
+
+ if (!isset(self::$rateLimits[$key])) {
+ // Load from cache/store
+ $lastSent = self::loadRateLimit($event, $recipientId, $provider);
+ self::$rateLimits[$key] = $lastSent;
+ }
+
+ $cooldown = self::getCooldown($event, $provider);
+
+ if ($cooldown > 0 && self::$rateLimits[$key] > 0) {
+ $elapsed = time() - self::$rateLimits[$key];
+
+ if ($elapsed < $cooldown) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Record that a notification was sent for rate-limiting purposes.
+ *
+ * @param string $event
+ * @param string $recipientId
+ * @param string $provider
+ */
+ private static function recordRateLimit(string $event, string $recipientId, string $provider): void {
+ $key = "$event.$recipientId.$provider";
+ $now = time();
+ self::$rateLimits[$key] = $now;
+
+ // Persist to cache
+ $cacheKey = "notification_ratelimit.$event.$recipientId.$provider";
+
+ try {
+ $cache = Cache::getInstance();
+ $cache->set($cacheKey, 'notification', $now, 86400); // 24h TTL
+ } catch (\Throwable $e) {
+ // Best-effort — in-memory is fine as fallback
+ }
+ }
+
+ /**
+ * Load last-sent timestamp from cache.
+ *
+ * @param string $event
+ * @param string $recipientId
+ * @param string $provider
+ */
+ private static function loadRateLimit(string $event, string $recipientId, string $provider): int {
+ try {
+ $cacheKey = "notification_ratelimit.$event.$recipientId.$provider";
+ $cache = Cache::getInstance();
+ $lastSent = $cache->get($cacheKey, 'notification');
+
+ return is_int($lastSent) ? $lastSent : 0;
+ } catch (\Throwable $e) {
+ return 0;
+ }
+ }
+
+ /**
+ * Get cooldown window in seconds for a provider.
+ *
+ * @param string $event
+ * @param string $provider
+ */
+ private static function getCooldown(string $event, string $provider): int {
+ // Per-event cooldown wins over everything else
+ $eventCooldown = self::$eventSettings[$event]['cooldown'] ?? null;
+
+ if ($eventCooldown !== null && $eventCooldown !== '') {
+ return max(0, (int)$eventCooldown);
+ }
+
+ // Per-provider cooldown from config
+ $providerCooldown = self::$providerSettings[$provider]['cooldown'] ?? null;
+
+ if ($providerCooldown !== null) {
+ return (int)$providerCooldown;
+ }
+
+ // Global cooldown
+ $globalCooldown = self::$providerSettings['global']['cooldown'] ?? null;
+
+ if ($globalCooldown !== null) {
+ return (int)$globalCooldown;
+ }
+
+ // Defaults: email=no cooldown, SMS/Slack/WhatsApp/webhooks=1 hour
+ $defaults = [
+ 'email' => 0,
+ 'sms' => 3600,
+ 'slack' => 3600,
+ 'whatsapp' => 3600,
+ 'telegram' => 3600,
+ 'webhooks' => 0,
+ ];
+
+ return $defaults[$provider] ?? 3600;
+ }
+
+ // ── Registration of all built-in events ────────────────────────────
+
+ /**
+ * Register all built-in notification events. Call once during bootstrap.
+ */
+ public static function registerDefaults(): void {
+ // ── Content — Posts ──
+ self::register('post.added', ['description' => 'A post is created', 'category' => 'content']);
+ self::register('post.edited', ['description' => 'A post is edited', 'category' => 'content']);
+ self::register('post.deleted', ['description' => 'A post is deleted', 'category' => 'content']);
+ self::register('post.published', ['description' => 'A post is published', 'category' => 'content', 'default_recipients' => ['admin_user']]);
+ self::register('post.unpublished', ['description' => 'A post is unpublished', 'category' => 'content', 'default_recipients' => ['admin_user']]);
+ self::register('post.scheduled', ['description' => 'A post is scheduled', 'category' => 'content', 'default_recipients' => ['admin_user']]);
+ self::register('post.unscheduled', ['description' => 'A post schedule is cancelled', 'category' => 'content', 'default_recipients' => ['admin_user']]);
+ self::register('post.rescheduled', ['description' => 'A post schedule time is changed', 'category' => 'content', 'default_recipients' => ['admin_user']]);
+ self::register('post.tag.attached', ['description' => 'A tag is attached to a post', 'category' => 'content']);
+ self::register('post.tag.detached', ['description' => 'A tag is detached from a post', 'category' => 'content']);
+
+ // ── Content — Pages ──
+ self::register('page.added', ['description' => 'A page is created', 'category' => 'content']);
+ self::register('page.edited', ['description' => 'A page is edited', 'category' => 'content']);
+ self::register('page.deleted', ['description' => 'A page is deleted', 'category' => 'content']);
+ self::register('page.published', ['description' => 'A page is published', 'category' => 'content', 'default_recipients' => ['admin_user']]);
+ self::register('page.published.edited', ['description' => 'An already-published page is edited', 'category' => 'content', 'default_recipients' => ['admin_user']]);
+ self::register('page.unpublished', ['description' => 'A page is unpublished', 'category' => 'content', 'default_recipients' => ['admin_user']]);
+ self::register('page.scheduled', ['description' => 'A page is scheduled', 'category' => 'content', 'default_recipients' => ['admin_user']]);
+ self::register('page.unscheduled', ['description' => 'A page schedule is cancelled', 'category' => 'content', 'default_recipients' => ['admin_user']]);
+ self::register('page.rescheduled', ['description' => 'A page schedule time is changed', 'category' => 'content', 'default_recipients' => ['admin_user']]);
+ self::register('page.tag.attached', ['description' => 'A tag is attached to a page', 'category' => 'content']);
+ self::register('page.tag.detached', ['description' => 'A tag is detached from a page', 'category' => 'content']);
+
+ // ── Content — Tags & site ──
+ self::register('tag.added', ['description' => 'A tag is created', 'category' => 'content']);
+ self::register('tag.edited', ['description' => 'A tag is edited', 'category' => 'content']);
+ self::register('tag.deleted', ['description' => 'A tag is deleted', 'category' => 'content']);
+ self::register('site.changed', ['description' => 'Site content or setting changes', 'category' => 'content']);
+
+ // ── Users ──
+ self::register('user.signup', ['description' => 'A new user self-registers', 'category' => 'users', 'default_recipients' => ['user', 'site_admin']]);
+ self::register('user.added', ['description' => 'A user is created by admin', 'category' => 'users', 'default_recipients' => ['site_admin']]);
+ self::register('user.edited', ['description' => 'A user account is edited', 'category' => 'users', 'default_recipients' => ['site_admin']]);
+ self::register('user.deleted', ['description' => 'A user is deleted', 'category' => 'users', 'default_recipients' => ['site_admin']]);
+
+ // Migrated from legacy direct mail() password-reset flows
+ self::register('user.password_reset', ['description' => 'A storefront user requests a password reset', 'category' => 'users']);
+ self::register('admin.password_reset', ['description' => 'An admin user requests a password reset', 'category' => 'system']);
+
+ // ── Commerce — Products ──
+ self::register('product.added', ['description' => 'A product is created', 'category' => 'commerce']);
+ self::register('product.edited', ['description' => 'A product is edited', 'category' => 'commerce']);
+ self::register('product.deleted', ['description' => 'A product is deleted', 'category' => 'commerce']);
+ self::register('product.lowstock', ['description' => 'A product stock falls below threshold', 'category' => 'commerce']);
+
+ // ── Commerce — Orders ──
+ self::register('order.new', ['description' => 'A customer places a new order', 'category' => 'commerce', 'default_recipients' => ['user', 'site_admin']]);
+ self::register('order.added', ['description' => 'An order is created by admin', 'category' => 'commerce', 'default_recipients' => ['site_admin']]);
+ self::register('order.deleted', ['description' => 'An order is deleted', 'category' => 'commerce', 'default_recipients' => ['site_admin']]);
+ self::register('order.status_change', ['description' => 'An order status changes', 'category' => 'commerce', 'default_recipients' => ['user', 'site_admin']]);
+
+ // ── Engagement — Comments, reviews & questions ──
+ self::register('comment.added', ['description' => 'A new comment is posted', 'category' => 'engagement', 'default_recipients' => ['admin_user']]);
+ self::register('comment.edited', ['description' => 'A comment is edited', 'category' => 'engagement', 'default_recipients' => ['admin_user']]);
+ self::register('comment.deleted', ['description' => 'A comment is deleted', 'category' => 'engagement', 'default_recipients' => ['admin_user']]);
+ self::register('product.review.added', ['description' => 'A new product review is submitted', 'category' => 'engagement', 'default_recipients' => ['admin_user']]);
+ self::register('product.review.deleted', ['description' => 'A product review is deleted', 'category' => 'engagement', 'default_recipients' => ['admin_user']]);
+ self::register('product.question.added', ['description' => 'A new product question is submitted', 'category' => 'engagement', 'default_recipients' => ['admin_user']]);
+ self::register('product.question.answered', ['description' => 'A product question receives an answer', 'category' => 'engagement', 'default_recipients' => ['admin_user']]);
+
+ // ── Commerce — Subscriptions & payments ──
+ self::register('subscription.add', ['description' => 'A customer starts a subscription', 'category' => 'commerce', 'default_recipients' => ['user', 'site_admin']]);
+ self::register('subscription.cancel', ['description' => 'A subscription is cancelled', 'category' => 'commerce', 'default_recipients' => ['user', 'site_admin']]);
+ self::register('payment.failed', ['description' => 'A payment attempt fails', 'category' => 'commerce', 'default_recipients' => ['user', 'site_admin']]);
+ self::register('payment.refunded', ['description' => 'A payment is refunded', 'category' => 'commerce', 'default_recipients' => ['user', 'site_admin']]);
+ self::register('order.return', ['description' => 'A customer initiates a return', 'category' => 'commerce', 'default_recipients' => ['user', 'site_admin']]);
+
+ // ── Media ──
+ self::register('media.new', ['description' => 'A new media file is uploaded', 'category' => 'media', 'default_recipients' => ['site_admin']]);
+ self::register('media.delete', ['description' => 'A media file is deleted', 'category' => 'media', 'default_recipients' => ['site_admin']]);
+
+ // ── Plugins & themes ──
+ self::register('plugin.add', ['description' => 'A plugin is installed', 'category' => 'system', 'default_recipients' => ['site_admin']]);
+ self::register('plugin.delete', ['description' => 'A plugin is uninstalled', 'category' => 'system', 'default_recipients' => ['site_admin']]);
+ self::register('plugin.activate', ['description' => 'A plugin is activated', 'category' => 'system', 'default_recipients' => ['site_admin']]);
+ self::register('plugin.deactivate', ['description' => 'A plugin is deactivated', 'category' => 'system', 'default_recipients' => ['site_admin']]);
+ self::register('theme.add', ['description' => 'A theme is installed', 'category' => 'system', 'default_recipients' => ['site_admin']]);
+ self::register('theme.delete', ['description' => 'A theme is deleted', 'category' => 'system', 'default_recipients' => ['site_admin']]);
+ self::register('theme.activate', ['description' => 'A theme is activated', 'category' => 'system', 'default_recipients' => ['site_admin']]);
+
+ // ── Other ──
+ self::register('contact-form.message', ['description' => 'A contact form message is received', 'category' => 'other']);
+ self::register('cronjob.fail', ['description' => 'A scheduled cron job fails', 'category' => 'system', 'default_recipients' => ['site_admin']]);
+ self::register('php.fatal_error', ['description' => 'A PHP fatal error occurs', 'category' => 'system', 'default_recipients' => ['site_admin']]);
+
+ // ── System — Queue ──
+ self::register('queue.job.failed', ['description' => 'A background queue job fails permanently', 'category' => 'system', 'default_recipients' => ['site_admin']]);
+
+ // Let plugins register their own notification events
+ Event::trigger(self::class, 'register');
+ }
+
+ // ── Admin helpers ──────────────────────────────────────────────────
+
+ /**
+ * Get events grouped by category for admin display.
+ *
+ * @return array<string, list<array{event: string, description: string, category: string, default_recipients: string[]}>>
+ */
+ public static function getEventsGrouped(): array {
+ $grouped = [];
+
+ foreach (self::$events as $event => $config) {
+ $category = $config['category'];
+
+ if (!isset($grouped[$category])) {
+ $grouped[$category] = [];
+ }
+
+ $grouped[$category][] = [
+ 'event' => $event,
+ 'description' => $config['description'],
+ 'category' => $category,
+ 'default_recipients' => $config['default_recipients'] ?? ['site_admin'],
+ ];
+ }
+
+ return $grouped;
+ }
+}
diff --git a/system/notifications/providers/email.php b/system/notifications/providers/email.php
new file mode 100644
index 0000000..1c88292
--- /dev/null
+++ b/system/notifications/providers/email.php
@@ -0,0 +1,83 @@
+<?php
+
+/**
+ * Vvveb
+ *
+ * Copyright (C) 2022 Ziadin Givan
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+namespace Vvveb\System\Notifications\Providers;
+
+/**
+ * Email notification provider — sends via the existing Vvveb email system.
+ */
+class Email implements Provider {
+ /**
+ * Send an email notification.
+ *
+ * @param string $event The notification event name
+ * @param array<array-key, mixed> $data The full notification envelope
+ * @param array<array-key, mixed> $settings Provider settings
+ *
+ * @return bool
+ */
+ public static function send(string $event, array $data, array $settings): bool {
+ $recipient = $data['recipient'] ?? [];
+ $to = $recipient['email'] ?? '';
+
+ if (!$to) {
+ return false;
+ }
+
+ $subject = $data['subject'] ?? $event;
+ $message = $data['message'] ?? '';
+ $html = $data['data']['html'] ?? $message;
+ $txt = $data['data']['txt'] ?? strip_tags($message);
+ $siteId = $data['data']['site_id'] ?? SITE_ID;
+
+ return \Vvveb\email(
+ $to,
+ $subject,
+ ['html' => $html, 'txt' => $txt],
+ $data['data'] ?? [],
+ [],
+ null,
+ $siteId
+ );
+ }
+
+ /**
+ * Settings fields for admin — email reuses existing settings so returns minimal fields.
+ */
+ public static function settingsFields(): array {
+ return [
+ [
+ 'type' => 'toggle',
+ 'name' => 'enabled',
+ 'label' => 'Enable Email Notifications',
+ 'description' => 'Send notifications via email using the site email settings',
+ ],
+ [
+ 'type' => 'number',
+ 'name' => 'cooldown',
+ 'label' => 'Cooldown (seconds)',
+ 'description' => 'Minimum seconds between identical notifications (0 = no cooldown)',
+ 'placeholder' => '0',
+ ],
+ ];
+ }
+}
diff --git a/system/notifications/providers/provider.php b/system/notifications/providers/provider.php
new file mode 100644
index 0000000..5638bdf
--- /dev/null
+++ b/system/notifications/providers/provider.php
@@ -0,0 +1,46 @@
+<?php
+
+/**
+ * Vvveb
+ *
+ * Copyright (C) 2022 Ziadin Givan
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+namespace Vvveb\System\Notifications\Providers;
+
+/**
+ * Interface that all notification providers must implement.
+ */
+interface Provider {
+ /**
+ * Send a notification for the given event.
+ *
+ * @param string $event The notification event name
+ * @param array<array-key, mixed> $data The full notification envelope
+ * @param array<array-key, mixed> $settings Provider-specific settings from config
+ *
+ * @return bool True on success, false on failure
+ */
+ public static function send(string $event, array $data, array $settings): bool;
+
+ /**
+ * Return field definitions for the admin settings tab.
+ *
+ * @return list<array{type: string, name: string, label: string, description?: string, placeholder?: string}>
+ */
+ public static function settingsFields(): array;
+}
diff --git a/system/notifications/providers/slack.php b/system/notifications/providers/slack.php
new file mode 100644
index 0000000..f3f0018
--- /dev/null
+++ b/system/notifications/providers/slack.php
@@ -0,0 +1,170 @@
+<?php
+
+/**
+ * Vvveb
+ *
+ * Copyright (C) 2022 Ziadin Givan
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+namespace Vvveb\System\Notifications\Providers;
+
+/**
+ * Slack notification provider — sends via Incoming Webhook URL.
+ */
+class Slack implements Provider {
+ /**
+ * Send a Slack notification.
+ *
+ * @param string $event The notification event name
+ * @param array<array-key, mixed> $data The full notification envelope
+ * @param array<array-key, mixed> $settings Provider settings (webhook_url, channel)
+ *
+ * @return bool
+ */
+ public static function send(string $event, array $data, array $settings): bool {
+ $webhookUrl = $settings['webhook_url'] ?? '';
+
+ if (!$webhookUrl) {
+ return false;
+ }
+
+ $recipient = $data['recipient'] ?? [];
+ $subject = $data['subject'] ?? $event;
+ $message = $data['message'] ?? '';
+ $siteName = $data['data']['site_name'] ?? \Vvveb\config('site.name', 'Vvveb');
+
+ // Build Slack message payload.
+ // Header blocks are capped at 150 chars and section text at 3000 by the
+ // Slack API — longer values get the whole request rejected with 400
+ $subject = mb_substr($subject, 0, 150);
+
+ $blocks = [
+ [
+ 'type' => 'header',
+ 'text' => [
+ 'type' => 'plain_text',
+ 'text' => $subject,
+ 'emoji' => true,
+ ],
+ ],
+ ];
+
+ if ($message) {
+ $blocks[] = [
+ 'type' => 'section',
+ 'text' => [
+ 'type' => 'mrkdwn',
+ 'text' => mb_substr($message, 0, 3000),
+ ],
+ ];
+ }
+
+ // Add recipient info if available
+ $recipientName = $recipient['name'] ?? $recipient['email'] ?? '';
+
+ if ($recipientName) {
+ $blocks[] = [
+ 'type' => 'context',
+ 'elements' => [
+ [
+ 'type' => 'mrkdwn',
+ 'text' => "👤 Recipient: $recipientName",
+ ],
+ ],
+ ];
+ }
+
+ // Per-event channel override (e.g. route different events to different channels)
+ $channel = $recipient['channel'] ?? ($settings['channel'] ?? '');
+
+ $payload = [
+ 'username' => $siteName . ' Notifications',
+ 'icon_emoji' => ':bell:',
+ 'blocks' => $blocks,
+ ];
+
+ // Empty channel falls back to the webhook's configured default
+ if (!empty($channel)) {
+ $payload['channel'] = $channel;
+ }
+
+ $json = json_encode($payload);
+
+ $ch = curl_init($webhookUrl);
+
+ curl_setopt_array($ch, [
+ CURLOPT_POST => true,
+ CURLOPT_POSTFIELDS => $json,
+ CURLOPT_RETURNTRANSFER => true,
+ CURLOPT_TIMEOUT => 10,
+ CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
+ ]);
+
+ $response = curl_exec($ch);
+ $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+ curl_close($ch);
+
+ if ($httpCode !== 200 || !is_string($response)) {
+ return false;
+ }
+
+ $response = trim($response);
+
+ // Incoming webhooks answer plain "ok" on success; some responses are JSON {"ok":true}
+ if ($response === 'ok') {
+ return true;
+ }
+
+ $body = json_decode($response, true);
+
+ return is_array($body) && !empty($body['ok']);
+ }
+
+ /**
+ * Settings fields for admin.
+ */
+ public static function settingsFields(): array {
+ return [
+ [
+ 'type' => 'toggle',
+ 'name' => 'enabled',
+ 'label' => 'Enable Slack Notifications',
+ 'description' => 'Send notifications to Slack via Incoming Webhook',
+ ],
+ [
+ 'type' => 'url',
+ 'name' => 'webhook_url',
+ 'label' => 'Webhook URL',
+ 'placeholder' => 'https://hooks.slack.com/services/xxx/yyy/zzz',
+ 'description' => 'Create an Incoming Webhook in your Slack workspace settings',
+ ],
+ [
+ 'type' => 'text',
+ 'name' => 'channel',
+ 'label' => 'Channel',
+ 'placeholder' => '#notifications (optional — uses webhook default)',
+ ],
+ [
+ 'type' => 'number',
+ 'name' => 'cooldown',
+ 'label' => 'Cooldown (seconds)',
+ 'description' => 'Minimum seconds between identical notifications (default: 3600)',
+ 'placeholder' => '3600',
+ ],
+ ];
+ }
+}
diff --git a/system/notifications/providers/sms.php b/system/notifications/providers/sms.php
new file mode 100644
index 0000000..e7a322c
--- /dev/null
+++ b/system/notifications/providers/sms.php
@@ -0,0 +1,124 @@
+<?php
+
+/**
+ * Vvveb
+ *
+ * Copyright (C) 2022 Ziadin Givan
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+namespace Vvveb\System\Notifications\Providers;
+
+/**
+ * SMS notification provider — sends via HTTP API (Twilio-style).
+ */
+class Sms implements Provider {
+ /**
+ * Send an SMS notification.
+ *
+ * @param string $event The notification event name
+ * @param array<array-key, mixed> $data The full notification envelope
+ * @param array<array-key, mixed> $settings Provider settings (sid, token, from)
+ *
+ * @return bool
+ */
+ public static function send(string $event, array $data, array $settings): bool {
+ $recipient = $data['recipient'] ?? [];
+ $phone = $recipient['phone'] ?? '';
+
+ if (!$phone) {
+ return false;
+ }
+
+ $sid = $settings['sid'] ?? '';
+ $token = $settings['token'] ?? '';
+ $from = $settings['from'] ?? '';
+
+ if (!$sid || !$token || !$from) {
+ return false;
+ }
+
+ // Use message body or fall back to subject
+ $message = $data['message'] ?? $data['subject'] ?? $event;
+
+ // Trim to 1600 chars for SMS (concatenated SMS limit)
+ $message = mb_substr($message, 0, 1600);
+
+ $apiUrl = "https://api.twilio.com/2010-04-01/Accounts/$sid/Messages.json";
+
+ $body = http_build_query([
+ 'To' => $phone,
+ 'From' => $from,
+ 'Body' => $message,
+ ]);
+
+ $ch = curl_init($apiUrl);
+
+ curl_setopt_array($ch, [
+ CURLOPT_POST => true,
+ CURLOPT_POSTFIELDS => $body,
+ CURLOPT_RETURNTRANSFER => true,
+ CURLOPT_TIMEOUT => 30,
+ CURLOPT_USERPWD => "$sid:$token",
+ CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
+ ]);
+
+ $response = curl_exec($ch);
+ $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+ curl_close($ch);
+
+ return $httpCode >= 200 && $httpCode < 300;
+ }
+
+ /**
+ * Settings fields for admin.
+ */
+ public static function settingsFields(): array {
+ return [
+ [
+ 'type' => 'toggle',
+ 'name' => 'enabled',
+ 'label' => 'Enable SMS Notifications',
+ 'description' => 'Send notifications via SMS',
+ ],
+ [
+ 'type' => 'text',
+ 'name' => 'sid',
+ 'label' => 'Account SID',
+ 'placeholder' => 'Your Twilio Account SID',
+ ],
+ [
+ 'type' => 'password',
+ 'name' => 'token',
+ 'label' => 'Auth Token',
+ 'placeholder' => 'Your Twilio Auth Token',
+ ],
+ [
+ 'type' => 'text',
+ 'name' => 'from',
+ 'label' => 'From Number',
+ 'placeholder' => '+1234567890',
+ ],
+ [
+ 'type' => 'number',
+ 'name' => 'cooldown',
+ 'label' => 'Cooldown (seconds)',
+ 'description' => 'Minimum seconds between identical notifications (default: 3600)',
+ 'placeholder' => '3600',
+ ],
+ ];
+ }
+}
diff --git a/system/notifications/providers/telegram.php b/system/notifications/providers/telegram.php
new file mode 100644
index 0000000..612c928
--- /dev/null
+++ b/system/notifications/providers/telegram.php
@@ -0,0 +1,131 @@
+<?php
+
+/**
+ * Vvveb
+ *
+ * Copyright (C) 2022 Ziadin Givan
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+namespace Vvveb\System\Notifications\Providers;
+
+/**
+ * Telegram notification provider — sends messages via the Telegram Bot API.
+ */
+class Telegram implements Provider {
+ /**
+ * Send a Telegram message.
+ *
+ * @param string $event The notification event name
+ * @param array<array-key, mixed> $data The full notification envelope
+ * @param array<array-key, mixed> $settings Provider settings (bot_token, chat_id)
+ *
+ * @return bool
+ */
+ public static function send(string $event, array $data, array $settings): bool {
+ $botToken = $settings['bot_token'] ?? '';
+ $chatId = $settings['chat_id'] ?? '';
+
+ if (!$botToken || !$chatId) {
+ return false;
+ }
+
+ $subject = $data['subject'] ?? $event;
+ $message = $data['message'] ?? '';
+
+ // HTML parse mode: escape content so arbitrary payloads can't break the API call
+ $text = '<b>' . htmlspecialchars($subject, ENT_QUOTES, 'UTF-8', false) . '</b>';
+
+ if ($message !== '') {
+ $text .= "\n\n" . htmlspecialchars((string)$message, ENT_QUOTES, 'UTF-8', false);
+ }
+
+ // Telegram message limit is 4096 characters
+ $text = mb_substr($text, 0, 4096);
+
+ $payload = [
+ 'chat_id' => $chatId,
+ 'text' => $text,
+ 'parse_mode' => 'HTML',
+ 'disable_web_page_preview' => true,
+ ];
+
+ // Per-event chat override (e.g. different channels per notification type)
+ if (!empty($data['recipient']['chat_id'])) {
+ $payload['chat_id'] = $data['recipient']['chat_id'];
+ }
+
+ $apiUrl = "https://api.telegram.org/bot{$botToken}/sendMessage";
+
+ $ch = curl_init($apiUrl);
+
+ curl_setopt_array($ch, [
+ CURLOPT_POST => true,
+ CURLOPT_POSTFIELDS => json_encode($payload),
+ CURLOPT_RETURNTRANSFER => true,
+ CURLOPT_TIMEOUT => 30,
+ CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
+ ]);
+
+ $response = curl_exec($ch);
+ $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+ curl_close($ch);
+
+ if ($httpCode !== 200 || !is_string($response)) {
+ return false;
+ }
+
+ // Telegram answers {"ok":true,...} on success
+ $body = json_decode($response, true);
+
+ return is_array($body) && !empty($body['ok']);
+ }
+
+ /**
+ * Settings fields for admin.
+ */
+ public static function settingsFields(): array {
+ return [
+ [
+ 'type' => 'toggle',
+ 'name' => 'enabled',
+ 'label' => 'Enable Telegram Notifications',
+ 'description' => 'Send notifications via a Telegram bot',
+ ],
+ [
+ 'type' => 'password',
+ 'name' => 'bot_token',
+ 'label' => 'Bot Token',
+ 'placeholder' => '123456789:AAF...',
+ 'description' => 'Create a bot with @BotFather and copy its token',
+ ],
+ [
+ 'type' => 'text',
+ 'name' => 'chat_id',
+ 'label' => 'Chat ID',
+ 'placeholder' => '@channelname or -1001234567890',
+ 'description' => 'Target chat, group or channel ID. Add the bot to the chat first; get the ID from @userinfobot or getUpdates',
+ ],
+ [
+ 'type' => 'number',
+ 'name' => 'cooldown',
+ 'label' => 'Cooldown (seconds)',
+ 'description' => 'Minimum seconds between identical notifications (default: 3600)',
+ 'placeholder' => '3600',
+ ],
+ ];
+ }
+}
diff --git a/system/notifications/providers/webhooks.php b/system/notifications/providers/webhooks.php
new file mode 100644
index 0000000..31ce3e9
--- /dev/null
+++ b/system/notifications/providers/webhooks.php
@@ -0,0 +1,236 @@
+<?php
+
+/**
+ * Vvveb
+ *
+ * Copyright (C) 2022 Ziadin Givan
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+namespace Vvveb\System\Notifications\Providers;
+
+/**
+ * Webhook notification provider — sends POST/PUT/GET requests to user-defined endpoints.
+ *
+ * Multiple named webhook endpoints can be defined. Each defined webhook
+ * becomes a selectable provider option per event (e.g. "My CRM webhook").
+ * The per-event routing selects which named webhooks to fire.
+ */
+class Webhooks implements Provider {
+ /**
+ * Send a webhook notification to a specific endpoint.
+ *
+ * For per-event routing, $settings['webhooks'] should contain the named webhooks,
+ * and $data['data']['_webhook_name'] identifies which webhook to fire.
+ *
+ * @param string $event The notification event name
+ * @param array<array-key, mixed> $data The full notification envelope
+ * @param array<array-key, mixed> $settings Provider settings including 'webhooks' array
+ *
+ * @return bool
+ */
+ public static function send(string $event, array $data, array $settings): bool {
+ $webhooks = $settings['webhooks'] ?? [];
+ $target = $data['data']['_webhook_name'] ?? '';
+ // Per-event selection: list of globally defined webhook names and/or free-form URLs
+ $selected = array_filter((array)($settings['_selected'] ?? []), fn ($s) => $s !== '');
+ unset($settings['_selected']);
+
+ if (!$webhooks && !$selected) {
+ return false;
+ }
+
+ if (!empty($selected)) {
+ // Send only to the webhooks selected for this event; entries that are not
+ // names of defined webhooks are treated as ad-hoc endpoint URLs
+ $names = [];
+ $extraUrls = [];
+
+ foreach ($selected as $sel) {
+ if (str_starts_with($sel, 'http://') || str_starts_with($sel, 'https://')) {
+ $extraUrls[] = ['url' => $sel, 'method' => 'POST', 'enabled' => true];
+ } else {
+ $names[] = $sel;
+ }
+ }
+
+ $success = true;
+ $sent = false;
+
+ foreach ($webhooks as $wh) {
+ if (in_array($wh['name'] ?? '', $names, true) && !empty($wh['enabled'])) {
+ $result = self::sendToWebhook($wh, $event, $data);
+ $sent = true;
+
+ if (!$result) {
+ $success = false;
+ }
+ }
+ }
+
+ foreach ($extraUrls as $wh) {
+ $result = self::sendToWebhook($wh, $event, $data);
+ $sent = true;
+
+ if (!$result) {
+ $success = false;
+ }
+ }
+
+ return $sent ? $success : false;
+ }
+
+ // If a specific webhook is targeted, send only to that one
+ if ($target) {
+ foreach ($webhooks as $wh) {
+ if (($wh['name'] ?? '') === $target && !empty($wh['enabled'])) {
+ return self::sendToWebhook($wh, $event, $data);
+ }
+ }
+
+ return false;
+ }
+
+ // Otherwise send to all enabled webhooks
+ $success = true;
+
+ foreach ($webhooks as $wh) {
+ if (!empty($wh['enabled'])) {
+ $result = self::sendToWebhook($wh, $event, $data);
+
+ if (!$result) {
+ $success = false;
+ }
+ }
+ }
+
+ return $success;
+ }
+
+ /**
+ * Send a single webhook request.
+ *
+ * @param array<array-key, mixed> $webhook
+ * @param string $event
+ * @param array<array-key, mixed> $data
+ */
+ private static function sendToWebhook(array $webhook, string $event, array $data): bool {
+ $url = $webhook['url'] ?? '';
+ $method = strtoupper($webhook['method'] ?? 'POST');
+ $headers = $webhook['headers'] ?? [];
+
+ if (!$url) {
+ return false;
+ }
+
+ // Build payload
+ $payload = $data;
+ unset($payload['data']['_webhook_name']); // internal routing key, not for external use
+
+ // Convert headers string to array
+ $headerArr = ['Content-Type: application/json'];
+
+ if (is_string($headers)) {
+ // Parse "Key: Value\nKey2: Value2" format
+ $lines = array_filter(array_map('trim', explode("\n", $headers)));
+
+ foreach ($lines as $line) {
+ if (str_contains($line, ':')) {
+ $headerArr[] = $line;
+ }
+ }
+ } elseif (is_array($headers)) {
+ foreach ($headers as $key => $value) {
+ $headerArr[] = "$key: $value";
+ }
+ }
+
+ $jsonPayload = json_encode($payload);
+
+ $ch = curl_init($url);
+
+ curl_setopt_array($ch, [
+ CURLOPT_CUSTOMREQUEST => $method,
+ CURLOPT_POSTFIELDS => $jsonPayload,
+ CURLOPT_RETURNTRANSFER => true,
+ CURLOPT_TIMEOUT => 30,
+ CURLOPT_HTTPHEADER => $headerArr,
+ ]);
+
+ $response = curl_exec($ch);
+ $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+ curl_close($ch);
+
+ return $httpCode >= 200 && $httpCode < 300;
+ }
+
+ /**
+ * Settings fields for admin — webhooks have a dynamic list of named endpoints.
+ */
+ public static function settingsFields(): array {
+ return [
+ [
+ 'type' => 'toggle',
+ 'name' => 'enabled',
+ 'label' => 'Enable Webhook Notifications',
+ 'description' => 'Send notifications to HTTP webhook endpoints',
+ ],
+ [
+ 'type' => 'list',
+ 'name' => 'webhooks',
+ 'label' => 'Webhook Endpoints',
+ 'description' => 'Define named webhook endpoints that can be selected per notification event',
+ 'fields' => [
+ [
+ 'type' => 'toggle',
+ 'name' => 'enabled',
+ 'label' => 'Enabled',
+ ],
+ [
+ 'type' => 'text',
+ 'name' => 'name',
+ 'label' => 'Name',
+ 'placeholder' => 'My Webhook',
+ ],
+ [
+ 'type' => 'url',
+ 'name' => 'url',
+ 'label' => 'URL',
+ 'placeholder' => 'https://example.com/webhook',
+ ],
+ [
+ 'type' => 'select',
+ 'name' => 'method',
+ 'label' => 'HTTP Method',
+ 'options' => [
+ 'POST' => 'POST',
+ 'PUT' => 'PUT',
+ 'PATCH' => 'PATCH',
+ 'GET' => 'GET',
+ ],
+ ],
+ [
+ 'type' => 'textarea',
+ 'name' => 'headers',
+ 'label' => 'Custom Headers',
+ 'placeholder' => "X-Api-Key: my-key\nX-Custom: value",
+ 'description' => 'One header per line, format: Key: Value',
+ ],
+ ],
+ ],
+ ];
+ }
+}
diff --git a/system/notifications/providers/whatsapp.php b/system/notifications/providers/whatsapp.php
new file mode 100644
index 0000000..03ab307
--- /dev/null
+++ b/system/notifications/providers/whatsapp.php
@@ -0,0 +1,132 @@
+<?php
+
+/**
+ * Vvveb
+ *
+ * Copyright (C) 2022 Ziadin Givan
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+namespace Vvveb\System\Notifications\Providers;
+
+/**
+ * WhatsApp Business API notification provider.
+ */
+class Whatsapp implements Provider {
+ /**
+ * Send a WhatsApp message notification.
+ *
+ * @param string $event The notification event name
+ * @param array<array-key, mixed> $data The full notification envelope
+ * @param array<array-key, mixed> $settings Provider settings (api_url, token, from)
+ *
+ * @return bool
+ */
+ public static function send(string $event, array $data, array $settings): bool {
+ $recipient = $data['recipient'] ?? [];
+ $phone = $recipient['phone'] ?? '';
+
+ if (!$phone) {
+ return false;
+ }
+
+ $apiUrl = $settings['api_url'] ?? '';
+ $token = $settings['token'] ?? '';
+ $from = $settings['from'] ?? '';
+
+ if (!$apiUrl || !$token) {
+ return false;
+ }
+
+ $subject = $data['subject'] ?? $event;
+ $message = $data['message'] ?? $subject;
+
+ // Normalize phone number (remove spaces, dashes)
+ $phone = preg_replace('/[^\d+]/', '', $phone);
+
+ // WhatsApp Business API payload (v16+ Cloud API format)
+ $payload = [
+ 'messaging_product' => 'whatsapp',
+ 'to' => $phone,
+ 'type' => 'text',
+ 'text' => [
+ 'preview_url' => false,
+ 'body' => "*$subject*\n\n$message",
+ ],
+ ];
+
+ $headers = [
+ 'Authorization: Bearer ' . $token,
+ 'Content-Type: application/json',
+ ];
+
+ $ch = curl_init($apiUrl);
+
+ curl_setopt_array($ch, [
+ CURLOPT_POST => true,
+ CURLOPT_POSTFIELDS => json_encode($payload),
+ CURLOPT_RETURNTRANSFER => true,
+ CURLOPT_TIMEOUT => 30,
+ CURLOPT_HTTPHEADER => $headers,
+ ]);
+
+ $response = curl_exec($ch);
+ $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+ curl_close($ch);
+
+ return $httpCode >= 200 && $httpCode < 300;
+ }
+
+ /**
+ * Settings fields for admin.
+ */
+ public static function settingsFields(): array {
+ return [
+ [
+ 'type' => 'toggle',
+ 'name' => 'enabled',
+ 'label' => 'Enable WhatsApp Notifications',
+ 'description' => 'Send notifications via WhatsApp Business API',
+ ],
+ [
+ 'type' => 'url',
+ 'name' => 'api_url',
+ 'label' => 'API URL',
+ 'placeholder' => 'https://graph.facebook.com/v17.0/YOUR_PHONE_ID/messages',
+ 'description' => 'WhatsApp Cloud API endpoint URL',
+ ],
+ [
+ 'type' => 'password',
+ 'name' => 'token',
+ 'label' => 'API Token',
+ 'placeholder' => 'Your WhatsApp Business API token',
+ ],
+ [
+ 'type' => 'text',
+ 'name' => 'from',
+ 'label' => 'From Phone Number ID',
+ 'placeholder' => 'Your WhatsApp Business Phone Number ID',
+ ],
+ [
+ 'type' => 'number',
+ 'name' => 'cooldown',
+ 'label' => 'Cooldown (seconds)',
+ 'description' => 'Minimum seconds between identical notifications (default: 3600)',
+ 'placeholder' => '3600',
+ ],
+ ];
+ }
+}
diff --git a/system/page-cache.php b/system/page-cache.php
index 6cda94e..79968cc 100644
--- a/system/page-cache.php
+++ b/system/page-cache.php
@@ -22,124 +22,279 @@
namespace Vvveb\System;
-use function Vvveb\globBrace;
+use function Vvveb\rrmdir;
use Vvveb\System\Core\FrontController;
+/**
+ * Full-page static cache.
+ *
+ * Serves responses from flat HTML files keyed by request URI, with a
+ * lock/stale protocol so visitors get fresh-enough content while pages
+ * regenerate: existing cache is renamed to ".old" (served while locked),
+ * generation is guarded by a ".new" lock file, and non-200 responses
+ * discard both instead of caching errors.
+ */
class PageCache {
- const STALE_EXT = '.old';
+ public const STALE_EXT = '.old';
+
+ public const LOCK_EXT = '.new';
- const LOCK_EXT = '.new';
+ public const CACHE_DIR = PAGE_CACHE_DIR;
- const CACHE_DIR = PAGE_CACHE_DIR;
+ public const MAX_LOCK_SECONDS = 10;
- const MAX_LOCK_SECONDS = 10;
+ /** @var string File name used for directory-style URIs. */
+ public const INDEX_FILE = 'index.html';
- static $cacheCookies = ['user', 'cart', 'admin', 'nocache'];
+ /** @var int Maximum URI length eligible for caching. */
+ public const MAX_URI_LENGTH = 300;
- private $fileName;
+ /** @var int Base directory permissions (further restricted by umask). */
+ public const DIR_MODE = 0755;
- private $uri;
+ /** @var string[] URI prefixes that are never cached. */
+ public const BLOCKED_PATHS = ['/user', '/cart', '/checkout', '/feed'];
- private $canCache; //can serve cached page
+ /** @var string[] Cookie names that disable caching. */
+ public static array $cacheCookies = ['user', 'cart', 'admin', 'nocache'];
- private $canSaveCache; //can save page in cache
+ /** @var ?string Full path to the cache file. */
+ private ?string $fileName = null;
- private $cacheFolder;
+ /** @var ?string Request URI being cached. */
+ private ?string $uri = null;
- static private $enabled;
+ /** @var ?bool Whether the current request may be served from cache. */
+ private ?bool $canCache = null;
- static private $instance;
+ /** @var ?bool Whether the current response may be saved to cache. */
+ private ?bool $canSaveCache = null;
- static function getInstance() {
- if (! self :: $instance) {
- self :: $instance = new self();
+ /** @var string Absolute path to the host-specific cache folder. */
+ private string $cacheFolder = '';
+
+ /** @var bool Whether caching is globally enabled. */
+ private static bool $enabled = true;
+
+ /** @var ?self Singleton instance. */
+ private static ?self $instance = null;
+
+ /**
+ * Return the singleton PageCache instance.
+ *
+ * @return self
+ */
+ public static function getInstance(): self {
+ if (!self::$instance) {
+ self::$instance = new self();
}
- return self :: $instance;
+ return self::$instance;
}
- function __construct($host = null) {
+ /**
+ * @param ?string $host Optional hostname override.
+ */
+ public function __construct(?string $host = null) {
$this->cacheFolder = $this->cacheFolder($host);
$this->uri = $this->uri();
if ($this->uri) {
- $this->fileName = $this->cacheFolder . $this->uri;
+ $this->fileName = $this->cacheFolder . $this->uri;
}
- //$this->canSaveCache = $this->canSaveCache();
}
- function cacheFolder($host) {
- $host = $host ?? $_SERVER['HTTP_HOST'] ?? '';
- $hostWp = substr($host, 0, strpos($host, ':') ?: null);
+ /**
+ * Build the absolute cache folder path for the given host.
+ *
+ * @param ?string $host Hostname, or null to use $_SERVER['HTTP_HOST'].
+ *
+ * @return string
+ */
+ public function cacheFolder(?string $host = null): string {
+ $host ??= $_SERVER['HTTP_HOST'] ?? '';
+
+ //strip the port component (e.g. "example.com:8080" -> "example.com")
+ $pos = strpos($host, ':');
+ $hostWp = $pos === false ? $host : substr($host, 0, $pos);
- return DIR_PUBLIC . self :: CACHE_DIR . ($hostWp ?? 'default');
+ //fall back to "default" when no host is available (e.g. CLI)
+ $hostWp = $hostWp ?: 'default';
+
+ return DIR_PUBLIC . self::CACHE_DIR . $hostWp;
}
- function uri($url = null) {
+ /**
+ * Normalise and validate a request URI for caching.
+ *
+ * @param ?string $url URI to validate, or null to use $_SERVER['REQUEST_URI'].
+ *
+ * @return string|false The normalised URI, or false if the URI is too long
+ * or contains control characters.
+ */
+ public function uri(?string $url = null): string|false {
$uri = $url ?? $_SERVER['REQUEST_URI'] ?? '/';
- if (strlen($uri) > 300) {
+ if (strlen($uri) > self::MAX_URI_LENGTH) {
+ return false;
+ }
+
+ //reject control characters and null bytes - they have no place in a path
+ if (preg_match('/[\x00-\x1f\x7f]/', $uri)) {
return false;
}
if (substr($uri, -1) == '/') {
- $uri .= 'index.html';
+ $uri .= self::INDEX_FILE;
}
return $uri;
}
- function isGenerating() {
- return is_file($this->fileName . self :: LOCK_EXT);
+ /**
+ * Path of the lock file marking an in-progress generation.
+ *
+ * @return string
+ */
+ private function lockFile(): string {
+ return $this->fileName . self::LOCK_EXT;
}
- function isGeneratingStuck() {
- return time() - filemtime($this->fileName . self :: LOCK_EXT) > self :: MAX_LOCK_SECONDS;
+ /**
+ * Path of the stale (previous-generation) cache file.
+ *
+ * @return string
+ */
+ private function staleFile(): string {
+ return $this->fileName . self::STALE_EXT;
}
- function isStale() {
- return is_file($this->fileName . self :: STALE_EXT);
+ /**
+ * Append the index file name when the cached path is a directory.
+ *
+ * Mutates $this->fileName so subsequent calls in the same request
+ * operate on the resolved path.
+ *
+ * @return string The resolved cache file path.
+ */
+ private function resolveIndexFileName(): string {
+ if (is_dir($this->fileName)) {
+ $this->fileName .= DS . self::INDEX_FILE;
+ }
+
+ return $this->fileName;
}
- function getStale() {
- return $this->fileName . self :: STALE_EXT;
+ /**
+ * Create a directory (and parents), removing a colliding cached page
+ * file that blocks the directory path.
+ *
+ * @param string $dir Directory to create.
+ *
+ * @return bool True on success.
+ */
+ private function ensureDirectory(string $dir): bool {
+ if (is_dir($dir)) {
+ return true;
+ }
+
+ //if a page with the same name as the folder exists remove it
+ if (file_exists($dir)) {
+ unlink($dir);
+ }
+
+ return (bool)@mkdir($dir, (self::DIR_MODE & ~umask()), true);
}
- function startGenerating() {
- $dir = dirname($this->fileName);
+ /**
+ * Check whether a cache file is currently being generated (lock exists).
+ *
+ * @return bool
+ */
+ public function isGenerating(): bool {
+ return is_file($this->lockFile());
+ }
- if (is_dir($this->fileName)) {
- $this->fileName .= DS . 'index.html';
+ /**
+ * Check whether the generation lock has exceeded MAX_LOCK_SECONDS.
+ *
+ * @return bool False when no lock exists (generation finished or never started).
+ */
+ public function isGeneratingStuck(): bool {
+ $lock = $this->lockFile();
+
+ //no lock file means generation already finished (or never started)
+ if (!is_file($lock)) {
+ return false;
}
- if (! is_dir($dir)) {
- //if page with the same name as folder remove
- if (file_exists($dir)) {
- unlink($dir);
- }
+ return time() - (filemtime($lock) ?: time()) > self::MAX_LOCK_SECONDS;
+ }
- if (! mkdir($dir, (0755 & ~umask()), true)) {
- return false;
- }
+ /**
+ * Check whether a stale (old) cache file exists.
+ *
+ * @return bool
+ */
+ public function isStale(): bool {
+ return is_file($this->staleFile());
+ }
+
+ /**
+ * Return the path to the stale cache file.
+ *
+ * @return string
+ */
+ public function getStale(): string {
+ return $this->staleFile();
+ }
+
+ /**
+ * Prepare directories and lock file for a new cache generation.
+ *
+ * Moves any existing cache file to the stale slot so it can be served
+ * while the new version generates.
+ *
+ * @return bool True on success, false if directory creation fails.
+ */
+ public function startGenerating(): bool {
+ $dir = dirname($this->fileName);
+
+ $this->resolveIndexFileName();
+
+ if (!$this->ensureDirectory($dir)) {
+ return false;
}
//keep old cache to serve while generating
if (file_exists($this->fileName)) {
- rename($this->fileName, $this->fileName . self :: STALE_EXT);
+ rename($this->fileName, $this->staleFile());
}
- return touch($this->fileName . self :: LOCK_EXT);
+ return touch($this->lockFile());
}
- function startCapture() {
+ /**
+ * Start output buffering for cache capture.
+ *
+ * @return void
+ */
+ public function startCapture(): void {
ob_start();
}
- function validUrl($url) {
+ /**
+ * Validate that a URL is safe for caching.
+ *
+ * @param string $url The URL to validate.
+ *
+ * @return bool True if the URL is valid for caching.
+ */
+ public function validUrl(string $url): bool {
//no ?&\ or .. in the url and the number of levels should not exceed 4
- $invalid = strpbrk($url, '?&\\') || (strpos($url, '..') !== false) || (substr_count($url,'/') > 4);
+ $invalid = strpbrk($url, '?&\\') || (str_contains($url, '..')) || (substr_count($url, '/') > 4);
- if (! $invalid) {
- foreach (['/user', '/cart', '/checkout', '/feed'] as $a) {
+ if (!$invalid) {
+ foreach (self::BLOCKED_PATHS as $a) {
if (strncmp($url, $a, strlen($a)) === 0) {
$invalid = true;
@@ -148,23 +303,32 @@ class PageCache {
}
}
- return ! $invalid;
+ return !$invalid;
}
- function canCache() {
- if ($this->canCache !== NULL) {
+ /**
+ * Determine whether the current request may be served from cache.
+ *
+ * @return bool
+ */
+ public function canCache(): bool {
+ if ($this->canCache !== null) {
return $this->canCache;
}
- if (! $this->uri ||
+ if (self::$enabled === false) {
+ return $this->canCache = false;
+ }
+
+ if (!$this->uri ||
APP == 'admin' || //no cache for admin
APP == 'install' || //no cache for install
- ! empty($_POST) || //forms posts
- isset($_COOKIE['nocache']) || //cookie set by plugin
+ !empty($_POST) || //forms posts
+ (isset($_COOKIE['nocache'])) || //cookie set by plugin
isset($_COOKIE['cart']) || // cookie set by add to cart
isset($_COOKIE['user']) || //cookie set by login
isset($_COOKIE['admin']) || //cookie set by admin login
- ! $this->validUrl($this->uri) //valid url
+ !$this->validUrl($this->uri) //valid url
) {
return $this->canCache = false;
}
@@ -172,12 +336,19 @@ class PageCache {
return $this->canCache = true;
}
- function canSaveCache() {
- if ($this->canSaveCache !== NULL) {
+ /**
+ * Determine whether the current response may be saved to cache.
+ *
+ * Only anonymous visitors' responses are cached.
+ *
+ * @return bool
+ */
+ public function canSaveCache(): bool {
+ if ($this->canSaveCache !== null) {
return $this->canSaveCache;
}
- if (! $this->canCache ||
+ if (!$this->canCache ||
($user = \Vvveb\System\User\User::current()) || //not logged in
($admin = \Vvveb\System\User\Admin::current())) {
return $this->canSaveCache = false;
@@ -186,30 +357,59 @@ class PageCache {
return $this->canSaveCache = true;
}
- function hasCache() {
+ /**
+ * Check whether a cache file exists for the current request.
+ *
+ * @return bool
+ */
+ public function hasCache(): bool {
return is_file($this->fileName);
}
- function getCache() {
+ /**
+ * Output the cached file contents directly.
+ *
+ * @return int|false Number of bytes read (from readfile), or false if the
+ * cache file disappeared between hasCache() and this call.
+ */
+ public function getCache(): int|false {
+ if (!is_file($this->fileName)) {
+ return false;
+ }
+
return readfile($this->fileName);
}
- function cleanUp() {
- //remove lock and stale cache
- foreach ([$this->fileName . self :: LOCK_EXT,
- $this->fileName . self :: STALE_EXT, ] as $file) {
+ /**
+ * Remove lock and stale cache files.
+ *
+ * @return bool True if any file was removed, false otherwise.
+ */
+ public function cleanUp(): bool {
+ $removed = false;
+
+ foreach ([$this->lockFile(), $this->staleFile()] as $file) {
if (file_exists($file)) {
- return unlink($file);
+ $removed = @unlink($file) || $removed;
}
}
- return false;
+ return $removed;
}
- function saveCache() {
+ /**
+ * Save the current output buffer to the cache file.
+ *
+ * Non-200 responses discard the lock and stale files (a temporary error
+ * must not evict the last good cache) and prune the empty folders that
+ * were created for them.
+ *
+ * @return string|false The captured output, or false on directory-creation failure.
+ */
+ public function saveCache(): string|false {
$data = ob_get_contents();
- $lock = $this->fileName . self :: LOCK_EXT;
+ $lock = $this->lockFile();
//if page not found or server error don't cache
if (FrontController::getStatus() != 200) {
@@ -218,14 +418,21 @@ class PageCache {
unlink($lock);
}
+ //remove stale cache so a temporary error doesn't leave orphaned files
+ if (file_exists($this->staleFile())) {
+ @unlink($this->staleFile());
+ }
+
//remove all empty created folders
+ $file = $this->fileName;
+
while (
- ($dir = dirname($this->fileName)) &&
- (strpos($dir, $this->cacheFolder . DS) !== false) && //don't go above site cache folder
+ ($dir = dirname($file)) &&
+ (str_contains($dir, $this->cacheFolder . DS)) && //don't go above site cache folder
@rmdir($dir) //try to remove empty folder
) {
//go one level up
- $this->fileName = $dir;
+ $file = $dir;
}
return $data;
@@ -233,19 +440,13 @@ class PageCache {
if ($this->canSaveCache &&
$this->fileName && $data &&
- http_response_code() == 200) {
- //create directory structure
- if (is_dir($this->fileName)) {
- $this->fileName .= DS . 'index.html';
- }
+ http_response_code() == 200) { //status 200 already ensured above
+ $this->resolveIndexFileName();
- $dir = dirname($this->fileName);
-
- if (! file_exists($dir)) {
- if (! mkdir($dir, (0755 & ~umask()), true)) {
- return false;
- }
+ if (!$this->ensureDirectory(dirname($this->fileName))) {
+ return false;
}
+
//save cache
file_put_contents($this->fileName, $data);
//remove lock
@@ -254,61 +455,99 @@ class PageCache {
}
//remove stale
- if (file_exists($this->fileName . self :: STALE_EXT)) {
- @unlink($this->fileName . self :: STALE_EXT);
+ if (file_exists($this->staleFile())) {
+ @unlink($this->staleFile());
}
}
return $data;
}
- function purge($path = '/') {
+ /**
+ * Delete all cached files under the given path.
+ *
+ * @param string $path Relative path inside the cache folder.
+ *
+ * @return bool Always returns true.
+ */
+ public function purge(string $path = '/'): bool {
+ //reject paths that would escape the site cache folder
+ if (str_contains($path, '..') || strpbrk($path, "\0")) {
+ return false;
+ }
+
$folder = $this->cacheFolder . $path;
- $glob = ['', '*/*/', '*/'];
- //$files = glob($name, GLOB_BRACE);
- $files = globBrace($folder, $glob, '*');
+ return rrmdir($folder, [], true);
+ }
- if ($files) {
- foreach ($files as $file) {
- if ($file[0] === '.') {
- continue;
- }
+ /**
+ * Remove all expired cache files from the cache directory.
+ *
+ * A file is considered expired when its modification time is older than
+ * $expired seconds. Lock (.new) and stale (.old) files are removed as well
+ * once past their expiry.
+ *
+ * @param int $expired Expiry window in seconds.
+ *
+ * @return void
+ */
+ public function purgeExpired($expired = 1000): void {
+ ignore_user_abort(true);
+ rrmdir($this->cacheFolder, [], true, function($file) use ($expired): bool {
+ $time = filemtime($file);
+
+ return ($time + $expired) < time();
+ });
+ ignore_user_abort(false);
+ }
- if (is_file($file)) {
- if (! @unlink($file)) {
- clearstatcache(false, $file);
- }
- } else {
- /*
- if (! @rmdir($file)) {
- clearstatcache(false, $file);
- }
- */
- }
- }
+ /**
+ * Randomly trigger expired-cache cleanup on object destruction.
+ *
+ * There is a 1-in-1000 chance that purgeExpired() is called each time
+ * a File cache instance is destroyed, providing probabilistic garbage
+ * collection without requiring a cron job.
+ *
+ * @return void
+ */
+ public function __destruct() {
+ if (random_int(1, 1000) === 1) {
+ $this->purgeExpired();
}
-
- return true;
}
- static function enable($type = false) {
- $cookie = (in_array($type, self :: $cacheCookies) ? $type : 'nocache');
-
- if (! self :: $enabled && isset($_COOKIE[$cookie])) {
+ /**
+ * Enable caching, optionally for a specific cookie type.
+ *
+ * @param string|false $type Cookie name that controls caching, or false for default.
+ *
+ * @return void
+ */
+ public static function enable(string|false $type = false): void {
+ $cookie = (in_array($type, self::$cacheCookies) ? $type : 'nocache');
+
+ if (!self::$enabled && isset($_COOKIE[$cookie])) {
@setcookie($cookie, '', time() - 3600, '/');
}
- self :: $enabled = true;
+ self::$enabled = true;
}
- static function disable($type = false) {
- $cookie = (in_array($type, self :: $cacheCookies) ? $type : 'nocache');
-
- if (self :: $enabled && ! isset($_COOKIE[$cookie])) {
+ /**
+ * Disable caching, optionally for a specific cookie type.
+ *
+ * @param string|false $type Cookie name that controls caching, or false for default.
+ *
+ * @return void
+ */
+ public static function disable(string|false $type = false): void {
+ $cookie = (in_array($type, self::$cacheCookies) ? $type : 'nocache');
+
+ if (self::$enabled && !isset($_COOKIE[$cookie])) {
@setcookie($cookie, '1', 0, '/');
}
- self :: $enabled = false;
+ self::$enabled = false;
}
}
diff --git a/system/payment-ledger.php b/system/payment-ledger.php
new file mode 100755
index 0000000..684a0a3
--- /dev/null
+++ b/system/payment-ledger.php
@@ -0,0 +1,90 @@
+<?php
+
+/**
+ * Vvveb
+ *
+ * Copyright (C) 2022 Ziadin Givan
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+namespace Vvveb\System;
+
+/**
+ * Money-event ledger: one chronological row per funds movement.
+ *
+ */
+class PaymentLedger {
+ /**
+ * Append a ledger row. Never throws.
+ *
+ * @param array<string, mixed> $data order_id, kind (authorize, capture,
+ * purchase, void, refund, renewal),
+ * gateway, reference, amount, currency,
+ * status (succeeded, failed, pending),
+ * note, tax_amount (tax portion of the
+ * movement, 0 when unknown).
+ *
+ * @return int|null Insert id or null when skipped/failed.
+ */
+ public static function record(array $data): ?int {
+ try {
+ $orderId = (int)($data['order_id'] ?? 0);
+
+ if (!$orderId) {
+ return null;
+ }
+
+ $result = \Vvveb\model('order_transaction')->add(['transaction' => [
+ 'order_id' => $orderId,
+ 'kind' => substr((string)($data['kind'] ?? ''), 0, 32),
+ 'gateway' => substr((string)($data['gateway'] ?? ''), 0, 64),
+ 'reference' => substr((string)($data['reference'] ?? ''), 0, 191),
+ 'amount' => round((float)($data['amount'] ?? 0), 4),
+ 'tax_amount' => round(max(0, (float)($data['tax_amount'] ?? 0)), 4),
+ 'currency' => substr(strtoupper((string)($data['currency'] ?? '')), 0, 3),
+ 'status' => substr((string)($data['status'] ?? ''), 0, 32),
+ 'note' => isset($data['note']) ? mb_substr((string)$data['note'], 0, 1000) : '',
+ ]]);
+
+ $id = (int)($result['order_transaction'] ?? 0);
+
+ return $id ?: null;
+ } catch (\Throwable $e) {
+ return null;
+ }
+ }
+
+ /**
+ * Ledger rows for an order, oldest first. Never throws.
+ *
+ * @param int|string $orderId Order id.
+ *
+ * @return array<int, array<string, mixed>> Transaction rows.
+ */
+ public static function forOrder(int|string $orderId): array {
+ try {
+ $results = \Vvveb\model('order_transaction')->getByOrder([
+ 'order_id' => (int)$orderId,
+ 'start' => 0,
+ 'limit' => 500,
+ ]);
+
+ return $results['order_transaction'] ?? [];
+ } catch (\Throwable $e) {
+ return [];
+ }
+ }
+}
diff --git a/system/payment-method.php b/system/payment-method.php
index e5e0f1e..417532d 100755
--- a/system/payment-method.php
+++ b/system/payment-method.php
@@ -22,18 +22,616 @@
namespace Vvveb\System;
+use Vvveb\System\Cart\Order;
+
abstract class PaymentMethod {
- protected $cart;
+ /** @var object Cart instance. */
+ protected object $cart;
+
+ /** Purchase/authorize completed synchronously. */
+ public const STATUS_SUCCESS = 'success';
+
+ /** Customer must be redirected off-site (3DS, hosted page); core performs the redirect. */
+ public const STATUS_REDIRECT = 'redirect';
+
+ /** Operation failed, see getError(). */
+ public const STATUS_FAILED = 'failed';
- function __construct($cart) {
+ /** @var string|null Last failure reason, set via fail(). */
+ private ?string $error = null;
+
+ /** @var string|null Off-site redirect target, set via redirect(). */
+ private ?string $redirectUrl = null;
+
+ /**
+ * @param object $cart Cart instance.
+ */
+ public function __construct(object $cart) {
$this->cart = $cart;
}
- abstract public function init();
+ /**
+ * Initialize the payment method.
+ *
+ * @return void
+ */
+ abstract public function init(): void;
+
+ /**
+ * Get payment method details and options.
+ *
+ * @param array<string, mixed> &$checkoutInfo Checkout information passed by reference.
+ * @param array<string, mixed> $options Method-specific options.
+ *
+ * @return array<string, mixed>|false Method data or false if unavailable.
+ */
+ abstract public function getMethod(array &$checkoutInfo = [], array $options = []): array|false;
+
+ /**
+ * Set the active payment method.
+ *
+ * @return void
+ */
+ abstract public function setMethod(): void;
+
+ /**
+ * Check whether this method implements an operation.
+ *
+ * Only overridden operations count: inherited no-op stubs report false,
+ * so admin buttons and capability checks stay accurate without
+ * per-method declarations.
+ *
+ * @param string $operation One of authorize, capture, completeAuthorize,
+ * purchase, completePurchase, refund, void,
+ * createCard, webhook.
+ *
+ * @return bool True if the concrete class overrides the operation.
+ */
+ public function supports(string $operation): bool {
+ $method = match ($operation) {
+ 'authorize' => 'authorize',
+ 'capture' => 'capture',
+ 'completeAuthorize' => 'completeAuthorize',
+ 'purchase' => 'purchase',
+ 'completePurchase' => 'completePurchase',
+ 'refund' => 'refund',
+ 'void' => 'void',
+ 'createCard' => 'createCard',
+ 'webhook' => 'webhook',
+ 'createSubscription' => 'createSubscription',
+ 'cancelSubscription' => 'cancelSubscription',
+ 'pauseSubscription' => 'pauseSubscription',
+ 'resumeSubscription' => 'resumeSubscription',
+ 'swapSubscription' => 'swapSubscription',
+ 'skipSubscription' => 'skipSubscription',
+ 'retrySubscriptionPayment' => 'retrySubscriptionPayment',
+ default => null,
+ };
+
+ if ($method === null) {
+ return false;
+ }
+
+ try {
+ $reflection = new \ReflectionMethod($this, $method);
+
+ return $reflection->getDeclaringClass()->getName() !== self::class;
+ } catch (\ReflectionException $e) {
+ return false;
+ }
+ }
+
+ /**
+ * Get the last failure reason.
+ *
+ * @return string|null Error message or null when the last operation succeeded.
+ */
+ public function getError(): ?string {
+ return $this->error;
+ }
+
+ /**
+ * Get the off-site redirect target set via redirect().
+ *
+ * @return string|null Redirect URL or null when no redirect was requested.
+ */
+ public function getRedirectUrl(): ?string {
+ return $this->redirectUrl;
+ }
+
+ /**
+ * Record a failure reason and return false for convenience.
+ *
+ * @param string $message Human readable failure reason.
+ *
+ * @return bool Always false.
+ */
+ protected function fail(string $message): bool {
+ $this->error = $message;
+
+ return false;
+ }
+
+ /**
+ * Request an off-site redirect instead of exiting inside the method.
+ *
+ * Returned to core, which persists payment data and performs the
+ * redirect, keeping order creation and events in one place.
+ *
+ * @param string $url Redirect target.
+ *
+ * @return array{status: string, redirect: string} Redirect result.
+ */
+ protected function redirect(string $url): array {
+ $this->redirectUrl = $url;
+
+ return ['status' => self::STATUS_REDIRECT, 'redirect' => $url];
+ }
+
+ /**
+ * Zero-decimal currencies (Stripe list): amounts are already in minor
+ * units, multiplying by 100 would overcharge 100x.
+ *
+ * @var array<int, string>
+ */
+ public const ZERO_DECIMAL_CURRENCIES = ['BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'UGX', 'VND', 'VUV', 'XAF', 'XOF', 'XPF'];
+
+ /**
+ * Check whether a currency has no minor units.
+ *
+ * @param string|null $currency ISO currency code.
+ *
+ * @return bool True for zero-decimal currencies.
+ */
+ public static function isZeroDecimalCurrency(?string $currency): bool {
+ return $currency !== null && in_array(strtoupper($currency), self::ZERO_DECIMAL_CURRENCIES, true);
+ }
+
+ /**
+ * Convert a decimal total to integer minor units.
+ *
+ * @param mixed $total Decimal total.
+ * @param string|null $currency ISO currency code, 2 decimals assumed when unknown.
+ *
+ * @return int Minor units.
+ */
+ public static function toMinorUnits(mixed $total, ?string $currency = null): int {
+ $total = round((float)$total, 2);
+
+ if (self::isZeroDecimalCurrency($currency)) {
+ return (int)round($total);
+ }
+
+ return (int)round($total * 100);
+ }
+
+ /**
+ * Convert integer minor units back to a decimal total.
+ *
+ * @param int $minor Minor units.
+ * @param string|null $currency ISO currency code, 2 decimals assumed when unknown.
+ *
+ * @return float Decimal total.
+ */
+ public static function fromMinorUnits(int $minor, ?string $currency = null): float {
+ if (self::isZeroDecimalCurrency($currency)) {
+ return (float)$minor;
+ }
+
+ return round($minor / 100, 2);
+ }
+
+ /**
+ * Detect raw card numbers (PANs) in card data.
+ *
+ * Posting PANs to the store balloons PCI scope; card details must stay
+ * in hosted fields/tokens. Matches 13-19 digit runs, ignoring spaces
+ * and dashes.
+ *
+ * @param mixed $card Card data (array, string or nested).
+ *
+ * @return bool True when a PAN-like number is present.
+ */
+ protected function containsPan(mixed $card): bool {
+ if (is_array($card)) {
+ foreach ($card as $value) {
+ if ($this->containsPan($value)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ if (!is_scalar($card)) {
+ return false;
+ }
+
+ return (bool)preg_match('/\b(?:\d[\s-]?){13,19}\b/', (string)$card);
+ }
+
+ /**
+ * Append a money-ledger row for this operation. Never throws.
+ *
+ * @param string $kind Operation kind (authorize, capture,
+ * purchase, void, refund, renewal).
+ * @param array<string, mixed> $checkoutInfo Checkout information (order_id, total,
+ * currency).
+ * @param string $status Result status (succeeded, failed, pending).
+ * @param string $reference Gateway-side reference.
+ * @param string $note Optional note.
+ * @param string $gateway Gateway name, defaults to the
+ * checkout payment method.
+ *
+ * @return void
+ */
+ protected function recordLedger(string $kind, array $checkoutInfo, string $status, string $reference = '', string $note = '', string $gateway = ''): void {
+ if ($gateway === '') {
+ $gateway = (string)($checkoutInfo['payment_method'] ?? '');
+ }
+
+ \Vvveb\System\PaymentLedger::record([
+ 'order_id' => $checkoutInfo['order_id'] ?? 0,
+ 'kind' => $kind,
+ 'gateway' => $gateway,
+ 'reference' => $reference,
+ 'amount' => $checkoutInfo['amount'] ?? $checkoutInfo['total'] ?? 0,
+ 'tax_amount' => $checkoutInfo['tax_amount'] ?? 0,
+ 'currency' => $checkoutInfo['currency'] ?? '',
+ 'status' => $status,
+ 'note' => $note,
+ ]);
+ }
+
+ /**
+ * Partial-operation amount override from checkout info.
+ *
+ * `capture()` and `refund()` honor an `amount` key (partial capture /
+ * partial refund); when absent or invalid the full `total` applies.
+ *
+ * @param array<string, mixed> $checkoutInfo Checkout info, optional `amount`.
+ *
+ * @return float|null Positive amount override or null for the full total.
+ */
+ protected function partialAmount(array $checkoutInfo): ?float {
+ if (!isset($checkoutInfo['amount']) || !is_numeric($checkoutInfo['amount'])) {
+ return null;
+ }
+
+ $amount = (float)$checkoutInfo['amount'];
+
+ return $amount > 0 ? $amount : null;
+ }
+
+ /**
+ * Convert a decimal total to integer minor units (cents).
+ *
+ * @param mixed $total Decimal total.
+ *
+ * @return int Minor units.
+ */
+ protected function toCents(mixed $total): int {
+ return self::toMinorUnits($total);
+ }
+
+ /**
+ * Build an idempotency key for the current checkout.
+ *
+ * Pass it as the gateway transaction/invoice reference so retried
+ * submits (double click, back button) don't double-charge.
+ *
+ * @param array<string, mixed> $checkoutInfo Checkout information.
+ *
+ * @return string Idempotency key.
+ */
+ protected function idempotencyKey(array $checkoutInfo): string {
+ if (!empty($checkoutInfo['idempotency_key'])) {
+ return (string)$checkoutInfo['idempotency_key'];
+ }
+
+ return hash('sha256', implode('|', [
+ $checkoutInfo['order_id'] ?? '',
+ $checkoutInfo['payment_method'] ?? '',
+ number_format((float)($checkoutInfo['total'] ?? 0), 2, '.', ''),
+ $checkoutInfo['currency'] ?? '',
+ ]));
+ }
+
+ /**
+ * Read stored payment data, accepting the array or JSON string shapes
+ * used across checkout and admin contexts.
+ *
+ * @param array<string, mixed> $checkoutInfo Checkout information.
+ *
+ * @return array<string, mixed> Payment data.
+ */
+ protected function storedPaymentData(array $checkoutInfo): array {
+ $data = $checkoutInfo['payment_data'] ?? [];
+
+ if (is_string($data)) {
+ $data = json_decode($data, true);
+ }
+
+ return is_array($data) ? $data : [];
+ }
+
+ /**
+ * Store payment data on the checkout info and persist it to the order
+ * when an order id is available.
+ *
+ * @param array<string, mixed> $checkoutInfo Checkout information updated in place.
+ * @param array<string, mixed> $data Payment data to store.
+ * @param int|null $statusId Optional payment status id to persist.
+ *
+ * @return void
+ */
+ protected function storePaymentData(array &$checkoutInfo, array $data, ?int $statusId = null): void {
+ $checkoutInfo['payment_data'] = json_encode($data);
+ $order_id = $checkoutInfo['order_id'] ?? 0;
+
+ if (!$order_id) {
+ return;
+ }
+
+ $update = ['payment_data' => $checkoutInfo['payment_data']];
+
+ if ($statusId !== null) {
+ $update['payment_status_id'] = $statusId;
+ }
+
+ try {
+ Order::getInstance()->edit($update, $order_id);
+ } catch (\Throwable $e) {
+ //persistence failure is non-fatal, data is still in $checkoutInfo
+ }
+ }
+
+ /**
+ * Verify a webhook payload signature (HMAC-SHA256 helper).
+ *
+ * @param string $payload Raw request body.
+ * @param string $signature Signature header value (hex or base64).
+ * @param string $secret Webhook secret.
+ *
+ * @return bool True when the signature matches.
+ */
+ protected function verifyHmac(string $payload, string $signature, string $secret): bool {
+ if ($payload === '' || $signature === '' || $secret === '') {
+ return false;
+ }
+
+ $expected = hash_hmac('sha256', $payload, $secret);
+ $decoded = base64_decode($signature, true);
+
+ if ($decoded !== false && hash_equals($expected, bin2hex($decoded))) {
+ return true;
+ }
+
+ return hash_equals($expected, strtolower(trim($signature)));
+ }
+
+ /**
+ * Authorize the payment.
+ *
+ * @param array<string, mixed> &$checkoutInfo Checkout information passed by reference.
+ *
+ * @return bool|array{status: string, redirect?: string} True on success,
+ * redirect result for off-site authorization, false on failure.
+ */
+ public function authorize(array &$checkoutInfo = []): bool|array {
+ return false;
+ }
+
+ /**
+ * Capture the payment.
+ *
+ * @param array<string, mixed> &$checkoutInfo Checkout information passed by reference.
+ *
+ * @return bool True on success, false on failure (see getError()).
+ */
+ public function capture(array &$checkoutInfo = []): bool {
+ return false;
+ }
+
+ /**
+ * Complete authorize the payment.
+ *
+ * @param array<string, mixed> &$checkoutInfo Checkout information passed by reference.
+ *
+ * @return bool True on success, false on failure (see getError()).
+ */
+ public function completeAuthorize(array &$checkoutInfo = []): bool {
+ return false;
+ }
+
+ /**
+ * Purchase
+ *
+ * @param array<string, mixed> &$checkoutInfo Checkout information passed by reference.
+ *
+ * @return bool|array{status: string, redirect?: string} True on success,
+ * redirect result for off-site payments, false on failure.
+ */
+ public function purchase(array &$checkoutInfo = []): bool|array {
+ return false;
+ }
+
+ /**
+ * Complete purchase
+ *
+ * @param array<string, mixed> &$checkoutInfo Checkout information passed by reference.
+ *
+ * @return bool True on success, false on failure (see getError()).
+ */
+ public function completePurchase(array &$checkoutInfo = []): bool {
+ return false;
+ }
+
+ /**
+ * Refund the payment.
+ *
+ * @param array<string, mixed> &$checkoutInfo Checkout information passed by reference.
+ *
+ * @return bool True on success, false on failure (see getError()).
+ */
+ public function refund(array &$checkoutInfo = []): bool {
+ return false;
+ }
+
+ /**
+ * Cancel the payment.
+ *
+ * @param array<string, mixed> &$checkoutInfo Checkout information passed by reference.
+ *
+ * @return bool True on success, false on failure (see getError()).
+ */
+ public function void(array &$checkoutInfo = []): bool {
+ return false;
+ }
- abstract public function getMethod(&$checkoutInfo = [], $options = []);
+ /**
+ * Create a card reference for future payments.
+ *
+ * @param array<string, mixed> &$checkoutInfo Checkout information passed by reference.
+ *
+ * @return bool True on success, false on failure (see getError()).
+ */
+ public function createCard(array &$checkoutInfo = []): bool {
+ return false;
+ }
+
+ /**
+ * Handle an asynchronous gateway notification (webhook).
+ *
+ * Implementations must verify the payload signature, apply the status
+ * update idempotently and return false with getError() on failure.
+ * Core never calls this directly; plugin routes delegate to it so all
+ * drivers share one contract.
+ *
+ * @param array<string, mixed> &$checkoutInfo Checkout information passed by reference.
+ *
+ * @return bool True when the notification was handled.
+ */
+ public function webhook(array &$checkoutInfo = []): bool {
+ return false;
+ }
- abstract public function setMethod();
+ /**
+ * Resolve the gateway-side subscription reference for lifecycle operations.
+ *
+ * Controllers pass an explicit `gateway_subscription_id`; as a fallback
+ * the `payment_method` field stores `gateway:id` pairs (e.g. stripe:sub_1).
+ *
+ * @param array<string, mixed> $checkoutInfo Checkout/subscription information.
+ *
+ * @return string|null Gateway subscription id or null when not resolvable.
+ */
+ protected function gatewaySubscriptionId(array $checkoutInfo): ?string {
+ foreach (['gateway_subscription_id', 'subscription_reference'] as $key) {
+ if (!empty($checkoutInfo[$key])) {
+ return (string)$checkoutInfo[$key];
+ }
+ }
- abstract public function authorize();
+ $method = (string)($checkoutInfo['payment_method'] ?? '');
+
+ if (str_contains($method, ':')) {
+ $reference = substr($method, strpos($method, ':') + 1);
+
+ if ($reference !== '') {
+ return $reference;
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Create a subscription at the gateway.
+ *
+ * @param array<string, mixed> &$checkoutInfo Must carry the plan/customer context.
+ *
+ * @return bool True on success, false on failure (see getError()).
+ */
+ public function createSubscription(array &$checkoutInfo = []): bool {
+ return false;
+ }
+
+ /**
+ * Cancel a subscription at the gateway (immediate).
+ *
+ * @param array<string, mixed> &$checkoutInfo Must carry the gateway reference
+ * (see gatewaySubscriptionId()).
+ *
+ * @return bool True on success, false on failure (see getError()).
+ */
+ public function cancelSubscription(array &$checkoutInfo = []): bool {
+ return false;
+ }
+
+ /**
+ * Pause a subscription at the gateway.
+ *
+ * @param array<string, mixed> &$checkoutInfo Must carry the gateway reference.
+ *
+ * @return bool True on success, false on failure (see getError()).
+ */
+ public function pauseSubscription(array &$checkoutInfo = []): bool {
+ return false;
+ }
+
+ /**
+ * Resume a paused subscription at the gateway.
+ *
+ * @param array<string, mixed> &$checkoutInfo Must carry the gateway reference.
+ *
+ * @return bool True on success, false on failure (see getError()).
+ */
+ public function resumeSubscription(array &$checkoutInfo = []): bool {
+ return false;
+ }
+
+ /**
+ * Swap the price/plan of a subscription at the gateway.
+ *
+ * Price/plan edits deliberately do NOT propagate automatically:
+ * gateway prices are immutable, so swapping live subscriptions must stay
+ * an explicit per-subscription action.
+ *
+ * @param array<string, mixed> &$checkoutInfo Must carry the gateway reference
+ * plus `price_id` (or equivalent).
+ *
+ * @return bool True on success, false on failure (see getError()).
+ */
+ public function swapSubscription(array &$checkoutInfo = []): bool {
+ return false;
+ }
+
+ /**
+ * Skip the next billing of a subscription at the gateway (push the next
+ * payment out by one interval).
+ *
+ * @param array<string, mixed> &$checkoutInfo Must carry the gateway reference
+ * plus `delay_until` (unix timestamp).
+ *
+ * @return bool True on success, false on failure (see getError()).
+ */
+ public function skipSubscription(array &$checkoutInfo = []): bool {
+ return false;
+ }
+
+ /**
+ * Retry a failed subscription invoice payment at the gateway.
+ *
+ * Must be a no-op when the invoice is already paid (gateway smart
+ * retries may have recovered it) and report that as success.
+ *
+ * @param array<string, mixed> &$checkoutInfo Must carry the gateway reference
+ * plus `invoice_id`.
+ *
+ * @return bool True on success, false on failure (see getError()).
+ */
+ public function retrySubscriptionPayment(array &$checkoutInfo = []): bool {
+ return false;
+ }
}
diff --git a/system/payment.php b/system/payment.php
index 89c4cb7..e1677df 100755
--- a/system/payment.php
+++ b/system/payment.php
@@ -25,33 +25,50 @@ namespace Vvveb\System;
use Vvveb\System\Cart\Cart;
class Payment {
- private $driver;
+ /** @var array<string, array{0: string, 1: array<string, mixed>}> Registered payment methods. */
+ private array $methods = [];
- private $methods = [];
+ /** @var array<string, PaymentMethod> Instantiated payment method objects. */
+ private array $instances = [];
- private $instances = [];
+ /** @var PaymentMethod|null The currently active payment method instance. */
+ private ?PaymentMethod $instance = null;
- private $instance;
-
- public static function getInstance($options = []) {
+ /**
+ * Get singleton instance of the Payment class.
+ *
+ * @return self
+ */
+ public static function getInstance(): self {
static $inst = null;
if ($inst === null) {
- $inst = new Payment($options);
+ $inst = new self();
}
return $inst;
}
- public function __construct($options = []) {
- }
+ /**
+ * Constructor.
+ */
+ public function __construct() {}
- public function getMethods(&$checkoutInfo) {
+ /**
+ * Get all available payment methods and their data.
+ *
+ * @param array<string, mixed> &$checkoutInfo Checkout information passed by reference.
+ * @param ?object $cart
+ *
+ * @return array<string, array<string, mixed>> Available payment methods with data.
+ */
+ public function getMethods(array &$checkoutInfo, ?object $cart = null): array {
$data = [];
+ $cart ??= Cart::getInstance();
foreach ($this->methods as $name => $method) {
- list($class, $options) = $method;
- $obj = new $class(Cart::getInstance());
+ [$class, $options] = $method;
+ $obj = new $class($cart, $options);
$this->instances[$name] = $obj;
$paymentData = $obj->getMethod($checkoutInfo, $options);
//if payment method returns false or no data then don't add it to the list
@@ -63,11 +80,83 @@ class Payment {
return $data;
}
- public function registerMethod($method, $class, $options = []) {
+ /**
+ * Register a payment method.
+ *
+ * @param string $method Method identifier.
+ * @param string $class Fully-qualified class name.
+ * @param array<string, mixed> $options Method-specific options.
+ *
+ * @return void
+ */
+ public function registerMethod(string $method, string $class, array $options = []): void {
+ $options['class'] = $class;
$this->methods[$method] = [$class, $options];
}
- public function setMethod($method) {
+ /**
+ * Get a specific registered payment method instance by name.
+ * Instantiates the method on demand if it was not already created by getMethods().
+ *
+ * @param string $method Method identifier.
+ * @param ?object $cart
+ *
+ * @return PaymentMethod|null The method instance or null if the method is not registered.
+ */
+ public function getMethodInstance(string $method, ?object $cart = null): ?PaymentMethod {
+ if (isset($this->instances[$method])) {
+ return $this->instances[$method];
+ }
+
+ if (isset($this->methods[$method])) {
+ [$class, $options] = $this->methods[$method];
+ $obj = new $class($cart ?? Cart::getInstance(), $options);
+ $this->instances[$method] = $obj;
+
+ return $obj;
+ }
+
+ return null;
+ }
+
+ /**
+ * Get the last failure reason from the active method.
+ *
+ * @return string|null Error message or null when the last operation succeeded.
+ */
+ public function getError(): ?string {
+ return $this->instance?->getError();
+ }
+
+ /**
+ * Get the off-site redirect target requested by the active method.
+ *
+ * @return string|null Redirect URL or null when no redirect was requested.
+ */
+ public function getRedirectUrl(): ?string {
+ return $this->instance?->getRedirectUrl();
+ }
+
+ /**
+ * Check whether a registered method implements an operation.
+ *
+ * @param string $method Method identifier.
+ * @param string $operation Operation name (see PaymentMethod::supports()).
+ *
+ * @return bool True if the method supports the operation.
+ */
+ public function supports(string $method, string $operation): bool {
+ return (bool)$this->getMethodInstance($method)?->supports($operation);
+ }
+
+ /**
+ * Set the active payment method and initialize all methods.
+ *
+ * @param string $method Method identifier.
+ *
+ * @return void
+ */
+ public function setMethod(string $method): void {
foreach ($this->instances as $instance) {
$instance->init();
}
@@ -78,9 +167,166 @@ class Payment {
}
}
- public function authorize(&$checkoutInfo = []) {
+ /**
+ * Authorize the payment using the active method.
+ * authorize an amount on the customer's card
+ *
+ * @param array<string, mixed> &$checkoutInfo Checkout information passed by reference.
+ *
+ * @return bool|array{status: string, redirect?: string} Method result, use getError()/getRedirectUrl() for details.
+ */
+ public function authorize(array &$checkoutInfo = []): bool|array {
+ if ($this->instance) {
+ return $this->instance->authorize($checkoutInfo);
+ }
+
+ return false;
+ }
+
+ /**
+ * Authorize the payment using the active method.
+ * handle return from off-site gateways after authorization
+ *
+ * @param array<string, mixed> &$checkoutInfo Checkout information passed by reference.
+ *
+ * @return bool
+ */
+ public function completeAuthorize(array &$checkoutInfo = []): bool {
+ if ($this->instance) {
+ return $this->instance->completeAuthorize($checkoutInfo);
+ }
+
+ return false;
+ }
+
+ /**
+ * Capture the payment using the active method.
+ * capture an amount you have previously authorized
+ *
+ * @param array<string, mixed> &$checkoutInfo Checkout information passed by reference.
+ *
+ * @return bool
+ */
+ public function capture(array &$checkoutInfo = []): bool {
+ if ($this->instance) {
+ return $this->instance->capture($checkoutInfo);
+ }
+
+ return false;
+ }
+
+ /**
+ * Purchase the payment using the active method.
+ * authorize and immediately capture an amount on the customer's card
+ *
+ * @param array<string, mixed> &$checkoutInfo Checkout information passed by reference.
+ *
+ * @return bool|array{status: string, redirect?: string} Method result, use getError()/getRedirectUrl() for details.
+ */
+ public function purchase(array &$checkoutInfo = []): bool|array {
+ if ($this->instance) {
+ return $this->instance->purchase($checkoutInfo);
+ }
+
+ return false;
+ }
+
+ /**
+ * completePurchase the payment using the active method.
+ * handle return from off-site gateways after purchase
+ *
+ * @param array<string, mixed> &$checkoutInfo Checkout information passed by reference.
+ *
+ * @return bool
+ */
+ public function completePurchase(array &$checkoutInfo = []): bool {
+ if ($this->instance) {
+ return $this->instance->completePurchase($checkoutInfo);
+ }
+
+ return false;
+ }
+
+ /**
+ * Void/Cancel the payment using the active method.
+ * generally can only be called up to 24 hours after submitting a transaction
+ *
+ * @param array<string, mixed> &$checkoutInfo Checkout information passed by reference.
+ *
+ * @return bool
+ */
+ public function void(array &$checkoutInfo = []): bool {
+ if ($this->instance) {
+ return $this->instance->void($checkoutInfo);
+ }
+
+ return false;
+ }
+
+ /**
+ * Refund the payment using the active method.
+ * refund an already processed transaction
+ *
+ * @param array<string, mixed> &$checkoutInfo Checkout information passed by reference.
+ *
+ * @return bool
+ */
+ public function refund(array &$checkoutInfo = []): bool {
if ($this->instance) {
- $this->instance->authorize($checkoutInfo);
+ return $this->instance->refund($checkoutInfo);
+ }
+
+ return false;
+ }
+
+ /**
+ * createCard
+ * get a cardReference that can be used for future payments. This might be used in a monthly billing scenario, for example.
+ *
+ * @param array<string, mixed> &$checkoutInfo Checkout information passed by reference.
+ *
+ * @return bool
+ */
+ public function createCard(array &$checkoutInfo = []): bool {
+ if ($this->instance && $this->instance->supports('createCard')) {
+ return (bool)$this->instance->createCard($checkoutInfo);
}
+
+ return false;
+ }
+
+ /**
+ * Handle an asynchronous gateway notification using the active method.
+ *
+ * @param array<string, mixed> &$checkoutInfo Checkout information passed by reference.
+ *
+ * @return bool True when the notification was handled.
+ */
+ public function webhook(array &$checkoutInfo = []): bool {
+ if ($this->instance && $this->instance->supports('webhook')) {
+ return (bool)$this->instance->webhook($checkoutInfo);
+ }
+
+ return false;
+ }
+
+ /**
+ * Run a subscription lifecycle operation on a registered method.
+ *
+ * @param string $method Method identifier.
+ * @param string $operation One of createSubscription, cancelSubscription,
+ * pauseSubscription, resumeSubscription, swapSubscription.
+ * @param array<string, mixed> &$info Subscription context passed by reference.
+ *
+ * @return bool True on success, false when unsupported or failed (see getError()).
+ */
+ public function subscription(string $method, string $operation, array &$info = []): bool {
+ $instance = $this->getMethodInstance($method);
+
+ if (!$instance || !$instance->supports($operation)) {
+ return false;
+ }
+
+ return (bool)$instance->{$operation}($info);
}
}
diff --git a/system/queue.php b/system/queue.php
new file mode 100755
index 0000000..6a6164a
--- /dev/null
+++ b/system/queue.php
@@ -0,0 +1,524 @@
+<?php
+
+/**
+ * Vvveb
+ *
+ * Copyright (C) 2022 Ziadin Givan
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+namespace Vvveb\System;
+
+use function Vvveb\__;
+use function Vvveb\config;
+use function Vvveb\logError;
+use Vvveb\System\Queue\Providers\Base;
+use Vvveb\System\Queue\Providers\Database;
+use Vvveb\System\Queue\Providers\FailedJobsAware;
+use Vvveb\System\Queue\Providers\Provider;
+use Vvveb\System\Queue\Providers\Redis;
+
+/**
+ * Background job queue.
+ *
+ * Push jobs onto named queues and process them from a worker
+ * (`php cli.php queue:work`) or a cron single-pass (`module=cron`).
+ *
+ * Backends are providers behind a common interface; Redis and database
+ * (PostgreSQL / MySQL / MariaDB / SQLite) ship built in, plugins can register
+ * more through the 'Vvveb\System\Queue\Providers', 'register' event
+ *
+ * Usage:
+ *
+ * // register a handler (eg. during plugin bootstrap)
+ * \Vvveb\Queue::registerHandler('SendOrderConfirmation', function ($payload, $job) { ... });
+ *
+ * // enqueue
+ * \Vvveb\Queue::push('default', 'SendOrderConfirmation', ['order_id' => 10]);
+ * \Vvveb\Queue::later('default', 3600, 'SendReminder', ['user_id' => 5]);
+ */
+class Queue {
+ public const DEFAULT_QUEUE = 'default';
+
+ /** @var Provider|null Active provider instance. */
+ protected static ?Provider $provider = null;
+
+ /** @var array<string, callable> Registered job handlers keyed by job name. */
+ protected static array $handlers = [];
+
+ /**
+ * Get the active provider instance based on config/queue.php,
+ * letting plugins register additional backends.
+ *
+ * @return Provider
+ */
+ public static function getProvider(): Provider {
+ if (static::$provider) {
+ return static::$provider;
+ }
+
+ $config = config('queue', []);
+ $providers = [
+ 'database' => Database::class,
+ 'redis' => Redis::class,
+ ];
+
+ //let plugins register additional backends (same as payment/notification providers)
+ [$providers] = Event::trigger('Vvveb\System\Queue\Providers', 'register', $providers);
+
+ $name = $config['default'] ?? 'database';
+
+ if (!isset($providers[$name]) || !class_exists($providers[$name])) {
+ //fall back to database when the configured backend is missing
+ $name = isset($providers['database']) ? 'database' : array_key_first($providers);
+ }
+
+ $options = $config['providers'][$name] ?? [];
+ $options['retry'] = $config['retry'] ?? [];
+
+ static::$provider = new $providers[$name]($options);
+
+ return static::$provider;
+ }
+
+ /**
+ * Override the provider instance (used by tests and plugins).
+ *
+ * @param Provider $provider
+ *
+ * @return void
+ */
+ public static function setProvider(Provider $provider): void {
+ static::$provider = $provider;
+ }
+
+ /**
+ * Push a job onto a queue. Payload must be serializable (array/scalar).
+ *
+ * Options: max_attempts (int), available_at (unix ts), delay (seconds).
+ *
+ * @param string $queue Queue name.
+ * @param string $job Job name (a handler must be registered for it).
+ * @param array<array-key, mixed> $payload Job payload.
+ * @param array<array-key, mixed> $options max_attempts, available_at, delay.
+ *
+ * @return string Job id.
+ */
+ public static function push(string $queue, string $job, array $payload = [], array $options = []): string {
+ $config = config('queue', []);
+ $availableAt = isset($options['available_at']) ? (int)$options['available_at']
+ : (isset($options['delay']) ? time() + (int)$options['delay'] : time());
+
+ $record = [
+ 'id' => Base::uuid(),
+ 'queue' => $queue,
+ 'job' => $job,
+ 'payload' => $payload,
+ 'attempts' => 0,
+ 'max_attempts' => (int)($options['max_attempts'] ?? $config['max_attempts'] ?? 3),
+ 'available_at' => $availableAt,
+ 'reserved_at' => null,
+ 'created_at' => time(),
+ ];
+
+ Event::trigger(self::class, 'push:before', $record, $options);
+
+ return static::getProvider()->push($queue, $record);
+ }
+
+ /**
+ * Push a job to run after a delay in seconds.
+ *
+ * @param string $queue Queue name.
+ * @param int $delaySeconds Delay before the job becomes available.
+ * @param string $job Job name.
+ * @param array<array-key, mixed> $payload Job payload.
+ * @param array<array-key, mixed> $options Extra options passed to push().
+ *
+ * @return string Job id.
+ */
+ public static function later(string $queue, int $delaySeconds, string $job, array $payload = [], array $options = []): string {
+ $options['delay'] = $delaySeconds;
+
+ return static::push($queue, $job, $payload, $options);
+ }
+
+ /**
+ * Pop and return the next available job on a queue (claimed by this worker).
+ *
+ * @param string $queue Queue name.
+ *
+ * @return array<array-key, mixed>|null Job record or null if empty.
+ */
+ public static function pop(string $queue): ?array {
+ return static::getProvider()->pop($queue);
+ }
+
+ /**
+ * Mark a job as completed.
+ *
+ * @param string $jobId Job id.
+ *
+ * @return void
+ */
+ public static function complete(string $jobId): void {
+ static::getProvider()->complete($jobId);
+ }
+
+ /**
+ * Mark a job as failed; re-queues it with exponential backoff if retries
+ * remain, otherwise moves it to the failed store and triggers the
+ * 'queue.job.failed' notification event.
+ *
+ * @param string $jobId Job id.
+ * @param string|null $error Error message.
+ *
+ * @return bool True when the job died permanently (moved to failed store).
+ */
+ public static function fail(string $jobId, ?string $error = null): bool {
+ $failed = static::getProvider()->fail($jobId, $error ?? 'Unknown error');
+
+ if ($failed) {
+ try {
+ Notifications::trigger('queue.job.failed', [
+ 'job_id' => $jobId,
+ 'error' => $error,
+ 'subject' => __('Background job failed'),
+ 'message' => sprintf(__('Job %s failed permanently: %s'), $jobId, $error),
+ ]);
+ } catch (\Throwable $e) {
+ //never let notifications break the worker
+ }
+ }
+
+ return $failed;
+ }
+
+ /**
+ * Return a claimed job to the queue after an optional delay.
+ *
+ * @param string $jobId Job id.
+ * @param int $delaySeconds Delay before the job becomes available again.
+ *
+ * @return void
+ */
+ public static function release(string $jobId, int $delaySeconds = 0): void {
+ static::getProvider()->release($jobId, $delaySeconds);
+ }
+
+ /**
+ * Pending (ready + delayed) job count on a queue.
+ *
+ * @param string $queue Queue name.
+ *
+ * @return int
+ */
+ public static function size(string $queue): int {
+ return static::getProvider()->size($queue);
+ }
+
+ /**
+ * Register a handler for a job name so the worker knows how to run it.
+ *
+ * The handler receives ($payload, $job) where $payload is the job payload
+ * array and $job the full job record. Throw inside the handler to fail the job.
+ *
+ * @param string $job Job name.
+ * @param callable $handler function (array $payload, array $job): void
+ *
+ * @return void
+ */
+ public static function registerHandler(string $job, callable $handler): void {
+ static::$handlers[$job] = $handler;
+ }
+
+ /**
+ * Get the registered handler for a job name.
+ *
+ * @param string $job Job name.
+ *
+ * @return callable|null
+ */
+ public static function getHandler(string $job): ?callable {
+ return static::$handlers[$job] ?? null;
+ }
+
+ /**
+ * Run a popped job against its registered handler, catching any error so a
+ * bad job never kills the worker loop; completes or fails the job accordingly.
+ *
+ * @param array<array-key, mixed> $job Job record.
+ *
+ * @return array{ok: bool, error?: string}
+ */
+ public static function runJob(array $job): array {
+ $handler = static::getHandler($job['job']);
+
+ Event::trigger(self::class, 'job:before', $job);
+
+ try {
+ if (!$handler) {
+ throw new \Exception(sprintf(__('No handler registered for job "%s"!'), $job['job']));
+ }
+
+ $handler($job['payload'], $job);
+ } catch (\Throwable $e) {
+ $error = $e->getMessage();
+
+ try {
+ logError(sprintf('[Queue] Job %s (%s) failed: %s', $job['id'], $job['job'], $error));
+ static::fail($job['id'], $error);
+ } catch (\Throwable $ignored) {
+ }
+
+ Event::trigger(self::class, 'job:error', $job, $error);
+
+ return ['ok' => false, 'error' => $error];
+ }
+
+ try {
+ static::complete($job['id']);
+ } catch (\Throwable $e) {
+ logError(sprintf('[Queue] Completing job %s failed: %s', $job['id'], $e->getMessage()));
+ }
+
+ Event::trigger(self::class, 'job:after', $job);
+
+ return ['ok' => true];
+ }
+
+ /**
+ * Worker loop: pop → run registered handler → complete/fail.
+ *
+ * @param string|null $queue Queue name, null = default queue.
+ * @param int $maxJobs Stop after N processed jobs, 0 = run forever.
+ * @param int $sleep Seconds to sleep between empty polls.
+ * @param bool $drain Stop as soon as the queue is empty (cron mode)
+ * instead of polling forever.
+ *
+ * @return array{processed: int, ok: int, failed: int} Counters.
+ */
+ public static function work(?string $queue = null, int $maxJobs = 0, int $sleep = 1, bool $drain = false): array {
+ $queue = $queue ?: self::DEFAULT_QUEUE;
+ $sleep = max(0, $sleep);
+ $counters = ['processed' => 0, 'ok' => 0, 'failed' => 0];
+ $lastReap = time();
+ $reservedTimeout = (int)(config('queue.reserved_timeout_seconds', 300));
+
+ while ($maxJobs === 0 || $counters['processed'] < $maxJobs) {
+ //periodically requeue jobs stranded by crashed workers
+ if (time() - $lastReap >= 60) {
+ $lastReap = time();
+ static::reapStalledJobs($reservedTimeout);
+ }
+
+ try {
+ $job = static::pop($queue);
+ } catch (\Throwable $e) {
+ logError('[Queue] Popping failed: ' . $e->getMessage());
+
+ if ($drain) {
+ break;
+ }
+
+ sleep(max(1, $sleep));
+
+ continue;
+ }
+
+ if (!$job) {
+ if ($drain) {
+ break;
+ }
+
+ if ($sleep > 0) {
+ sleep($sleep);
+ }
+
+ continue;
+ }
+
+ $result = static::runJob($job);
+ $counters['processed']++;
+
+ if ($result['ok']) {
+ $counters['ok']++;
+ } else {
+ $counters['failed']++;
+ }
+
+ if (function_exists('pcntl_signal_dispatch')) {
+ pcntl_signal_dispatch();
+ }
+ }
+
+ return $counters;
+ }
+
+ /**
+ * Single short pass for the cron mechanism (shared hosting without a
+ * persistent worker): drain up to $maxJobs jobs or stop after $maxSeconds.
+ *
+ * @return array{processed: int, ok: int, failed: int}
+ */
+ public static function cronPass(): array {
+ $config = config('queue.cron_pass', []);
+
+ if (isset($config['enabled']) && !$config['enabled']) {
+ return ['processed' => 0, 'ok' => 0, 'failed' => 0];
+ }
+
+ $maxJobs = (int)($config['max_jobs'] ?? 25);
+ $maxSeconds = (int)($config['max_seconds'] ?? 20);
+ $start = time();
+ $queue = self::DEFAULT_QUEUE;
+ $counters = ['processed' => 0, 'ok' => 0, 'failed' => 0];
+
+ static::reapStalledJobs((int)(config('queue.reserved_timeout_seconds', 300)));
+
+ while ($counters['processed'] < $maxJobs && (time() - $start) < $maxSeconds) {
+ try {
+ $job = static::pop($queue);
+ } catch (\Throwable $e) {
+ logError('[Queue] Cron pass pop failed: ' . $e->getMessage());
+
+ break;
+ }
+
+ if (!$job) {
+ break;
+ }
+
+ $result = static::runJob($job);
+ $counters['processed']++;
+
+ if ($result['ok']) {
+ $counters['ok']++;
+ } else {
+ $counters['failed']++;
+ }
+ }
+
+ return $counters;
+ }
+
+ /**
+ * Requeue jobs whose reservation expired (crashed worker cleanup).
+ *
+ * @param int|null $reservedTimeoutSeconds Defaults to queue config value.
+ *
+ * @return int Number of requeued jobs.
+ */
+ public static function reapStalledJobs(?int $reservedTimeoutSeconds = null): int {
+ $provider = static::getProvider();
+
+ if (!$provider instanceof FailedJobsAware) {
+ return 0;
+ }
+
+ try {
+ return $provider->requeueStalled(
+ $reservedTimeoutSeconds ?? (int)(config('queue.reserved_timeout_seconds', 300))
+ );
+ } catch (\Throwable $e) {
+ logError('[Queue] Stalled-job reaper failed: ' . $e->getMessage());
+
+ return 0;
+ }
+ }
+
+ /**
+ * List failed jobs (when the active provider supports it).
+ *
+ * @param string|null $queue Filter by queue.
+ * @param int $limit Max rows.
+ *
+ * @return list<array<array-key, mixed>>
+ */
+ public static function failedJobs(?string $queue = null, int $limit = 100): array {
+ $provider = static::getProvider();
+
+ if (!$provider instanceof FailedJobsAware) {
+ return [];
+ }
+
+ return $provider->getFailed($queue, $limit);
+ }
+
+ /**
+ * Retry a failed job (when the active provider supports it).
+ *
+ * @param string $jobId Job id.
+ *
+ * @return bool
+ */
+ public static function retryFailedJob(string $jobId): bool {
+ $provider = static::getProvider();
+
+ return ($provider instanceof FailedJobsAware) ? $provider->retryFailed($jobId) : false;
+ }
+
+ /**
+ * Delete a failed job (when the active provider supports it).
+ *
+ * @param string $jobId Job id.
+ *
+ * @return bool
+ */
+ public static function deleteFailedJob(string $jobId): bool {
+ $provider = static::getProvider();
+
+ return ($provider instanceof FailedJobsAware) ? $provider->deleteFailed($jobId) : false;
+ }
+
+ /**
+ * Clear all failed jobs (when the active provider supports it).
+ *
+ * @param string|null $queue Filter by queue.
+ *
+ * @return int Deleted count.
+ */
+ public static function clearFailedJobs(?string $queue = null): int {
+ $provider = static::getProvider();
+
+ return ($provider instanceof FailedJobsAware) ? $provider->clearFailed($queue) : 0;
+ }
+
+ /**
+ * Per-queue counters for monitoring (when the active provider supports it).
+ *
+ * @param string $queue Queue name.
+ *
+ * @return array{ready: int, delayed: int, reserved: int}
+ */
+ public static function stats(string $queue): array {
+ $provider = static::getProvider();
+
+ return ($provider instanceof FailedJobsAware) ? $provider->stats($queue) :
+ ['ready' => static::size($queue), 'delayed' => 0, 'reserved' => 0];
+ }
+
+ /**
+ * Human readable name of the active provider ('database', 'redis', ...).
+ *
+ * @return string
+ */
+ public static function providerName(): string {
+ $config = config('queue', []);
+
+ return $config['default'] ?? 'database';
+ }
+}
diff --git a/system/routes.php b/system/routes.php
index 640e6d6..639c4d1 100755
--- a/system/routes.php
+++ b/system/routes.php
@@ -23,38 +23,45 @@
namespace Vvveb\System;
class Routes {
- const stringRegex = '{(\w+)}';
+ public const string stringRegex = '{(\w+)}';
- const varRegex = '[{#]([a-zA-Z]\w+)({([\d,]+)})?[#}]';
+ public const string varRegex = '[{#]([a-zA-Z]\w+)({([\d,]+)})?[#}]';
- const stringLimitRegex = '{([a-zA-Z]\w+){([\d,]+)}}';
+ public const string stringLimitRegex = '{([a-zA-Z]\w+){([\d,]+)}}';
- const numericRegex = '#([a-zA-Z]\w+)#';
+ public const string numericRegex = '#([a-zA-Z]\w+)#';
- const numericLimitRegex = '#([a-zA-Z]\w+){([\d,]+)}#';
+ public const string numericLimitRegex = '#([a-zA-Z]\w+){([\d,]+)}#';
- const wildcardRegex = '\*';
+ public const string wildcardRegex = '\*';
- private static $routes = [];
+ /** @var array<string, array<string, string>> */
+ private static array $routes = [];
- private static $urls = [];
+ /** @var array<string, array{0: string, 1: string}> */
+ private static array $urls = [];
- private static $modules = null;
+ /** @var array<string, array<int, array{url: string, parameters: list<string>, count: int}> >|null */
+ private static ?array $modules = null;
- private static $init = false;
+ private static bool $init = false;
- private static function processRoute($url, $data) {
+ /**
+ * Process a route pattern into regex and store module data.
+ *
+ * @param string $url The route URL pattern.
+ * @param array<string, string> $data Route configuration data.
+ *
+ * @return string The compiled regex pattern.
+ */
+ private static function processRoute(string $url, array $data): string {
$module = $data['module'];
unset($data['edit'], $data['module']);
- //self :: $modules[$module] = $url;
-
$parameters = [];
if (preg_match_all('/' . self :: varRegex . '/', $url, $matches)) {
- if ($matches[1]) {
- $parameters = $matches[1];
- }
+ $parameters = $matches[1];
}
if ($data) {
@@ -62,56 +69,66 @@ class Routes {
}
self :: $modules[$module][] = ['url' => $url, 'parameters' => $parameters, 'count' => count($parameters)];
- //add urls with most parameters first for proper matching
- uasort(self :: $modules[$module], function ($a, $b) {
- return $b['count'] <=> $a['count'];
- });
+ uasort(self :: $modules[$module], fn (array $a, array $b): int => $b['count'] <=> $a['count']);
$route = $url;
- //escape / for regex
- $url = str_replace('/', '\/', $url);
- //numeric limit
- $url = preg_replace('/' . self :: numericLimitRegex . '/', '(?<$1>\d{$2})', $url);
- //numeric
- $url = preg_replace('/' . self :: numericRegex . '/', '(?<$1>\d+)', $url);
- //string limit
- $url = preg_replace('/' . self :: stringLimitRegex . '/', '(?<$1>[^$\/]{$2})', $url);
- //string
- $url = preg_replace('/' . self :: stringRegex . '/', '(?<$1>[^$\/]+)', $url);
- //wildcard
- $url = preg_replace('/' . self :: wildcardRegex . '/', '.*?', $url);
+ $url = str_replace('/', '\/', $url);
+ $url = preg_replace('/' . self :: numericLimitRegex . '/', '(?<$1>\d{$2})', $url);
+ $url = preg_replace('/' . self :: numericRegex . '/', '(?<$1>\d+)', $url);
+ $url = preg_replace('/' . self :: stringLimitRegex . '/', '(?<$1>[^$\/]{$2})', $url);
+ $url = preg_replace('/' . self :: stringRegex . '/', '(?<$1>[^$\/]+)', $url);
+ $url = preg_replace('/' . self :: wildcardRegex . '/', '.*?', $url);
self :: $urls[$route] = [$url, $module];
return $url;
}
- public static function addRoute($url, $data) {
+ /**
+ * Add a route with its URL pattern and configuration data.
+ *
+ * @param string $url The route URL pattern.
+ * @param array<string, string> $data Route configuration data.
+ */
+ public static function addRoute(string $url, array $data): void {
self :: $routes[$url] = $data;
self :: processRoute($url, $data);
}
- public static function removeRoute($url) {
+ /**
+ * Remove one or more routes by URL pattern.
+ *
+ * @param string|array<int, string> $url A single URL pattern or array of URL patterns to remove.
+ */
+ public static function removeRoute(string|array $url): void {
if (is_array($url)) {
foreach ($url as $route) {
- $module = self :: $urls[$route] ?? false;
+ $entry = self :: $urls[$route] ?? false;
- if ($module) {
- unset(self :: $modules[$module]);
+ if ($entry) {
+ unset(self :: $modules[$entry[1]]);
}
unset(self :: $urls[$route]);
}
} else {
- $module = self :: $urls[$url] ?? false;
+ $entry = self :: $urls[$url] ?? false;
- if ($module) {
- unset(self :: $modules[$module]);
+ if ($entry) {
+ unset(self :: $modules[$entry[1]]);
}
unset(self :: $urls[$url]);
}
}
- public static function init($app = 'app', $site_id = null) {
+ /**
+ * Initialize routes from cache or config files.
+ *
+ * @param string $app Application name.
+ * @param int|null $site_id Optional site ID for site-specific routes.
+ *
+ * @return bool Always returns true.
+ */
+ public static function init(string $app = 'app', ?int $site_id = null): bool {
$cacheDriver = Cache :: getInstance();
if ($site_id) {
$cacheKey = $site_id;
@@ -120,9 +137,9 @@ class Routes {
}
if ($result = $cacheDriver->get('routes', $cacheKey)) {
- static::$routes = $result['routes'];
- static::$urls = $result['urls'];
- static::$modules = $result['modules'];
+ self::$routes = $result['routes'];
+ self::$urls = $result['urls'];
+ self::$modules = $result['modules'];
} else {
$routesConfig = DIR_ROOT . '/config/';
if ($site_id) {
@@ -134,16 +151,16 @@ class Routes {
if (file_exists($routesConfig)) {
self :: $routes += include $routesConfig;
}
- list(self :: $routes) = Event::trigger(__CLASS__, __FUNCTION__ , self :: $routes);
+ [self :: $routes] = Event::trigger(__CLASS__, __FUNCTION__, self :: $routes);
foreach (self :: $routes as $url => $data) {
self :: processRoute($url, $data);
}
$result = [];
- $result['routes'] = static::$routes;
- $result['modules'] = static::$modules;
- $result['urls'] = static::$urls;
+ $result['routes'] = self::$routes;
+ $result['modules'] = self::$modules;
+ $result['urls'] = self::$urls;
$cacheDriver->set('routes', $cacheKey, $result);
}
@@ -153,16 +170,23 @@ class Routes {
return true;
}
- public static function match($url) {
- if (! self :: $init) {
+ /**
+ * Match a URL against registered route patterns and return extracted parameters.
+ *
+ * @param string $url The URL to match.
+ *
+ * @return array<string, string>|false Matched parameters or false.
+ */
+ public static function match(string $url): array|false {
+ if (!self :: $init) {
self :: init();
}
- //remove get parameters
$url = preg_replace('/\?.*$/', '', str_replace('//', '/', $url));
foreach (self :: $urls as $route => $data) {
- $params = static::$routes[$route] ?? '';
- list($pattern, $module) = $data;
+ $matches = [];
+ $params = self::$routes[$route] ?? '';
+ [$pattern, $module] = $data;
if ($url == $pattern || preg_match('/^' . $pattern . '$/', $url, $matches)) {
$parameters = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);
@@ -180,17 +204,38 @@ class Routes {
return false;
}
- public static function get($route) {
+ /**
+ * Get the configuration data for a route by its pattern key.
+ *
+ * @param string $route The route pattern key.
+ *
+ * @return array{module: string, edit?: string} Route data or empty array.
+ */
+ public static function get(string $route): array {
return self :: $routes[$route] ?? [];
}
- public static function getRoutes() {
- return self :: $routes ?? [];
+ /**
+ * Get all registered routes.
+ *
+ * @return array<string, array<string, string>> All routes.
+ */
+ public static function getRoutes(): array {
+ return self :: $routes;
}
- public static function varReplace($url, $parameters) {
- return preg_replace_callback('/' . self :: stringRegex . '|' . self :: numericRegex . '/',
- function ($matches) use ($parameters) {
+ /**
+ * Replace variable placeholders in a URL with parameter values.
+ *
+ * @param string $url URL pattern with placeholders.
+ * @param array<string, string> $parameters Key-value pairs for replacement.
+ *
+ * @return string The URL with placeholders replaced.
+ */
+ public static function varReplace(string $url, array $parameters): string {
+ return preg_replace_callback(
+ '/' . self :: stringRegex . '|' . self :: numericRegex . '/',
+ function(array $matches) use ($parameters): string {
$var = $matches[1];
if (isset($parameters[$var])) {
@@ -198,19 +243,35 @@ class Routes {
}
return '';
- }, $url);
+ },
+ $url
+ );
}
- public static function getRouteData($module) {
- if (! self :: $init) {
+ /**
+ * Get route data for a module name.
+ *
+ * @param string $module The module name.
+ *
+ * @return array<int, array{url: string, parameters: list<string>, count: int}> Route data for the module.
+ */
+ public static function getRouteData(string $module): array {
+ if (!self :: $init) {
self :: init();
}
return self :: $modules[$module] ?? [];
}
- public static function getUrlData($url = false) {
- if (! $url) {
+ /**
+ * Get URL data by matching against registered routes.
+ *
+ * @param string|false $url The URL to resolve, or false to use current URL.
+ *
+ * @return array<array-key, mixed>|false Matched route parameters with route metadata, or false on no match.
+ */
+ public static function getUrlData(string|false $url = false): array|false {
+ if (!$url) {
$url = \Vvveb\getCurrentUrl();
}
@@ -218,8 +279,7 @@ class Routes {
$route = stripslashes($parameters['route'] ?? '');
if ($parameters) {
- //$parameters['pattern'] = self :: $modules[$parameters['route']][0]['url'];
- $parameters = $parameters + self :: $routes[$route];
+ $parameters += self :: $routes[$route];
if (isset($parameters['edit'])) {
$parameters['edit'] = self :: varReplace($parameters['edit'], $parameters);
@@ -229,8 +289,16 @@ class Routes {
return $parameters;
}
- public static function url($route, $parameters = false) {
- if (! self :: $init) {
+ /**
+ * Generate a URL from a module route name and parameters.
+ *
+ * @param string $route The module/route name.
+ * @param array<string, string>|false $parameters Query parameters or false for no parameters.
+ *
+ * @return string|null The resolved URL, or null if the route is not found.
+ */
+ public static function url(string $route, array|false $parameters = false): ?string {
+ if (!self :: $init) {
self :: init();
}
@@ -243,10 +311,9 @@ class Routes {
$parameters_count = is_array($parameters) ? count($parameters) : 0;
$param_keys = is_array($parameters) ? array_keys($parameters) : [];
+ $no_parameters = $pattern;
- //if ($param_keys) {
foreach (self :: $modules[$route] as $value) {
- //select route that has all parameters
if ($value['parameters'] && $parameters_count) {
if (count(array_intersect($value['parameters'], $param_keys)) === count($value['parameters'])) {
$pattern = $value['url'];
@@ -257,15 +324,15 @@ class Routes {
$no_parameters = $value['url'];
}
}
- //}
- if (! $parameters) {
+ if (!$parameters) {
$pattern = $no_parameters;
}
$missing = false;
- $url = preg_replace_callback('/' . self :: varRegex . '/',
- function ($matches) use ($parameters, &$missing) {
+ $url = preg_replace_callback(
+ '/' . self :: varRegex . '/',
+ function(array $matches) use ($parameters, &$missing): string {
$var = $matches[1];
if (isset($parameters[$var])) {
@@ -275,7 +342,9 @@ class Routes {
}
return '';
- }, $pattern);
+ },
+ $pattern
+ );
if ($missing) {
return '/?route=' . $route . '&' . (is_array($parameters) ? http_build_query($parameters) : '');
@@ -283,5 +352,7 @@ class Routes {
return $url;
}
}
+
+ return null;
}
}
diff --git a/system/session.php b/system/session.php
index d644a17..ba20bac 100755
--- a/system/session.php
+++ b/system/session.php
@@ -23,56 +23,113 @@
namespace Vvveb\System;
class Session {
- private $driver;
-
- public static function getInstance() {
+ /** @var object Session driver instance. */
+ private object $driver;
+
+ /**
+ * Get singleton instance of the Session class.
+ *
+ * @param array<string, mixed> $options Additional session options.
+ *
+ * @return self|null The singleton instance, or null if no driver is configured.
+ */
+ public static function getInstance(array $options = []): ?self {
static $inst = null;
if ($inst === null) {
$driver = \Vvveb\config(APP . '.session.driver', 'php');
if ($driver) {
- $inst = new Session($driver);
+ $inst = new self($driver, $options);
}
}
return $inst;
}
- public function __construct($driver, $expire = 3600) {
- $class = '\\Vvveb\\System\\Session\\' . $driver;
-
- if (class_exists($class)) {
- $options = \Vvveb\config(APP . '.session', []);
- $this->driver = new $class($options);
+ /**
+ * Initialize the session driver.
+ *
+ * @param string $driver Session driver name.
+ * @param array<string, mixed> $opts Additional options merged with config.
+ *
+ * @return object The instantiated session driver.
+ */
+ public function __construct(string $driver, array $opts = []) {
+ $class = '\Vvveb\System\Session\\' . $driver;
+
+ //if (class_exists($class)) {
+ $options = \Vvveb\config(APP . '.session', []);
+ $options += $opts;
+ $this->driver = new $class($options);
+ /*
} else {
throw new \Exception('Error loading session driver ' . $driver);
- }
-
- return $this->driver;
+ }*/
}
- public function get($key) {
- return $this->driver ? $this->driver->get($key) : null;
+ /**
+ * Retrieve a session value by key.
+ *
+ * @param string $key Session key.
+ *
+ * @return mixed The session value, or null if not found.
+ */
+ public function get(string $key): mixed {
+ return $this->driver->get($key);
}
- public function set($key, $value) {
- return $this->driver ? $this->driver->set($key, $value) : null;
+ /**
+ * Store a value in the session.
+ *
+ * @param string $key Session key.
+ * @param mixed $value Value to store.
+ *
+ * @return mixed The result of the driver set operation.
+ */
+ public function set(string $key, mixed $value): mixed {
+ return $this->driver->set($key, $value);
}
- public function delete($key) {
- return $this->driver ? $this->driver->delete($key) : null;
+ /**
+ * Delete a session value by key.
+ *
+ * @param string $key Session key.
+ *
+ * @return mixed The result of the driver delete operation.
+ */
+ public function delete(string $key): mixed {
+ return $this->driver->delete($key);
}
- public function close() {
- return $this->driver ? $this->driver->close() : null;
+ /**
+ * Close the session.
+ *
+ * @return mixed The result of the driver close operation.
+ */
+ public function close(): mixed {
+ return $this->driver->close();
}
- public function sessionId($id = null) {
- return $this->driver ? $this->driver->sessionId($id) : null;
+ /**
+ * Get or set the current session ID.
+ *
+ * @param string|null $id Session ID to set, or null to retrieve the current one.
+ *
+ * @return mixed The session ID.
+ */
+ public function sessionId(?string $id = null): mixed {
+ return $this->driver->sessionId($id);
}
- public function regenerateId($deleteOldSession = false) {
- return $this->driver ? $this->driver->regenerateId($deleteOldSession) : null;
+ /**
+ * Regenerate the session ID, optionally deleting the old session.
+ *
+ * @param bool $deleteOldSession Whether to delete the old session file.
+ *
+ * @return mixed The result of the driver regenerateId operation.
+ */
+ public function regenerateId(bool $deleteOldSession = false): mixed {
+ return $this->driver->regenerateId($deleteOldSession);
}
}
diff --git a/system/session/php.php b/system/session/php.php
index d1e56f8..97d94d7 100755
--- a/system/session/php.php
+++ b/system/session/php.php
@@ -22,29 +22,42 @@
namespace Vvveb\System\Session;
+use function Vvveb\isSecure;
use Vvveb\System\Sites;
class Php {
- private $options = [
+ /** @var array<string, mixed> */
+ private array $options = [
'gc_maxlifetime' => 3600 * 24 * 30, //month
- 'gc_divisor' => 50000,
- 'gc_probability' => 1,
- 'cookie_httponly' => 'On',
+ 'cookie_httponly' => 1,
+ 'cookie_samesite' => 'Lax',
+ 'use_strict_mode' => 1,
+ 'use_trans_sid' => 0,
];
- public function __construct($options) {
+ /**
+ * @param array<string, mixed> $options
+ */
+ public function __construct(array $options) {
$status = session_status();
if ($status === PHP_SESSION_ACTIVE || $status === PHP_SESSION_DISABLED || headers_sent()) {
return;
}
- $this->options += $options;
+ $this->options = $options + $this->options;
- @ini_set('session.gc_maxlifetime', $this->options['gc_maxlifetime']);
- @ini_set('session.gc_divisor', $this->options['gc_divisor']);
- @ini_set('session.gc_probability', $this->options['gc_probability']);
- @ini_set('session.cookie_httponly', $this->options['cookie_httponly']);
+ @ini_set('session.gc_maxlifetime', (string)$this->options['gc_maxlifetime']);
+ @ini_set('session.cookie_httponly', (string)($this->options['cookie_httponly'] ?? 1));
+ @ini_set('session.use_cookies', (string)($this->options['use_cookies'] ?? 1));
+ @ini_set('session.cookie_samesite', (string)($this->options['cookie_samesite'] ?? 'Lax'));
+ @ini_set('session.use_strict_mode', (string)($this->options['use_strict_mode'] ?? 1));
+ @ini_set('session.use_trans_sid', (string)($this->options['use_trans_sid'] ?? 0));
+
+ //mark the session cookie Secure when the current request is https
+ if (isSecure()) {
+ @ini_set('session.cookie_secure', '1');
+ }
if (defined('SITE_URL') && SITE_URL) {
$host = SITE_URL;
@@ -52,52 +65,94 @@ class Php {
$host = Sites :: getHost();
}
- if (! V_SUBDIR_INSTALL && V_SHARED_SESSION) {
+ if (!V_SUBDIR_INSTALL && V_SHARED_SESSION) {
//try to set cookie for all subdomains
$domain = preg_replace('/^[^\.]*\./', '', $host);
$name = str_replace('.', '', $domain);
// skip if ip number
- if ((! is_numeric($name)) && ($name != 'localhost')) {
- @ini_set('session.cookie_domain', ".$domain");
- session_set_cookie_params(0, '/', ".$domain");
- $sessionName = session_name($name);
+ if ((!is_numeric($name)) && ($name != 'localhost')) {
+ $params = [
+ 'lifetime' => (int)($this->options['cookie_lifetime'] ?? 0),
+ 'path' => '/',
+ 'domain' => '.' . $domain,
+ 'secure' => (bool)ini_get('session.cookie_secure'),
+ 'httponly' => (bool)($this->options['cookie_httponly'] ?? 1),
+ ];
+ $samesite = $this->options['cookie_samesite'] ?? 'Lax';
+ if ($samesite) {
+ $params['samesite'] = $samesite;
+ }
+ session_set_cookie_params($params);
}
}
- return session_start();
+ $id = $options['id'] ?? '';
+
+ if (is_string($id) && preg_match('/\A[a-zA-Z0-9,-]{22,256}\z/', $id)) {
+ session_id($id);
+ }
+
+ session_name('vvveb');
+ session_start();
}
public function __destruct() {
//return $this->close();
}
- public function get($key) {
- if (isset($_SESSION[$key])) {
- return $_SESSION[$key];
- }
+ /**
+ * @param string $key
+ *
+ * @return mixed
+ */
+ public function get(string $key): mixed {
+ return $_SESSION[$key] ?? null;
}
- public function set($key, $value) {
+ /**
+ * @param string $key
+ * @param mixed $value
+ */
+ public function set(string $key, mixed $value): void {
$_SESSION[$key] = $value;
}
- public function delete($key) {
+ /**
+ * @param string $key
+ */
+ public function delete(string $key): void {
unset($_SESSION[$key]);
}
- public function close() {
+ /**
+ * @return bool
+ */
+ public function close(): bool {
return session_write_close();
}
- public function sessionId($id = null) {
+ /**
+ * @param string|null $id
+ *
+ * @return string
+ */
+ public function sessionId(?string $id = null): string {
return session_id($id);
}
- public function regenerateId($deleteOldSession = false) {
+ /**
+ * @param bool $deleteOldSession
+ *
+ * @return bool
+ */
+ public function regenerateId(bool $deleteOldSession = false): bool {
return session_regenerate_id($deleteOldSession);
}
- public function gc() {
+ /**
+ * @return bool
+ */
+ public function gc(): bool {
//handled by php
return true;
}
diff --git a/system/session/request.php b/system/session/request.php
index d87f1b2..b5bc1a5 100644
--- a/system/session/request.php
+++ b/system/session/request.php
@@ -27,38 +27,53 @@ namespace Vvveb\System\Session;
* Used for apps like GraphQl where session is handled externally.
*/
class Request {
- private $data;
+ /** @var array<string, mixed> */
+ private array $data = [];
- public function __construct($options) {
- }
-
- public function __destruct() {
- }
+ public function __construct() {}
- public function get($key) {
- if (isset($this->data[$key])) {
- return $this->data[$key];
- }
+ /**
+ * @param string $key
+ *
+ * @return mixed
+ */
+ public function get(string $key): mixed {
+ return $this->data[$key] ?? null;
}
- public function set($key, $value) {
+ /**
+ * @param string $key
+ * @param mixed $value
+ */
+ public function set(string $key, mixed $value): void {
$this->data[$key] = $value;
}
- public function delete($key) {
+ /**
+ * @param string $key
+ */
+ public function delete(string $key): void {
unset($this->data[$key]);
}
- public function close() {
- }
+ public function close(): void {}
- public function sessionId($id = null) {
+ /**
+ * @param string|null $id
+ */
+ public function sessionId(?string $id = null): ?string {
+ return null;
}
- public function regenerateId($deleteOldSession = false) {
- }
+ /**
+ * @param bool $deleteOldSession
+ */
+ public function regenerateId(bool $deleteOldSession = false): void {}
- public function gc() {
+ /**
+ * @return bool
+ */
+ public function gc(): bool {
$this->data = [];
return true;
diff --git a/system/setting.php b/system/setting.php
index 2fcbd33..85a5199 100755
--- a/system/setting.php
+++ b/system/setting.php
@@ -22,16 +22,20 @@
namespace Vvveb\System;
-use Vvveb\Sql\SettingSQL as SettingSQL;
+use Vvveb\Sql\SettingSQL;
class Setting {
- private $setting = [];
+ /** @var array<string, mixed> */
+ private array $setting = [];
- private $settingSql;
+ /** @var SettingSQL */
+ private SettingSQL $settingSql;
- private static $instance;
+ /** @var ?self */
+ private static ?self $instance = null;
- public static function getInstance() {
+ /** @return self */
+ public static function getInstance(): self {
if (self::$instance) {
return self::$instance;
} else {
@@ -39,12 +43,99 @@ class Setting {
}
}
- function __construct() {
+ /**
+ * @return void
+ */
+ public function __construct() {
$this->settingSql = new SettingSQL();
}
- public function get($namespace, $key, $default = null, $site_id = SITE_ID) {
- if (! $namespace && ! $key) {
+ /**
+ * Decrypt a stored value (or nested settings array) for runtime use.
+ *
+ * Key-agnostic: any `enc:v1:` envelope is decrypted, legacy plaintext
+ * passes through, failures keep the stored value so re-save can recover.
+ *
+ * @param mixed $value Stored value.
+ *
+ * @return mixed Decrypted value.
+ */
+ private function decryptStored(mixed $value): mixed {
+ if (function_exists('\Vvveb\decryptSettings')) {
+ return \Vvveb\decryptSettings($value);
+ }
+
+ if (is_array($value)) {
+ foreach ($value as &$item) {
+ $item = $this->decryptStored($item);
+ }
+ unset($item);
+
+ return $value;
+ }
+
+ if (is_string($value) && function_exists('\Vvveb\isEncryptedSecret') && function_exists('\Vvveb\decryptSecret') && \Vvveb\isEncryptedSecret($value)) {
+ $plain = \Vvveb\decryptSecret($value);
+
+ return $plain === false ? $value : $plain;
+ }
+
+ return $value;
+ }
+
+ /**
+ * Encrypt a value for database storage.
+ *
+ * Sensitive keys (`key|secret|password|signature|token|private|username|
+ * login`) are encrypted with the install-generated `app.key`; everything
+ * else and already-encrypted values pass through. Failures fall back to
+ * plaintext so a missing key never loses data.
+ *
+ * @param string|int $key Setting key (drives the sensitivity check).
+ * @param mixed $value Plaintext value.
+ *
+ * @return mixed Encrypted value ready for storage.
+ */
+ private function encryptForStorage(string|int $key, mixed $value): mixed {
+ if (is_array($value)) {
+ if (function_exists('\Vvveb\encryptSettings')) {
+ return \Vvveb\encryptSettings($value);
+ }
+
+ return $value;
+ }
+
+ if (!is_string($value) || $value === '') {
+ return $value;
+ }
+
+ if (function_exists('\Vvveb\isEncryptedSecret') && \Vvveb\isEncryptedSecret($value)) {
+ return $value;
+ }
+
+ $sensitive = is_string($key) && function_exists('\Vvveb\isSensitiveSettingKey') ? \Vvveb\isSensitiveSettingKey($key) : false;
+
+ if ($sensitive && function_exists('\Vvveb\encryptSecret')) {
+ $encrypted = \Vvveb\encryptSecret($value);
+
+ if (is_string($encrypted) && $encrypted !== '') {
+ return $encrypted;
+ }
+ }
+
+ return $value;
+ }
+
+ /**
+ * @param string $namespace
+ * @param string|array<array-key, mixed>|null $key
+ * @param mixed $default
+ * @param int $site_id
+ *
+ * @return mixed
+ */
+ public function get(string $namespace, string|array|null $key, mixed $default = null, int $site_id = SITE_ID): mixed {
+ if (!$namespace && !$key) {
return $default;
}
@@ -61,7 +152,7 @@ class Setting {
$json = json_decode($val, true);
$val = $json ?: $val;
}
- $return[$value['key']] = $val;
+ $return[$value['key']] = $this->decryptStored($val);
}
return $return;
@@ -90,27 +181,44 @@ class Setting {
$result = $json ?? $result;
}
- return $result;
+ return $this->decryptStored($result);
}
}
- public function set($namespace, $key, $value, $site_id = SITE_ID) {
- if (! $namespace || ! $key) {
- return;
+ /**
+ * @param string $namespace
+ * @param string $key
+ * @param mixed $value
+ * @param int $site_id
+ *
+ * @return mixed
+ */
+ public function set(string $namespace, string $key, mixed $value, int $site_id = SITE_ID): mixed {
+ if (!$namespace || !$key) {
+ return null;
}
- $this->setting[$namespace][$key] = $value;
+ $this->setting[$namespace][$key] = $this->decryptStored($value);
- if (is_array($value)) {
- $value = json_encode($value);
+ $storeValue = $this->encryptForStorage($key, $value);
+
+ if (is_array($storeValue)) {
+ $storeValue = json_encode($storeValue);
}
- return $this->settingSql->set(['namespace' => $namespace, 'key' => $key, 'value' => $value, 'site_id' => $site_id]);
+ return $this->settingSql->set(['namespace' => $namespace, 'key' => $key, 'value' => $storeValue, 'site_id' => $site_id]);
}
- public function delete($namespace, $key, $site_id = SITE_ID) {
- if (! $namespace) {
- return;
+ /**
+ * @param string $namespace
+ * @param string $key
+ * @param int $site_id
+ *
+ * @return mixed
+ */
+ public function delete(string $namespace, ?string $key = null, int $site_id = SITE_ID): mixed {
+ if (!$namespace) {
+ return null;
}
unset($this->setting[$namespace][$key]);
@@ -118,13 +226,29 @@ class Setting {
return $this->settingSql->delete(['namespace' => $namespace, 'key' => $key, 'site_id' => $site_id]);
}
- public function setMulti($namespace, $settings, $site_id = SITE_ID) {
- if (! $site_id) {
+ /**
+ * @param string $namespace
+ * @param array<string, mixed> $settings
+ * @param int $site_id
+ *
+ * @return mixed
+ */
+ public function setMulti(string $namespace, array $settings, int $site_id = SITE_ID): mixed {
+ if (!$site_id) {
$site_id = 0;
}
$result = false;
+ if (function_exists('\Vvveb\encryptSettings')) {
+ $settings = \Vvveb\encryptSettings($settings);
+ } else {
+ foreach ($settings as $storeKey => &$item) {
+ $item = $this->encryptForStorage($storeKey, $item);
+ }
+ unset($item);
+ }
+
foreach ($settings as &$item) {
if (is_array($item)) {
$item = json_encode($item);
diff --git a/system/shipping-method.php b/system/shipping-method.php
index b51201a..202bfea 100755
--- a/system/shipping-method.php
+++ b/system/shipping-method.php
@@ -23,17 +23,114 @@
namespace Vvveb\System;
abstract class ShippingMethod {
- protected $cart;
+ /** @var object Cart instance. */
+ protected object $cart;
- function __construct($cart) {
+ /** @var string|null Last failure reason, set via fail(). */
+ private ?string $error = null;
+
+ /**
+ * @param object $cart Cart instance.
+ */
+ public function __construct(object $cart) {
$this->cart = $cart;
}
- abstract public function init();
+ /**
+ * Check whether this method implements an operation.
+ *
+ * @param string $operation One of ship (tracking/label booking stay on carriers).
+ *
+ * @return bool True if the concrete class overrides the operation.
+ */
+ public function supports(string $operation): bool {
+ return method_exists($this, $operation);
+ }
+
+ /**
+ * Get the last failure reason.
+ *
+ * @return string|null Error message or null when the last operation succeeded.
+ */
+ public function getError(): ?string {
+ return $this->error;
+ }
+
+ /**
+ * Record a failure reason and return false for convenience.
+ *
+ * @param string $message Human readable failure reason.
+ *
+ * @return bool Always false.
+ */
+ protected function fail(string $message): bool {
+ $this->error = $message;
+
+ return false;
+ }
+
+ /**
+ * Record a shipment row for an order, skipping duplicates.
+ *
+ * @param int|string $orderId Order id.
+ * @param string $method Method identifier shown in admin.
+ * @param string $tracking Tracking number, if known.
+ *
+ * @return bool True on success (or when the row already exists).
+ */
+ protected function recordShipment(int|string $orderId, string $method, string $tracking = ''): bool {
+ try {
+ $model = \Vvveb\model('order_shipment');
+ $rows = $model->getByOrder(['order_id' => (int)$orderId])['order_shipment'] ?? [];
+
+ foreach ($rows as $row) {
+ if (($row['shipping_method'] ?? '') === $method && ($row['tracking_number'] ?? '') === $tracking) {
+ return true;
+ }
+ }
+
+ $model->add(['shipment' => [
+ 'order_id' => (int)$orderId,
+ 'shipping_method' => $method,
+ 'tracking_number' => $tracking,
+ ]]);
+
+ return true;
+ } catch (\Throwable $e) {
+ return $this->fail('Shipment could not be recorded: ' . $e->getMessage());
+ }
+ }
+
+ /**
+ * Initialize the shipping method.
+ *
+ * @return void
+ */
+ abstract public function init(): void;
- abstract public function getMethod(&$checkoutInfo = [], $options = []);
+ /**
+ * Get shipping method details and options.
+ *
+ * @param array<string, mixed> &$checkoutInfo Checkout information passed by reference.
+ * @param array<string, mixed> $options Method-specific options.
+ *
+ * @return array<string, mixed>|false Method data or false if unavailable.
+ */
+ abstract public function getMethod(array &$checkoutInfo = [], array $options = []): array|false;
- abstract public function setMethod();
+ /**
+ * Set the active shipping method.
+ *
+ * @return void
+ */
+ abstract public function setMethod(): void;
- abstract public function ship();
+ /**
+ * Process the shipment.
+ *
+ * @param array<string, mixed> &$checkoutInfo Checkout information passed by reference.
+ *
+ * @return bool
+ */
+ abstract public function ship(array &$checkoutInfo = []): bool;
}
diff --git a/system/shipping.php b/system/shipping.php
index 6c172c5..32cdb56 100755
--- a/system/shipping.php
+++ b/system/shipping.php
@@ -25,33 +25,47 @@ namespace Vvveb\System;
use Vvveb\System\Cart\Cart;
class Shipping {
- private $driver;
+ /** @var array<string, array{0: string, 1: array<string, mixed>}> Registered shipping methods. */
+ private array $methods = [];
- private $methods = [];
+ /** @var array<string, ShippingMethod> Instantiated shipping method objects. */
+ private array $instances = [];
- private $instances = [];
+ /** @var ShippingMethod|null The currently active shipping method instance. */
+ private ?ShippingMethod $instance = null;
- private $instance;
-
- public static function getInstance($options = []) {
+ /**
+ * Get singleton instance of the Shipping class.
+ *
+ * @return self
+ */
+ public static function getInstance(): self {
static $inst = null;
if ($inst === null) {
- $inst = new Shipping($options);
+ $inst = new self();
}
return $inst;
}
- public function __construct($options = []) {
- }
-
- public function getMethods(&$checkoutInfo) {
+ public function __construct() {}
+
+ /**
+ * Get all available shipping methods and their data.
+ *
+ * @param array<string, mixed> &$checkoutInfo Checkout information passed by reference.
+ * @param ?object $cart
+ *
+ * @return array<string, array<string, mixed>> Available shipping methods with data.
+ */
+ public function getMethods(array &$checkoutInfo, ?object $cart = null): array {
$data = [];
+ $cart ??= Cart::getInstance();
foreach ($this->methods as $name => $method) {
- list($class, $options) = $method;
- $obj = new $class(Cart::getInstance());
+ [$class, $options] = $method;
+ $obj = new $class($cart);
$this->instances[$name] = $obj;
$shippingData = $obj->getMethod($checkoutInfo, $options);
//if shipping method returns false or no data then don't add it to the list
@@ -63,11 +77,27 @@ class Shipping {
return $data;
}
- public function registerMethod($method, $class, $options = []) {
+ /**
+ * Register a shipping method.
+ *
+ * @param string $method Method identifier.
+ * @param string $class Fully-qualified class name.
+ * @param array<string, mixed> $options Method-specific options.
+ *
+ * @return void
+ */
+ public function registerMethod(string $method, string $class, array $options = []): void {
$this->methods[$method] = [$class, $options];
}
- public function setMethod($method) {
+ /**
+ * Set the active shipping method and initialize all methods.
+ *
+ * @param string $method Method identifier.
+ *
+ * @return void
+ */
+ public function setMethod(string $method): void {
foreach ($this->instances as $instance) {
$instance->init();
}
@@ -78,9 +108,52 @@ class Shipping {
}
}
- public function ship(&$checkoutInfo = []) {
+ /**
+ * Get a specific registered shipping method instance by name.
+ * Instantiates the method on demand if it was not already created by getMethods().
+ *
+ * @param string $method Method identifier.
+ * @param ?object $cart
+ *
+ * @return ShippingMethod|null The method instance or null if the method is not registered.
+ */
+ public function getMethodInstance(string $method, ?object $cart = null): ?ShippingMethod {
+ if (isset($this->instances[$method])) {
+ return $this->instances[$method];
+ }
+
+ if (isset($this->methods[$method])) {
+ [$class, $options] = $this->methods[$method];
+ $obj = new $class($cart ?? Cart::getInstance());
+ $this->instances[$method] = $obj;
+
+ return $obj;
+ }
+
+ return null;
+ }
+
+ /**
+ * Get the last failure reason from the active method.
+ *
+ * @return string|null Error message or null when the last operation succeeded.
+ */
+ public function getError(): ?string {
+ return $this->instance?->getError();
+ }
+
+ /**
+ * Process the shipment using the active method.
+ *
+ * @param array<string, mixed> &$checkoutInfo Checkout information passed by reference.
+ *
+ * @return bool
+ */
+ public function ship(array &$checkoutInfo = []): bool {
if ($this->instance) {
- $this->instance->ship($checkoutInfo);
+ return $this->instance->ship($checkoutInfo);
}
+
+ return false;
}
}
diff --git a/system/sites.php b/system/sites.php
index c6edd27..d99013d 100644
--- a/system/sites.php
+++ b/system/sites.php
@@ -25,44 +25,54 @@ namespace Vvveb\System;
use function Vvveb\__;
class Sites {
- private static $sites = null;
-
- private static $host_matches = [];
-
- const HOST_REGEX = '@(?<prefix>https://|http://|//|^)(?<subdomain>.*?)?\.?(?<domain>[^\.]+)\.(?<tld>[^\.]+|[^\.]{2,3}\.[^\.]{2,3})((?<path>/.*)|$)@';
-
- private static $states;
-
- /*
- private static $states = [
- 'live' => ['name' => 'Live', 'template' => 'index.html', 'icon' => 'la-broadcast-tower'],
- 'maintenance' => ['name' => 'Maintenance', 'template' => 'index.maintenance.html', 'icon' => 'la-wrench'],
- 'coming-soon' => ['name' => 'Coming soon', 'template' => 'index.coming-soon.html', 'icon' => 'la-clock'],
- ];
- */
-
- public static function getStates() {
- static :: $states = [
- 'live' => ['name' => __('Live'), 'template' => 'index.html', 'icon' => 'la-broadcast-tower'],
- 'maintenance' => ['name' => __('Maintenance'), 'template' => 'index.maintenance.html', 'icon' => 'la-wrench'],
- 'coming-soon' => ['name' => __('Coming soon'), 'template' => 'index.coming-soon.html', 'icon' => 'la-clock'],
+ /** @var array<string, array<string, mixed>>|null All sites. */
+ private static ?array $sites = null;
+
+ /** @var array<string, array<string, string>> Cached host regex matches keyed by host. */
+ private static array $host_matches = [];
+
+ public const HOST_REGEX = '@(?<prefix>https://|http://|//|^)(?<subdomain>.*?)?\.?(?<domain>[^\.]+)\.(?<tld>[^\.]+|[^\.]{2,3}\.[^\.]{2,3})((?<path>/.*)|$)@';
+
+ /** @var array<string, array{name: string, template: string, icon: string}> Site states */
+ private static array $states = [];
+
+ /**
+ * Get available site states with their templates and icons.
+ *
+ * @return array<string, array{name: string, template: string, icon: string}>
+ */
+ public static function getStates(): array {
+ self :: $states = [
+ 'live' => ['name' => __('Live'), 'template' => 'index.html', 'icon' => 'broadcast'],
+ 'maintenance' => ['name' => __('Maintenance'), 'template' => 'index.maintenance.html', 'icon' => 'tool'],
+ 'coming-soon' => ['name' => __('Coming soon'), 'template' => 'index.coming-soon.html', 'icon' => 'clock'],
];
- return static :: $states;
+ return self :: $states;
}
- public static function getDefault() {
+ /**
+ * Get the default site.
+ *
+ * @return array<string, mixed>|false The first site data.
+ */
+ public static function getDefault(): array|false {
$sites = self :: getSites();
return current($sites);
}
- public static function getSites() {
- if (! self :: $sites) {
+ /**
+ * Get all configured sites with resolved URLs.
+ *
+ * @return array<string, array<string, mixed>>
+ */
+ public static function getSites(): array {
+ if (!self :: $sites) {
self :: $sites = \Vvveb\config('sites');
foreach (self::$sites as &$site) {
- $site['url'] = self :: url($site['host']) . (V_SUBDIR_INSTALL ? V_SUBDIR_INSTALL : '') . ($site['path'] ?? '' ? '/' . $site['path'] : '');
+ $site['url'] = self :: url($site['host']) . V_SUBDIR_INSTALL . ($site['path'] ?? '' ? '/' . $site['path'] : '');
}
return self :: $sites;
@@ -71,7 +81,14 @@ class Sites {
return self :: $sites;
}
- public static function getSiteByKey($site_key) {
+ /**
+ * Get site data by site key.
+ *
+ * @param string $site_key Site host or key.
+ *
+ * @return array<string, mixed>|false Site data or false if not found.
+ */
+ public static function getSiteByKey(string $site_key): array|false {
$sites = self :: getSites();
$site_key = self :: siteKey($site_key);
@@ -86,7 +103,14 @@ class Sites {
return false;
}
- public static function getSiteById($site_id) {
+ /**
+ * Get site data by site ID.
+ *
+ * @param int $site_id Site ID.
+ *
+ * @return array<string, mixed>|null Site data or null if not found.
+ */
+ public static function getSiteById(int $site_id): ?array {
$sites = self :: getSites();
foreach ($sites as $site_key => $site) {
@@ -96,9 +120,18 @@ class Sites {
return $site;
}
}
+
+ return null;
}
- public static function getTheme($site = false) {
+ /**
+ * Get the theme for a site.
+ *
+ * @param string|int|false $site Site key or ID.
+ *
+ * @return string Theme name, defaults to 'default'.
+ */
+ public static function getTheme(string|int|false $site = false): string {
$data = self :: getSiteData($site);
if ($data) {
@@ -108,32 +141,56 @@ class Sites {
return 'default';
}
- public static function setTheme($site, $theme, $template = '') {
+ /**
+ * Set the theme and optional template for a site.
+ *
+ * @param string|int $site Site key or ID.
+ * @param string $theme Theme name.
+ * @param string $template Template filename.
+ *
+ * @return mixed Result of setSiteData.
+ */
+ public static function setTheme(string|int $site, string $theme, string $template = ''): mixed {
if ($template) {
self :: setSiteData($site, 'template', $template);
}
- return self :: setSiteData($site, 'theme', $theme);
+ $result = self :: setSiteData($site, 'theme', $theme);
+
+ try {
+ Notifications::trigger('theme.activate', ['subject' => "Theme activated: $theme", 'message' => "Theme \"$theme\" was set as the active theme.", 'theme' => $theme]);
+ } catch (\Throwable $e) {
+ // notifications must never break site settings changes
+ }
+
+ return $result;
}
- public static function urlSplit($url = null) {
- $url = $url ?? $_SERVER['HTTP_HOST'] ?? '';
- $host = $host ?? self :: getHost();
+ /**
+ * Split a URL into its components (prefix, subdomain, domain, tld, path).
+ *
+ * @param string|null $url URL to split, or null to use the request host.
+ *
+ * @return array<int|string, string> Associative array of URL components.
+ */
+ public static function urlSplit(?string $url = null): array {
+ $url ??= $_SERVER['HTTP_HOST'] ?? '';
+ $host = self :: getHost();
$host_matches = self :: $host_matches[$host] ?? [];
if (preg_match(self :: HOST_REGEX, $url, $matches)) {
if (($host_matches || preg_match(self :: HOST_REGEX, $host, $host_matches))//check is not ip
- && ! is_numeric($host_matches['domain'] ?? null)) {
+ && !is_numeric($host_matches['domain'] ?? null)) {
self :: $host_matches[$host] = $host_matches;
- $has_subdomain = ! empty($host_matches['subdomain']) || ($matches['subdomain'] != '*');
- $has_tld = ! empty($host_matches['tld']) || ($matches['tld'] != '*');
+ $has_subdomain = !empty($host_matches['subdomain']) || ($matches['subdomain'] != '*');
+ $has_tld = !empty($host_matches['tld']) || ($matches['tld'] != '*');
return $matches;
}
//if host is ip number, localhost or does not have tld remove tld and subdomain
- if (is_numeric($host_matches['domain'] ?? null) || $host == 'localhost' || (strpos($host, '.') === false)) {
+ if (is_numeric($host_matches['domain'] ?? null) || $host == 'localhost' || (!str_contains($host, '.'))) {
$matches['domain'] = $host;
$matches['subdomain'] = $matches['tld'] = $matches['prefix'] = '';
}
@@ -150,14 +207,22 @@ class Sites {
$hasPort = strpos($url, ':') ?: null;
$hostWp = substr($url, 0, strpos($url, ':') ?: null);
- return ['domain' => $hostWp, 'tld'=> '', 'subdomain' => '', 'prefix' => ''];
+ return ['domain' => $hostWp, 'tld' => '', 'subdomain' => '', 'prefix' => ''];
}
return [];
}
- public static function url($url, $host = null) {
- $host = $host ?? self :: getHost();
+ /**
+ * Resolve a URL pattern with wildcards against the current host.
+ *
+ * @param string $url URL pattern with wildcards.
+ * @param string|null $host Hostname to resolve against.
+ *
+ * @return string Resolved URL.
+ */
+ public static function url(string $url, ?string $host = null): string {
+ $host ??= self :: getHost();
$hasPort = strpos($host, ':') ?: null;
$hostWp = substr($host, 0, strpos($host, ':') ?: null);
@@ -165,7 +230,7 @@ class Sites {
if (preg_match(self :: HOST_REGEX, $url, $matches)) {
if (($host_matches || preg_match(self :: HOST_REGEX, $host, $host_matches))//check is not ip
- && ! is_numeric($host_matches['domain'] ?? null)) {
+ && !is_numeric($host_matches['domain'] ?? null)) {
self :: $host_matches[$host] = $host_matches;
$subdomain = str_replace('*', $host_matches['subdomain'], $matches['subdomain']);
@@ -179,27 +244,43 @@ class Sites {
}
//if host is ip number, localhost or does not have tld remove tld and subdomain
- if (! ($matches['prefix'] || ($matches['tld'] && $matches['tld'] !== '*')) &&
- (is_numeric($host_matches['domain'] ?? null) || $hostWp == 'localhost' || (strpos($hostWp, '.') === false))) {
+ if (!($matches['prefix'] || ($matches['tld'] && $matches['tld'] !== '*')) &&
+ (is_numeric($host_matches['domain'] ?? null) || $hostWp == 'localhost' || (!str_contains($hostWp, '.')))) {
$matches['domain'] = $host;
$matches['subdomain'] = $matches['tld'] = $matches['prefix'] = '';
}
- $url = ($matches['prefix'] ? $matches['prefix'] : '') .
- (! empty($matches['subdomain']) ? $matches['subdomain'] . '.' : '') .
- ($matches['domain'] ?? '') .
- (! empty($matches['tld']) ? '.' . $matches['tld'] : '') .
+ $url = ($matches['prefix'] ?: '') .
+ (!empty($matches['subdomain']) ? $matches['subdomain'] . '.' : '') .
+ $matches['domain'] .
+ (!empty($matches['tld']) ? '.' . $matches['tld'] : '') .
($matches['path'] ?? '');
}
return $url;
}
- public static function siteKey($site_url = false) {
- return str_replace('.', ' ',$site_url);
+ /**
+ * Normalize a site URL to a key format (dots replaced with spaces).
+ *
+ * @param string $site_url Site URL to normalize.
+ *
+ * @return string Normalized site key.
+ */
+ public static function siteKey(string $site_url = ''): string {
+ return str_replace('.', ' ', $site_url);
}
- public static function setSiteDataById($site_id, $name, $value) {
+ /**
+ * Set site data by site ID.
+ *
+ * @param int $site_id Site ID.
+ * @param string $name Configuration key name.
+ * @param mixed $value Value to set.
+ *
+ * @return bool Result of setConfig.
+ */
+ public static function setSiteDataById(int $site_id, ?string $name, mixed $value): bool {
$site = self :: getSiteById($site_id);
if ($site && ($site['site_id'] == $site_id)) {
@@ -228,7 +309,16 @@ class Sites {
return false;
}
- public static function setSiteDataByKey($site_key, $name, $value) {
+ /**
+ * Set site data by site key.
+ *
+ * @param string $site_key Site key.
+ * @param string $name Configuration key name.
+ * @param mixed $value Value to set.
+ *
+ * @return mixed Result of setConfig.
+ */
+ public static function setSiteDataByKey(string $site_key, string $name, mixed $value): mixed {
$site = self :: getSiteByKey($site_key);
$site_key = self :: siteKey($site_key);
@@ -241,53 +331,90 @@ class Sites {
}
self :: $sites = null;
+
return \Vvveb\setConfig($key, $value);
}
return false;
}
- public static function setSiteData($site, $name, $value) {
+ /**
+ * Set site data by site ID or key.
+ *
+ * @param string|int $site Site ID or key.
+ * @param string $name Configuration key name.
+ * @param mixed $value Value to set.
+ *
+ * @return mixed Result of setSiteDataById or setSiteDataByKey.
+ */
+ public static function setSiteData(string|int $site, string $name, mixed $value): mixed {
if (is_numeric($site)) {
- return self :: setSiteDataById($site, $name, $value);
+ return self :: setSiteDataById((int)$site, $name, $value);
} else {
return self :: setSiteDataByKey($site, $name, $value);
}
}
- public static function getHost() {
+ /**
+ * Get the current HTTP host.
+ *
+ * @return string Hostname, defaults to 'localhost'.
+ */
+ public static function getHost(): string {
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
return $host;
}
- public static function requestUri($result, $path = '') {
+ /**
+ * Resolve request URI and add it to the site result.
+ *
+ * @param array<string, mixed> $result Site data array.
+ * @param string $path URL path prefix.
+ *
+ * @return array<string, mixed> Site data with URI.
+ */
+ public static function requestUri(array $result, string $path = ''): array {
$result['host'] = self :: url($result['host']);
$result['uri'] = $_SERVER['REQUEST_URI'] ?? '/';
$result['path'] = $path;
-
+
if (V_SUBDIR_INSTALL) {
- $result['uri'] = substr($result['uri'] , strlen(V_SUBDIR_INSTALL)) ?: '/';
+ $result['uri'] = substr($result['uri'], strlen(V_SUBDIR_INSTALL)) ?: '/';
}
-
+
if ($path) {
- $result['uri'] = substr($result['uri'] , strlen($path)) ?: '/';
+ $result['uri'] = substr($result['uri'], strlen($path)) ?: '/';
if ($result['uri'][0] != '/') {
$result['uri'] = '/' . $result['uri'];
}
- }
-
- return $result;
+ }
+
+ return $result;
}
-
- public static function getSiteData($site = false, $path = '') {
+
+ /**
+ * Get site data for the current host, matching by host/path patterns.
+ *
+ * @param string|int|false $site Site ID or key, or false to auto-detect.
+ * @param string $path URL path prefix.
+ *
+ * @return array<string, mixed>|null Site data or null.
+ */
+ public static function getSiteData(string|int|false $site = false, string $path = ''): ?array {
if (is_numeric($site)) {
- $result = self :: getSiteById($site);
- return self :: requestUri($result, $result['path'] ?? '');
+ $result = self :: getSiteById((int)$site);
+ if ($result) {
+ return self :: requestUri($result, $result['path'] ?? '');
+ }
+
+ return null;
}
- if (! $site) {
+ if (!$site) {
$host = self :: getHost();
+ } else {
+ $host = $site;
}
if ($path) {
@@ -296,7 +423,7 @@ class Sites {
}
if (preg_match('/(.+?)[$\/\?]/', $path, $matches)) {
- $path = $matches[1] ?? '';
+ $path = $matches[1];
}
}
@@ -307,7 +434,7 @@ class Sites {
$cacheDriver = Cache :: getInstance();
$cacheKey = $host;
- if (false && $result = $cacheDriver->get('site', $cacheKey)) {
+ if (false /*$result = $cacheDriver->get('site', $cacheKey)*/) {
return self :: requestUri($result, $result['path'] ?? '');
} else {
$host = self :: siteKey($host);
@@ -318,21 +445,21 @@ class Sites {
$tld_wildcard = substr($host, 0, $last) . ' *';
$domain_wildcard = substr($host, 0, $first) . ' * *';
$full_wildcard = '* ' . trim(substr($host, $first, $last - $first)) . ' *';
- $hostPath = $host . $path;
+ $hostPath = $host . $path;
$sites = \Vvveb\config('sites');
$match = '* * *';
- $sub = '';
+ $sub = '';
foreach ($sites as $id => $site) {
if ($path && ($id == $host . $path)) {
$match = $id;
- $sub = $path;
+ $sub = $path;
break;
}
if ($path && ($id == '* * *' . $path)) {
$match = $id;
- $sub = $path;
+ $sub = $path;
break;
}
@@ -375,7 +502,7 @@ class Sites {
'template' => '',
'site_id' => 1,
'state' => 'live',
- 'uri' => $_SERVER['REQUEST_URI'],
+ 'uri' => $_SERVER['REQUEST_URI'] ?? '/',
];
}
}
@@ -386,14 +513,29 @@ class Sites {
return $result;
}
- public static function saveSite($site) {
+ /**
+ * Save a site configuration.
+ *
+ * @param array<string, mixed> $site Site data.
+ *
+ * @return void
+ */
+ public static function saveSite(array $site): void {
$key = self :: siteKey(trim($site['key'] ?? $site['host']));
unset($site['key']);
- $return = \Vvveb\setConfig("sites.$key", $site);
+ \Vvveb\setConfig("sites.$key", $site);
}
- public static function deleteSite($site) {
+ /**
+ * Delete a site configuration.
+ *
+ * @param array<string, mixed> $site Site data.
+ *
+ * @return mixed Result of unsetConfig.
+ */
+ public static function deleteSite(array $site): mixed {
$key = self :: siteKey(trim($site['key'] ?? $site['host']));
- $return = \Vvveb\unsetConfig("sites.$key", $site);
+
+ return \Vvveb\unsetConfig("sites.$key");
}
}
diff --git a/system/sqlp/lexer.php b/system/sqlp/lexer.php
old mode 100755
new mode 100644
index 1fafba6..8078f35
--- a/system/sqlp/lexer.php
+++ b/system/sqlp/lexer.php
@@ -23,34 +23,52 @@
namespace Vvveb\System\Sqlp;
class Lexer {
- protected $regex;
+ /** @var string Compiled regex built from the token-map keys. */
+ protected string $regex;
- protected $offsetToToken;
+ /** @var list<string> Token names indexed by capture-group offset. */
+ protected array $offsetToToken;
- protected $macroMap;
+ /** @var array<string, string|array{0: string, 1: string}> Maps token names to their PHP code or [regex, template] pairs. */
+ protected array $macroMap;
- public function __construct($tokenMap, $macroMap) {
+ /**
+ * @param array<string, string> $tokenMap Regex pattern → token-name mapping.
+ * @param array<string, string|array{0: string, 1: string}> $macroMap Token-name → PHP-code mapping.
+ */
+ public function __construct(array $tokenMap, array $macroMap) {
$this->regex = '/(' . implode(')|(', array_keys($tokenMap)) . ')/As';
$this->offsetToToken = array_values($tokenMap);
$this->macroMap = $macroMap;
}
- public function lex($string) {
+ /**
+ * Tokenise an SQL string into a flat list of `[value, token-type, offset]` tuples.
+ *
+ * Consecutive `T_SQL` tokens are merged into a single entry.
+ *
+ * @param string $string Raw SQL-P source.
+ *
+ * @throws \Exception When an unexpected character is encountered.
+ *
+ * @return list<array{0: string, 1: string, 2: int}>
+ */
+ public function lex(string $string): array {
$tokens = [];
$offset = 0;
$sql = '';
while (isset($string[$offset])) {
- if (! preg_match($this->regex, $string, $matches, 0, $offset)) {
+ if (!preg_match($this->regex, $string, $matches, 0, $offset)) {
throw new \Exception(sprintf('Unexpected character "%s" at offset %d', $string[$offset], $offset));
}
// find the first non-empty element (but skipping $matches[0]) using a quick for loop
- for ($i = 1; '' === $matches[$i]; ++$i);
+ for ($i = 1; '' === $matches[$i]; $i++);
$token = $this->offsetToToken[$i - 1];
//gather all sql tokens into one continuous string
- if ($token == 'T_SQL') {
+ if ($token === 'T_SQL') {
$sql .= $matches[0];
} else {
if ($sql) {
@@ -70,27 +88,36 @@ class Lexer {
return $tokens;
}
- // a recursive function to build the ast structure
- function tree(&$structure, $k=0) {
+ /**
+ * Recursively build a simple AST from the flat token list (pre-macro expansion).
+ *
+ * Recognises `T_IF_START` / `T_IF_END` blocks and attaches child nodes.
+ *
+ * @param list<array{0: string, 1: string, 2: int}> $structure Flat token list (modified in-place).
+ * @param int $k Starting index.
+ *
+ * @return array{0: list<array<array-key, mixed>>, 1: int} [nodes, last-consumed-index].
+ */
+ public function tree(array &$structure, int $k = 0): array {
$output = [];
$count = count($structure);
- for ($i= $k; $i < $count; $i++) {
- list($element, $type, $offset) = $structure[$i];
+ for ($i = $k; $i < $count; $i++) {
+ [$element, $type, $offset] = $structure[$i];
$node = $structure[$i];
- if ($type == 'T_IF_START') {
+ if ($type === 'T_IF_START') {
$ret = $this->tree($structure, $i + 1);
$node['children'] = $ret[0];
$i = $ret[1];
} else {
- if ($type == 'T_IF_END' || $type == 'T_EACH_END') {
+ if ($type === 'T_IF_END' || $type === 'T_EACH_END') {
$output[] = $node;
return [$output, $i];
} else {
- if ($type == 'T_SQL') {
+ if ($type === 'T_SQL') {
}
}
}
@@ -98,43 +125,58 @@ class Lexer {
$output[] = $node;
}
- return $output;
+ return [$output, $i];
}
- function parseError($structure, $node_idx) {
+ /**
+ * Throw a parse error for an unclosed tag.
+ *
+ * @param list<array{0: string, 1: string, 2: int}> $structure Token tree.
+ * @param int $node_idx Index of the unclosed node.
+ *
+ * @return never
+ */
+ public function parseError(array $structure, int $node_idx): never {
$node = $structure[$node_idx];
- throw(
- new \Exception(
- sprintf('sqlP parse error, expecting close tag for `%s` at offset %d at `%s`',
- $node[0] , $node[2], $this->treeToSql($structure))
- ));
+ throw (new \Exception(sprintf('sqlP parse error, expecting close tag for `%s` at offset %d at `%s`', $node[0], $node[2], $this->treeToSql($structure))));
}
- // a recursive function to build the ast structure
- function treeMacro(&$structure, $k=0, $level = 0, $startTag = false) {
+ /**
+ * Recursively build a macro-aware AST from the flat token list.
+ *
+ * Handles `T_IF_START` / `T_ELSE` / `T_IF_END` and `T_EACH` / `T_EACH_END` blocks.
+ *
+ * @param list<array{0: string, 1: string, 2: int}> $structure Flat token list (modified in-place).
+ * @param int $k Starting index.
+ * @param int $level Nesting depth.
+ * @param string|false $startTag The opening tag type of the current block.
+ *
+ * @return array{0: list<array<string, mixed>>, 1: int}|list<array<string, mixed>> [nodes, last-index] or plain nodes.
+ */
+ public function treeMacro(array &$structure, int $k = 0, int $level = 0, string|false $startTag = false): array {
$output = [];
$count = count($structure);
for ($i = $k; $i < $count; $i++) {
- list($element, $type, $offset) = $structure[$i];
+ [$element, $type, $offset] = $structure[$i];
$node = $structure[$i];
- if ($type == 'T_EACH') {
+ if ($type === 'T_EACH') {
$ret = $this->treeMacro($structure, $i + 1, $level + 1, $type);
- if (is_array($ret) && count($ret) == 2) {
+ if (count($ret) === 2) {
$node['children'] = $ret[0];
$i = $ret[1];
} else {
$this->parseError($structure, $i);
}
} else {
- if ($type == 'T_ELSE') {
+ if ($type === 'T_ELSE') {
$ret = $this->treeMacro($structure, $i + 1, $level + 1, $type);
- if (is_array($ret) && count($ret) == 2) {
+ if (count($ret) === 2) {
$node['children'] = $ret[0];
$i = $ret[1];
} else {
@@ -143,10 +185,10 @@ class Lexer {
}
}
- if ($type == 'T_IF_START') {
+ if ($type === 'T_IF_START') {
$ret = $this->treeMacro($structure, $i + 1, $level + 1, $type);
- if (is_array($ret) && count($ret) == 2) {
+ if (count($ret) === 2) {
$node['children'] = $ret[0];
$i = $ret[1];
} else {
@@ -154,16 +196,16 @@ class Lexer {
}
} else {
if ($level > 0 && (
- ($type == 'T_ELSE' && $startTag == 'T_IF_START') ||
- ($type == 'T_IF_END' && $startTag == 'T_ELSE') ||
- ($type == 'T_IF_END' && $startTag == 'T_IF_START') ||
- ($type == 'T_EACH_END' && $startTag == 'T_EACH')
- )) {
+ ($type === 'T_ELSE' && $startTag === 'T_IF_START') ||
+ ($type === 'T_IF_END' && $startTag === 'T_ELSE') ||
+ ($type === 'T_IF_END' && $startTag === 'T_IF_START') ||
+ ($type === 'T_EACH_END' && $startTag === 'T_EACH')
+ )) {
$output[] = $node;
return [$output, $i];
} else {
- if ($type == 'T_SQL') {
+ if ($type === 'T_SQL') {
}
}
}
@@ -174,7 +216,14 @@ class Lexer {
return $output;
}
- function treeToSql(&$tree) {
+ /**
+ * Convert a token tree back into a plain SQL string.
+ *
+ * @param list<array<array-key, mixed>> $tree Token tree.
+ *
+ * @return string Reconstructed SQL.
+ */
+ public function treeToSql(array &$tree): string {
$sql = '';
foreach ($tree as $token) {
@@ -188,45 +237,54 @@ class Lexer {
return $sql;
}
- function parseMacro($statement, $regex, $template) {
- $macro = $template;
-
+ /**
+ * Expand a single macro by replacing its regex-captured placeholders in a template.
+ *
+ * @param string $statement SQL text containing the macro.
+ * @param string $regex Regex that captures the macro arguments.
+ * @param string $template PHP code template with `%placeholder%` and `$%varname%` tokens.
+ *
+ * @return string Expanded SQL.
+ */
+ public function parseMacro(string $statement, string $regex, string $template): string {
if (preg_match_all($regex, $statement, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
$macro = $template;
//replace macro template variables %$variable
$macro = preg_replace_callback(
- '@\$%(\w+)@',
- function ($varMatch) use ($match) {
- return
- preg_replace_callback(
- '/:([\w\.]+)/ms',
- function ($matches) {
- return '$' . \Vvveb\dotToArrayKey('params.' . $matches[1]);
- //return '$params[\'' . $matches[1] . '\']';
- },
- $match[$varMatch[1]]);
- },
- $macro);
-
- //@result
- //replace result variables
+ '@\$%(\w+)@',
+ function($varMatch) use ($match) {
+ return
+ preg_replace_callback(
+ '/:([\w\.]+)/ms',
+ function($matches) {
+ return '$' . \Vvveb\dotToArrayKey('params.' . $matches[1]);
+ //return '$params[\'' . $matches[1] . '\']';
+ },
+ $match[$varMatch[1]]
+ );
+ },
+ $macro
+ );
+
+ /**
+ * @result
+ * replace result variables
+ */
$macro =
preg_replace_callback(
'/@result\.([\w\.]+)/',
- function ($matches) {
- return \Vvveb\dotToArrayKey('$results.' . $matches[1]);
- },
- $macro);
+ fn ($matches) => \Vvveb\dotToArrayKey('$results.' . $matches[1]),
+ $macro
+ );
//replace macro template placeholders %placeholder
$macro = preg_replace_callback(
- '@\%(\w+)@',
- function ($varMatch) use ($match) {
- return $match[$varMatch[1]];
- },
- $macro);
+ '@\%(\w+)@',
+ fn ($varMatch) => $match[$varMatch[1]],
+ $macro
+ );
$statement = str_replace($match[0], $macro, $statement);
}
@@ -235,14 +293,22 @@ class Lexer {
return $statement;
}
- function treeToPhp(&$tree, &$macroMap) {
+ /**
+ * Convert a token tree into a PHP code string by expanding macros.
+ *
+ * @param list<array<array-key, mixed>> $tree Token tree.
+ * @param array<string, string|array{0: string, 1: string}> $macroMap Token-name → code mapping.
+ *
+ * @return string Generated PHP code.
+ */
+ public function treeToPhp(array &$tree, array &$macroMap): string {
$sql = '';
foreach ($tree as $token) {
$name = $token[1];
$code = $token[0];
- if ($name == 'T_SQL') {
+ if ($name === 'T_SQL') {
$sql .= $code;
} elseif (isset($macroMap[$name])) {
$macro = $macroMap[$name];
diff --git a/system/sqlp/macros.php b/system/sqlp/macros.php
deleted file mode 100755
index e84c887..0000000
--- a/system/sqlp/macros.php
+++ /dev/null
@@ -1,51 +0,0 @@
-<?php
-
-%T_IF_START_start%
- ';
- if ($%cond) {
- $sql .= '
-%T_IF_START_end%
-
-%T_ELSE_start%
- ';
- } else {
- $sql .= '
-%T_ELSE_end%
-
-%T_IF_END_start%
- ';
- } //end if
-
- $sql .= '
-%T_IF_END_end%
-
-%T_KEYS_start%
- ';
- $sql .= '`' . implode('`,`', array_keys($params['%keys']));
- $sql .= '`
-%T_KEYS_end%
-
-
-%T_SQL_COUNT_start%
- ';
- $sql .= $this->db->sqlCount($prevSql, '%column', $this->db->prefix . '%table');
- $sql .= '
-%T_SQL_COUNT_end%
-
-%T_SQL_LIMIT_start%
- ';
- $sql .= $this->db->sqlLimit('%start', '%limit');
- $sql .= '
-%T_SQL_LIMIT_end%
-
-%T_LIST_start%
-';
-
- list($_sql, $_params) = $this->db->expandList($params['%list'], '%list');
-
- $sql .= ' ' . $_sql;
-
- if (is_array($_params)) $paramTypes = array_merge($paramTypes, $_params);
-
- $sql .= ' ' .
-%T_LIST_end%
diff --git a/system/sqlp/mysqli.php b/system/sqlp/mysqli.tpl
old mode 100755
new mode 100644
similarity index 93%
rename from system/sqlp/mysqli.php
rename to system/sqlp/mysqli.tpl
index 93f67fb..a0e7e6f
--- a/system/sqlp/mysqli.php
+++ b/system/sqlp/mysqli.tpl
@@ -68,11 +68,7 @@ class %name%SQL {
$result = false;
if ($stmt['%query_id%']) {
- if (method_exists($stmt['%query_id%'], 'get_result')) {
- $result = $stmt['%query_id%']->get_result();
- } else {
- $result = $this->db->get_result($stmt['%query_id%']);
- }
+ $result = $stmt['%query_id%']->get_result();
}
@@ -88,12 +84,18 @@ class %name%SQL {
if ($row['array_key'] === null) {
$results[] = $values;
} else {
+ if (isset($values['array_key'])) {
+ unset($values['array_key']);
+ }
$results[$row['array_key']] = $values;
}
} else {
if ($row['array_key'] === null) {
$results['%query_id%'][] = $values;
} else {
+ if (isset($values['array_key'])) {
+ unset($values['array_key']);
+ }
$results['%query_id%'][$row['array_key']] = $values;
}
}
diff --git a/system/sqlp/pgsql.php b/system/sqlp/pgsql.tpl
similarity index 95%
rename from system/sqlp/pgsql.php
rename to system/sqlp/pgsql.tpl
index d0edf72..519d282 100755
--- a/system/sqlp/pgsql.php
+++ b/system/sqlp/pgsql.tpl
@@ -88,12 +88,18 @@ class %name%SQL {
if ($row['array_key'] === null) {
$results[] = $values;
} else {
+ if (isset($values['array_key'])) {
+ unset($values['array_key']);
+ }
$results[$row['array_key']] = $values;
}
} else {
if ($row['array_key'] === null) {
$results['%query_id%'][] = $values;
} else {
+ if (isset($values['array_key'])) {
+ unset($values['array_key']);
+ }
$results['%query_id%'][$row['array_key']] = $values;
}
}
diff --git a/system/sqlp/sqlite.php b/system/sqlp/sqlite.tpl
similarity index 94%
rename from system/sqlp/sqlite.php
rename to system/sqlp/sqlite.tpl
index 15b4188..672db9a 100755
--- a/system/sqlp/sqlite.php
+++ b/system/sqlp/sqlite.tpl
@@ -89,12 +89,18 @@ class %name%SQL {
if ($row['array_key'] === null) {
$results[] = $values;
} else {
+ if (isset($values['array_key'])) {
+ unset($values['array_key']);
+ }
$results[$row['array_key']] = $values;
}
} else {
if ($row['array_key'] === null) {
$results['%query_id%'][] = $values;
} else {
+ if (isset($values['array_key'])) {
+ unset($values['array_key']);
+ }
$results['%query_id%'][$row['array_key']] = $values;
}
}
diff --git a/system/sqlp/sqlp.php b/system/sqlp/sqlp.php
index e566875..deab792 100644
--- a/system/sqlp/sqlp.php
+++ b/system/sqlp/sqlp.php
@@ -24,64 +24,102 @@ namespace Vvveb\System\Sqlp;
use Vvveb\System\Db;
-define('TAB', "\n\n\t\t");
-
+/**
+ * SQL Parser — parses .sqlp files and generates PHP model classes.
+ */
#[\AllowDynamicProperties]
class Sqlp {
- private $types = ['int' => 'i', 'double' => 'd', 'decimal' => 'd', 'blob' => 'b', 'array' => 'a'/*, 'CHAR' => 's'*/];
+ /** @var string Indentation used when generating PHP code. */
+ private const TAB = "\n\n\t\t";
+
+ /** @var array<string, string> Map of PHP type names to parameter-type codes. */
+ private array $types = ['int' => 'i', 'double' => 'd', 'decimal' => 'd', 'blob' => 'b', 'array' => 'a', 'rows' => 'a', 'row' => 'a'/*, 'CHAR' => 's'*/];
- private $prefix = DB_PREFIX;
+ /** @var string Table-name prefix applied to every query. */
+ private string $prefix = DB_PREFIX;
- private $config = [];
+ /** @var array<string, mixed> Configuration loaded from config.php. */
+ private array $config = [];
- private $tree = [];
+ /** @var array<string, array{name: string, statement: string, params: list<array<string, mixed>>, fetch?: string, param_types?: string, vars?: string}> Parsed method tree. */
+ private array $tree = [];
- private $filters = [];
+ /** @var array<string, array<string, array{name: string, n: bool, d?: string, e?: string}>> Column-filter definitions keyed by prefixed table name. */
+ private array $filters = [];
- private $params = [];
+ /** @var array<string, array<string, string>> Parameter type maps keyed by method name. */
+ private array $paramTypes = [];
- private $db;
+ /** @var Db Database driver instance. */
+ private object $db;
- private $namespace;
+ /** @var string Namespace for the generated model class. */
+ private string $namespace;
- private $model;
+ /** @var array<array-key, mixed> Model config. */
+ private array $model = [];
- private $modelName;
+ /** @var string Model name derived from the .sqlp filename or passed explicitly. */
+ private string $modelName;
- private $filename;
+ /** @var string Full path to the .sqlp file being parsed. */
+ private string $filename;
- function __construct() {
+ /**
+ * Initialise the parser: connect to the database and load the engine-specific model template.
+ */
+ public function __construct() {
$this->db = Db::getInstance();
- $this->config = include 'config.php';
+ $this->config = include __DIR__ . '/config.php';
//load model for selected database
- $modelFile = __DIR__ . DS . DB_ENGINE . '.php';
+ $modelFile = __DIR__ . DS . DB_ENGINE . '.tpl';
$this->loadModel(file_get_contents($modelFile), $this->model);
}
- function loadModel($text, &$config) {
+ /**
+ * Recursively load a model template by expanding nested `%name_start%…%name_end%` blocks.
+ *
+ * @param string $text Raw template text.
+ * @param array<string, mixed> $config Populated in-place with extracted blocks.
+ *
+ * @return string Template text with block markers replaced by single `%name%` placeholders.
+ */
+ public function loadModel(string $text, array &$config): string {
$regex = '/%(.+?)_start%(.+?)%\1_end%/ms';
- $text = preg_replace_callback($regex, function ($matches) use (&$config) {
+ $text = preg_replace_callback($regex, function($matches) use (&$config) {
$config[$matches[1]] = $this->loadModel($matches[2], $config);
return '%' . $matches[1] . '%';
- },$text);
+ }, $text);
return $text;
}
/*
- * Convert array dot notation to php notation
+ * Convert array dot notation to php notation
* Ex: my.array.key to ['my']['array']['key']
*/
- function sqlPhpArrayKey($key) {
+ /**
+ * Convert a dot-notation key to a PHP array-access string.
+ *
+ * @param string $key Dot-separated key, e.g. "my.array.key".
+ *
+ * @return string PHP array-access suffix, e.g. "['my']['array<array-key, mixed>']['key']".
+ */
+ public function sqlPhpArrayKey(string $key): string {
return '[\'' . str_replace('.', '\'][\'', $key) . '\']';
}
- /*
- * Get table name or alias to use as array key when returning values for the query
+ // Get table name or alias to use as array key when returning values for the query
+ /**
+ * Extract the alias intended for use as an array key from a SELECT query.
+ *
+ * @param string $query SQL SELECT statement.
+ *
+ * @return string The alias name, or an empty string if none is found.
*/
- function getQueryArrayKey($query) {
+ public function getQueryArrayKey(string $query): string {
$arrayKeyRegex = '@SELECT.*?`?(\w+)`?\(?\)?\s+(as|AS)\s+(_|array_key)[\s,].*FROM@msi';
if (preg_match($arrayKeyRegex, $query, $matches)) {
@@ -91,10 +129,15 @@ class Sqlp {
return '';
}
- /*
- * Get the value for array_value alias to use as array key when returning values
+ // Get the value for array_value alias to use as array key when returning values
+ /**
+ * Extract the column aliased as `array_value` from a SELECT query.
+ *
+ * @param string $query SQL SELECT statement.
+ *
+ * @return string The column name, or an empty string if none is found.
*/
- function getQueryArrayValue($query) {
+ public function getQueryArrayValue(string $query): string {
$arrayKeyRegex = '@SELECT.*?`?(\w+)`?\(?\)?\s+(as|AS)\s+array_value[\s,].*FROM@msi';
if (preg_match($arrayKeyRegex, $query, $matches)) {
@@ -104,15 +147,21 @@ class Sqlp {
return '';
}
- /*
- * Replace subqueries with provided string to keep only main query for getTableName to correctly extract table name
+ /**
+ * Recursively replace balanced parenthesis groups (sub-queries / macros) with a replacement string.
+ *
+ * @param string $query SQL to process.
+ * @param string $replace Replacement for each matched group.
+ * @param string $startChar Opening delimiter (default "(").
+ * @param string $endChar Closing delimiter (default ")").
+ *
+ * @return string Processed SQL.
*/
- function removeParanthesis($query, $replace = '', $startChar = '(', $endChar = ')') {
+ public function removeParanthesis(string $query, string $replace = '', string $startChar = '(', string $endChar = ')'): string {
$level = 0;
$start = null;
- $end = 0;
- for ($i=0; $i < strlen($query); $i++) {
+ for ($i = 0, $len = strlen($query); $i < $len; $i++) {
$char = $query[$i];
if ($char == $startChar) {
@@ -121,35 +170,43 @@ class Sqlp {
}
$level++;
} else {
- if ($char == $endChar) {
- $level--;
+ if ($char === $endChar) {
+ //clamp at zero so stray closing delimiters don't break the balance
+ $level = max(0, $level - 1);
}
}
- if ($start && $level == 0) {
+ //strict null check - a group starting at position 0 is falsy but valid
+ if ($start !== null && $level == 0) {
$end = $i + 1;
$query = substr_replace($query, $replace, $start, $end - $start);
//reset
$i = 0;
$start = null;
+ $len = strlen($query);
}
}
return $query;
}
- /*
- * Extract table name from sql statement
+ /**
+ * Extract the primary table name from a SQL statement.
+ *
+ * Handles SELECT, INSERT INTO, UPDATE, DELETE FROM, and aggregate/function forms.
+ *
+ * @param string $query SQL statement.
+ *
+ * @return string Table name (without quotes or prefix).
*/
- function getTableName($query) {
+ public function getTableName(string $query): string {
$tableName = '';
//remove subselects
$query = $this->removeParanthesis($query, 'replace_subselect');
//remove macros
$count = 1;
-
- while ($count != 0) {
+ while ($count !== 0) {
$query = preg_replace('/@(\w+)[^@]+?@\1/ms', 'replaced_macro', $query, -1, $count);
}
@@ -167,7 +224,7 @@ class Sqlp {
preg_match($deleteRegex, $query, $matches1) ||
preg_match($functionRegex, $query, $matches1) ||
preg_match($countRegex, $query, $matches1)) {
- $tableName = ! empty($matches1[2]) ? $matches1[2] : $matches1[3];
+ $tableName = $matches1[2];
if (preg_match('@`?\w+`?$@i', $tableName, $matches2)) {
$tableName = $matches2[0];
@@ -177,13 +234,15 @@ class Sqlp {
return trim($tableName, '`"\'');
}
- /*
- * Add prefix to table name
+ /**
+ * Prefix all table references in a SQL statement with {@see $this->prefix}.
+ *
+ * @param string $query SQL statement.
+ *
+ * @return string SQL with prefixed table names.
*/
- function prefixTable($query) {
- $tableName = '';
-
- //$regexs[] = '/(SELECT.+FROM\s+`?)(\w+`? AS \w+|\w+`?)/ims';
+ public function prefixTable(string $query): string {
+ $regexs = [];
$regexs[] = '/(UPDATE\s+`?)(\w+`? AS \w+\s+SET|\w+`?\s+SET)/ims';
$regexs[] = '/(INSERT\s+INTO\s+`?)(\w+`? AS \w+|\w+`?)/ims';
//$regexs[] = '/(DELETE\s+FROM\s+`?)(\w+`? AS \w+|\w+`?)/ims';
@@ -195,9 +254,7 @@ class Sqlp {
foreach ($regexs as $regex) {
$query = preg_replace_callback(
$regex,
- function ($matches) {
- return $matches[1] . $this->prefix . $matches[2];
- },
+ fn ($matches) => $matches[1] . $this->prefix . $matches[2],
$query
);
}
@@ -205,59 +262,72 @@ class Sqlp {
return $query;
}
- function paramType($type) {
+ /**
+ * Return the parameter-type character for a given SQL type name.
+ *
+ * @param string $type SQL type name (e.g. "int", "double").
+ *
+ * @return string Single-character type code (i / d / b / a / s).
+ */
+ public function paramType(string $type): string {
return $this->types[strtolower($type)] ?? 's';
}
- function fetchType($type) {
- switch ($type) {
- case 'insert_id':
- return $this->model['insert_id'];
- //return '$this->db->insert_id';
-
- case 'affected_rows':
- return $this->model['affected_rows'];
- //return '$this->db->affected_rows';
-
- case 'fetch_row':
- return $this->model['fetch_row'];
- //return '$result->fetch_array(MYSQLI_ASSOC)';
-
- case 'fetch_one':
- return $this->model['fetch_one'];
- //return '$result->fetch_array(MYSQLI_NUM)[0] ?? null';
-
- case (isset($type[0]) && $type[0] == '@'):
- $key = str_replace('@result.', '', $type);
-
- return $this->template($this->model['fetch_result'], ['key' => $key]);
- //return sprintf($this->model['fetch_result'], $key, $key);
- //return "isset(\$results['$key']) ? \$results['$key'] : 'NULL'";
+ /**
+ * Return the PHP expression that fetches the desired result shape.
+ *
+ * @param string|null $type One of 'insert_id', 'affected_rows', 'fetch_row', 'fetch_one',
+ * 'fetch_all', or '@result.<key>'.
+ *
+ * @return string PHP expression string to embed in generated code.
+ */
+ public function fetchType(?string $type): string {
+ if (isset($type[0]) && $type[0] == '@') {
+ $key = str_replace('@result.', '', $type);
- case 'fetch_all':
- default:
- return $this->model['fetch_all'];
- //return '$result->fetch_all(MYSQLI_ASSOC)';
+ $return = $this->template($this->model['fetch_result'], ['key' => $key]);
+ } else {
+ $return = match ($type) {
+ 'insert_id' => $this->model['insert_id'],
+ 'affected_rows' => $this->model['affected_rows'],
+ 'fetch_row' => $this->model['fetch_row'],
+ 'fetch_one' => $this->model['fetch_one'],
+ default => $this->model['fetch_all'],
+ };
}
- }
- function template($template, $variables) {
- //$template = preg_replace('/\t+/', "\t\t", $template);
+ return trim($return);
+ }
- $keys = array_map(function ($value) {
- return "%$value%";
- }, array_keys($variables));
+ /**
+ * Replace `%variable%` placeholders in a template string.
+ *
+ * @param string $template Template containing `%key%` placeholders.
+ * @param array<string, mixed> $variables Values to substitute.
+ *
+ * @return string Rendered string.
+ */
+ public function template(string $template, array $variables): string {
+ $keys = array_map(fn ($value) => "%$value%", array_keys($variables));
$values = array_values($variables);
- $result = str_replace($keys, $values, $template);
+ return str_replace($keys, $values, $template);
//remove unmatched variables
//$result = preg_replace('/%\w+%/', '', $result);
-
- return $result;
}
- function parseMacro($statement, $params, $regex, $template) {
+ /**
+ * Parse a single macro block against its regex and expand the template for every match.
+ *
+ * @param string $statement SQL statement containing macro tokens.
+ * @param array<int, array<string, mixed>> $params Method parameters.
+ * @param string $regex PREG pattern that captures macro placeholders.
+ * @param string $template PHP code template to expand for each match.
+ *
+ * @return string Expanded SQL statement.
+ */
+ public function parseMacro(string $statement, array $params, string $regex, string $template): string {
$macro = $template;
if (preg_match_all($regex, $statement, $matches, PREG_SET_ORDER)) {
@@ -267,25 +337,26 @@ class Sqlp {
//replace macro template variables %$variable
$macro = preg_replace_callback(
'@\$%(\w+)@',
- function ($varMatch) use ($match) {
+ function($varMatch) use ($match) {
return
preg_replace_callback(
$this->config['varRegex'],
- function ($matches) {
+ function($matches) {
return '$' . \Vvveb\dotToArrayKey('params.' . $matches[1]);
//return '$params[\'' . $matches[1] . '\']';
},
- $match[$varMatch[1]]);
+ $match[$varMatch[1]]
+ );
},
- $macro);
+ $macro
+ );
//replace macro template placeholders %placeholder
$macro = preg_replace_callback(
'@\%(\w+)@',
- function ($varMatch) use ($match) {
- return $match[$varMatch[1]];
- },
- $macro);
+ fn ($varMatch) => $match[$varMatch[1]],
+ $macro
+ );
$statement = str_replace($match[0], $macro, $statement);
}
@@ -294,15 +365,23 @@ class Sqlp {
return $statement;
}
- function parseEach($statement, $params) {
+ /**
+ * Expand `@EACH` variable macros into foreach loops within the generated PHP code.
+ *
+ * @param string $statement SQL statement containing @EACH tokens.
+ * @param array<int, array<string, mixed>> $params Method parameters.
+ *
+ * @return string Statement with @EACH blocks expanded.
+ */
+ public function parseEach(string $statement, array $params): string {
//EACH VAR
if (preg_match_all($this->config['eachVarRegex'], $statement, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
$resultKey = $this->sqlPhpArrayKey($match[1]);
- $each = "\n" . TAB . 'if (isset($params' . $resultKey . ') && is_array($params' . $resultKey . '))' .
- 'foreach ($params' . $resultKey . ' as $key => $rowParent) { ' . "\n" . TAB . '
- $params[\'each\'] = $rowParent;
+ $each = "\n" . self::TAB . 'if (isset($params' . $resultKey . ') && is_array($params' . $resultKey . '))' .
+ 'foreach ($params' . $resultKey . ' as $key => $rowParent) { ' . "\n" . self::TAB .
+ ' $params[\'each\'] = $rowParent;
$params[\'each_key\'] = $key;
if (is_array($params[\'each\'])) {
$paramTypes[\'each\'] = \'a\';
@@ -313,7 +392,7 @@ class Sqlp {
}
$sql = \'';
- $statement = str_replace('$sql = \'' . $match[0], $each, $statement) . "\n" . TAB . ' }
+ $statement = str_replace('$sql = \'' . $match[0], $each, $statement) . "\n" . self::TAB . ' }
unset($params[\'each\']);
unset($paramTypes[\'each\']);
';
@@ -323,98 +402,119 @@ class Sqlp {
return $statement;
}
- function parseSQLCount($statement, $params) {
- //EACH VAR
- $statement = '$sql = ' . $statement;
-
- return $statement;
- }
-
- function parseMacros($statement, $params) {
- //if then else
- $space = "\n\n\t\t";
-
+ /**
+ * Parse all macro constructs in a SQL statement: variables, conditionals, result references, and filters.
+ *
+ * @param string $statement Raw SQL with macro tokens.
+ * @param array<int, array<string, mixed>> $params Method parameters.
+ *
+ * @return string PHP code string ready for embedding in a generated method.
+ */
+ public function parseMacros(string $statement, array $params): string {
//replace variables
$statement =
preg_replace_callback(
'/\$([\w_-]+)/',
- function ($matches) {
+ function($matches) {
$key = $matches[1];
return "' . (isset(\$params['$key']) ? \$params['$key'] : 'NULL') . '";
//return "' . \$results['". $matches[1] . "'] . '";
},
- $statement);
+ $statement
+ );
- $lex = new Lexer($this->config['tokenMap'], $this->config['macroMap']);
+ $lex = new Lexer($this->config['tokenMap'], $this->config['macroMap']);
$structure = $lex->lex($statement);
$output = $lex->treeMacro($structure);
$statement = $lex->treeToPhp($output, $this->config['macroMap']);
- //@result
- //replace result variables
+ /**
+ * @result
+ * replace result variables
+ */
$statement =
preg_replace_callback(
'/@result\.([\w\.]+)/',
- function ($matches) {
+ function($matches) {
$key = \Vvveb\dotToArrayKey('$results.' . $matches[1]);
return "' . (isset($key) ? $key : 'NULL') . '";
},
- $statement);
+ $statement
+ );
- //FILTER
- if (preg_match_all($this->config['filterRegex'], $statement, $matches, PREG_SET_ORDER)) {
- foreach ($matches as $match) {
- $filter = [];
- $columns = $this->db->getColumnsMeta($this->prefix . $match['columns']);
- $addMissingDefaults = $match['addmissing'] ?? 'false';
- $isArray = $match['array'] ?? 'false';
+ return $this->processFilters($statement);
+ }
- foreach ($columns as $column) {
- $name = $column['name'];
- unset($column['name']);
+ /**
+ * Process @FILTER directives: read column metadata for the referenced table,
+ * cache the filter definition and embed db->filter() calls in the generated code.
+ *
+ * @param string $statement Generated code containing @FILTER tokens.
+ *
+ * @return string Statement with filter processing embedded.
+ */
+ private function processFilters(string $statement): string {
+ if (!preg_match_all($this->config['filterRegex'], $statement, $matches, PREG_SET_ORDER)) {
+ return $statement;
+ }
- if (empty($column['e'])) {
- unset($column['e']);
- }
- $column['n'] = ($column['n'] == 'NO') ? false : true;
+ foreach ($matches as $match) {
+ $filter = [];
+ $columns = $this->db->getColumnsMeta($this->prefix . $match['columns']);
+ $addMissingDefaults = $match['addmissing'] ?? 'false';
+ $isArray = $match['array'] ?? 'false';
- if (isset($column['d'])) {
- $column['d'] = trim($column['d'], '\'');
- }
- $filter[$name] = $column;
+ foreach ($columns as $column) {
+ $name = $column['name'];
+ unset($column['name']);
+
+ if (empty($column['e'])) {
+ unset($column['e']);
}
+ $column['n'] = ($column['n'] === 'NO') ? false : true;
- //$filterArray = var_export($filter, true);
- $return = ! empty($match['return']) ? $match['return'] : $match['data'];
- $return = '$params' . $this->sqlPhpArrayKey($return);
- $key = '$params' . $this->sqlPhpArrayKey($match['data']);
- $filterName = '$this->filters[\'' . $this->prefix . $match['columns'] . '\']';
+ if (isset($column['d'])) {
+ $column['d'] = trim($column['d'], '\'');
+ }
+ $filter[$name] = $column;
+ }
- //$filterFunction = '\';' . TAB . '$filterArray = ' . $filterArray . ";\n" . TAB;
- $filterFunction = '\';' . TAB;
- $this->filters[$this->prefix . $match['columns']] = $filter;
+ $return = !empty($match['return']) ? $match['return'] : $match['data'];
+ $return = '$params' . $this->sqlPhpArrayKey($return);
+ $key = '$params' . $this->sqlPhpArrayKey($match['data']);
+ $filterName = '$this->filters[\'' . $this->prefix . $match['columns'] . '\']';
- if ($isArray == 'true') {
- $filterFunction .= 'if (isset(' . $key . ') && is_array(' . $key . ')) foreach ( ' . $key . ' as $key => &$filter) ' . $return . '[$key] = $this->db->filter($filter, ' . $filterName . ',' . $addMissingDefaults . ');' . TAB . '$sql = \'';
- } else {
- $filterFunction .= $return . '= $this->db->filter(' . $key . ', ' . $filterName . ',' . $addMissingDefaults . ');' . TAB . '$sql = \'';
- }
+ $filterFunction = '\';' . self::TAB;
+ $this->filters[$this->prefix . $match['columns']] = $filter;
- $statement = str_replace($match[0], $filterFunction, $statement);
+ if ($isArray === 'true') {
+ $filterFunction .= 'if (isset(' . $key . ') && is_array(' . $key . ')) foreach ( ' . $key . ' as $key => &$filter) ' . $return . '[$key] = $this->db->filter($filter, ' . $filterName . ',' . $addMissingDefaults . ');' . self::TAB . '$sql = \'';
+ } else {
+ $filterFunction .= $return . '= $this->db->filter(' . $key . ', ' . $filterName . ',' . $addMissingDefaults . ');' . self::TAB . '$sql = \'';
}
+
+ $statement = str_replace($match[0], $filterFunction, $statement);
}
return $statement;
}
- function parseParameters($params) {
+ /**
+ * Parse the parameter declarations block of a stored-procedure definition.
+ *
+ * @param string $params Raw parameter text from the .sqlp file.
+ *
+ * @return list<array{in_out: string, name: string, type: string, length: int, comment?: string}>
+ */
+ public function parseParameters(string $params): array {
$parameters = [];
if (preg_match_all($this->config['paramRegex'], $params, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
+ $param = [];
$param['in_out'] = trim($match[1]);
$param['name'] = trim($match[2]);
@@ -425,7 +525,7 @@ class Sqlp {
}
if (isset($match[4])) {
- $param['length'] = (int)preg_replace('/[^\d]/', '',$match[4]);
+ $param['length'] = (int)preg_replace('/[^\d]/', '', $match[4]);
}
if (isset($match[5])) {
@@ -439,17 +539,24 @@ class Sqlp {
return $parameters;
}
- function processImports($sql) {
- $sql = preg_replace_callback($this->config['importRegex'], function ($matches) {
+ /**
+ * Resolve `import(…)` directives by replacing them with the contents of the referenced file.
+ *
+ * @param string $sql Raw SQL text.
+ *
+ * @return string SQL with imports inlined.
+ */
+ public function processImports(string $sql): string {
+ return preg_replace_callback($this->config['importRegex'], function($matches) {
$file = $matches[1];
//absolute path
- if ($file[0] == '/') {
+ if ($file[0] === '/') {
$path = explode('/', substr($file, 1));
- $app = $path[0];
+ $app = $path[0];
unset($path[0]);
- if ($app == 'plugins') {
- $plugin = $path[1];
+ if ($app === 'plugins') {
+ $plugin = $path[1] ?? '';
unset($path[1]);
} else {
$plugin = '';
@@ -458,7 +565,7 @@ class Sqlp {
$file = implode('/', $path);
$file = DIR_ROOT . $app . ($plugin ? '/' . $plugin : '') . '/sql/' . DB_ENGINE . '/' . $file;
} else {//relative path
- $file = DIR_SQL . $matches[1];
+ $file = DIR_SQL . $matches[1];
}
if (file_exists($file)) {
@@ -467,18 +574,27 @@ class Sqlp {
return '';
}, $sql);
-
- return $sql;
}
- function parseSqlPfile($filename, $modelName = false, $namespace = '') {
+ /**
+ * Parse a `.sqlp` file and populate the internal method tree.
+ *
+ * @param string $filename Path to the `.sqlp` file.
+ * @param string|bool $modelName Optional explicit model name; when false it is derived from the filename.
+ * @param string $namespace Optional namespace for the generated class.
+ *
+ * @return void
+ */
+ public function parseSqlPfile(string $filename, string|bool $modelName = false, string $namespace = ''): void {
if ($modelName) {
$this->modelName = $modelName;
} else {
- $this->modelName = str_replace('.sql', '', preg_replace_callback('/_(\w)/',
- function ($m) {
- return ucfirst($m[1]);
- } , basename($filename)));
+ //strip .sql/.sqlp extension and camel-case underscored names
+ $this->modelName = str_replace('.sql', '', preg_replace_callback(
+ '/_(\w)/',
+ fn ($m) => ucfirst($m[1]),
+ basename($filename)
+ ));
}
$this->namespace = $namespace;
@@ -496,7 +612,7 @@ class Sqlp {
foreach ($matches as $match) {
$method['name'] = trim($match['name'], '`"\'');
//add slashes only for single quotes
- $method['statement'] = str_replace("'", "\'",trim($match['statement']));
+ $method['statement'] = str_replace("'", "\'", trim($match['statement']));
$method['statement'] = preg_replace('@(--.*)\s+@', '', $method['statement']);
$method['params'] = $this->parseParameters($match['params']);
@@ -508,169 +624,176 @@ class Sqlp {
}
}
- function getModel() {
+ /**
+ * Return the parsed method tree.
+ *
+ * @return array<string, array{name: string, statement: string, params: list<array<string, mixed>>}>
+ */
+ public function getModel(): array {
return $this->tree;
}
- function generateModel() {
+ /**
+ * Generate the complete PHP model source code from the parsed tree.
+ *
+ * @return string PHP class source code.
+ */
+ public function generateModel(): string {
$methods = '';
if ($this->tree) {
foreach ($this->tree as $i => $method) {
- $statement = "/*{$this->modelName} - {$method['name']}*/\n\t\t";
+ $methods .= $this->generateMethod($method, $i);
+ }
+ }
- $queries = explode(';', $method['statement']);
- $queriesCount = count($queries);
+ return $this->template($this->model['model'], [
+ 'name' => ucfirst($this->modelName),
+ 'namespace' => ucfirst($this->namespace),
+ 'filename' => $this->filename,
+ 'methods' => $methods,
+ 'filters' => var_export($this->filters, true),
+ 'paramTypes' => var_export($this->paramTypes, true),
+ ]);
+ }
- $statements = '';
+ /**
+ * Generate the code for a single model method (one per stored procedure).
+ *
+ * @param array{name: string, statement: string, params: list<array<string, mixed>>} $method Parsed method.
+ * @param string|int $methodIndex Tree key of the method (its name); compared strictly against the OUT-parameter counter.
+ *
+ * @return string Generated method code.
+ */
+ private function generateMethod(array $method, string|int $methodIndex): string {
+ $statements = "/*{$this->modelName} - {$method['name']}*/\n\t\t";
- $method['fetch'] = $this->fetchType('fetch_all');
+ $queries = explode(';', $method['statement']);
+ $method['fetch'] = $this->fetchType('fetch_all');
- $fetch = [];
+ //OUT parameters select the fetch style of their corresponding query
+ $fetch = [];
- foreach ($method['params'] as $param) {
- if ($param['in_out'] == 'OUT') {
- $fetch[] = $param['name'];
- }
- }
+ foreach ($method['params'] as $param) {
+ if ($param['in_out'] === 'OUT') {
+ $fetch[] = $param['name'];
+ }
+ }
- foreach ($queries as $qIndex => $query) {
- $statement = '';
- $query = $this->prefixTable(trim($query), DB_PREFIX);
+ foreach ($queries as $qIndex => $query) {
+ $statement = '';
+ $query = $this->prefixTable(trim($query));
- if (empty($query)) {
- continue;
- }
- $hasEach = (0 === strncmp($query, '@EACH', 5));
-
- $template = /*$hasEach?$this->config['eachQuery']:*/$this->model['query'];
-
- $queryId = preg_replace('/^' . $this->prefix . '/', '', $this->getTableName($query));
- $arrayKey = $this->getQueryArrayKey($query);
- $arrayValue = $this->getQueryArrayValue($query);
-
- //$query = $this->parseSQLCount($query);
- $statement .= $this->template($template,
- [
- 'statement' => $this->parseMacros($query, $method['params']),
- 'query_id' => $queryId,
- 'array_key' => $arrayKey,
- 'array_value' => $arrayValue,
- ]);
-
- $statement = $this->parseEach($statement, $method['params']);
-
- //expand array parameters
- foreach ($method['params'] as $param) {
- if ($param['type'] == 'ARRAY') {
- $expandArray = '\';' . TAB . ' list($_sql, $_params) = $this->db->expandArray($params[\'' . $param['name'] . '\'], \'' . $param['name'] . '\');'
- . TAB . '$sql .= $_sql;'
- . TAB . 'if (is_array($_params)) $paramTypes = array_merge($paramTypes, $_params);'
- . TAB . '$sql .= \' ';
-
- //$statement = str_replace(':' . $param['name'], $expandArray, $statement);
- $statement = preg_replace('@:' . $param['name'] . '(?!_\.) @', $expandArray, $statement);
- }
- }
+ if (empty($query)) {
+ continue;
+ }
- //clean empty sql strings
- $statement = preg_replace('@\$sql .= \'\s+\n\s*\';@ms', '$sql .= \' \';', $statement);
- $statement = preg_replace('@\s*\$sql .= \'\';@ms', '', $statement);
- //$statement = preg_replace('@\s*\$sql .= \'\s*\';@ms', '', $statement);
+ $template = $this->model['query'];
- if (isset($fetch[$qIndex])) {
- $method['fetch'] = $this->fetchType($fetch[$qIndex]);
- } else {
- if (isset($fetch[0])) {
- $method['fetch'] = $this->fetchType($fetch[0]);
- }
- }
+ $queryId = preg_replace('/^' . $this->prefix . '/', '', $this->getTableName($query));
+ $arrayKey = $this->getQueryArrayKey($query);
+ $arrayValue = $this->getQueryArrayValue($query);
- $statement = $this->template($statement, ['fetch' => $method['fetch']]);
+ $statement .= $this->template(
+ $template,
+ [
+ 'statement' => $this->parseMacros($query, $method['params']),
+ 'query_id' => $queryId,
+ 'array_key' => $arrayKey,
+ 'array_value' => $arrayValue,
+ ]
+ );
- $statements .= $statement;
- }
+ $statement = $this->parseEach($statement, $method['params']);
+ $statement = $this->expandArrayParams($statement, $method['params']);
- $method['statement'] = $statements;
-
- //generate function parameter list
- /*
- $method['vars'] = trim(implode("\n\t", array_map(
- function ($param) {
- if ($param['in_out'] == 'IN' && ($param['type'] = $this->paramType($param['type']))) {
- return $this->template($this->model['varsTemplate'], $param);
- }
- } ,$method['params'])), "\n\t");
- */
- /*
- $method['param_types'] = 'array(' . trim(implode(', ', array_map(
- function ($param) {
- if ($param['in_out'] == 'IN' && ($type = $this->paramType($param['type']))) {
- return '\'' . $param['name'] . '\' => \'' . $type . '\'';
- }
- } ,$method['params'])), ', ') . ')';
- */
-
- $paramTypes = [];
-
- foreach ($method['params'] as $param) {
- if ($param['in_out'] == 'IN' && ($type = $this->paramType($param['type']))) {
- $paramTypes[$param['name']] = $type;
- }
+ //clean empty sql strings
+ $statement = preg_replace('@\$sql \.= \'\s+\n\s*\';@ms', '$sql .= \' \';', $statement);
+ $statement = preg_replace('@\s*\$sql \.= \'\';@ms', '', $statement);
+
+ if (isset($fetch[$qIndex])) {
+ $method['fetch'] = $this->fetchType($fetch[$qIndex]);
+ } else {
+ if (isset($fetch[0])) {
+ $method['fetch'] = $this->fetchType($fetch[0]);
}
+ }
- $this->paramTypes[$method['name']] = $paramTypes;
+ $statement = $this->template($statement, ['fetch' => $method['fetch']]);
- $method['param_types'] = '$this->paramTypes[\'' . $method['name'] . '\']';
+ $statements .= $statement;
+ }
- $method['fetch'] = $this->fetchType('fetch_all');
+ $method['statement'] = $statements;
- $fetch = false;
- $o = 0;
+ //collect typed IN parameters for bind-param
+ $paramTypes = [];
- foreach ($method['params'] as $param) {
- if ($param['in_out'] == 'OUT') {
- if (! $fetch) {
- $fetch = $param['name'];
- }
+ foreach ($method['params'] as $param) {
+ if ($param['in_out'] === 'IN' && ($type = $this->paramType($param['type']))) {
+ $paramTypes[$param['name']] = $type;
+ }
+ }
- if ($o == $i) {
- $fetch = $param['name'];
+ $this->paramTypes[$method['name']] = $paramTypes;
- break;
- }
- $o++;
- }
+ $method['param_types'] = '$this->paramTypes[\'' . $method['name'] . '\']';
+
+ $method['fetch'] = $this->fetchType('fetch_all');
+
+ //pick the OUT parameter matching the method index, else the first one
+ $fetch = false;
+ $o = 0;
+
+ foreach ($method['params'] as $param) {
+ if ($param['in_out'] === 'OUT') {
+ if (!$fetch) {
+ $fetch = $param['name'];
}
- $method['fetch'] = $this->fetchType($fetch);
-
- $method['params'] = trim(implode(', ', array_map(
- function ($param) {
- if ($param['in_out'] == 'IN') {
- return '$' . $param['name'];
- }
- } ,$method['params'])), ', ');
-
- //if ($queriesCount > 1)
- //{
- $methods .= $this->template($this->model['methodMultipleTemplate'], $method);
- //} else
- //{
- //$methods .= $this->template($this->config['METHOD_TEMPLATE'], $method);
- //}
+ if ($o === $methodIndex) {
+ $fetch = $param['name'];
+
+ break;
+ }
+ $o++;
}
}
- $model = $this->template($this->model['model'],[
- 'name' => ucfirst($this->modelName),
- 'namespace' => ucfirst($this->namespace),
- 'filename' => $this->filename,
- 'methods' => $methods,
- 'filters' => var_export($this->filters, true),
- 'paramTypes' => var_export($this->paramTypes, true),
- ]);
+ $method['fetch'] = $this->fetchType($fetch);
- return $model;
+ $method['params'] = trim(implode(', ', array_map(
+ function($param) {
+ if ($param['in_out'] === 'IN') {
+ return '$' . $param['name'];
+ }
+ },
+ $method['params']
+ )), ', ');
+
+ return $this->template($this->model['methodMultipleTemplate'], $method);
+ }
+
+ /**
+ * Expand ARRAY-typed parameters into db->expandArray() calls embedded in the generated code.
+ *
+ * @param string $statement Generated statement code.
+ * @param list<array<string, mixed>> $params Method parameters.
+ *
+ * @return string Statement with array<array-key, mixed> expansions injected.
+ */
+ private function expandArrayParams(string $statement, array $params): string {
+ foreach ($params as $param) {
+ if (in_array(strtolower($param['type']), ['array', 'rows', 'row'], true)) {
+ $expandArray = '\';' . self::TAB . ' list($_sql, $_params) = $this->db->expandArray($params[\'' . $param['name'] . '\'], \'' . $param['name'] . '\');'
+ . self::TAB . '$sql .= $_sql;'
+ . self::TAB . 'if (is_array($_params)) $paramTypes = array_merge($paramTypes, $_params);'
+ . self::TAB . '$sql .= \' ';
+
+ $statement = preg_replace('@:' . $param['name'] . '(?!_\.) @', $expandArray, $statement);
+ }
+ }
+
+ return $statement;
}
}
diff --git a/system/subscription-manager.php b/system/subscription-manager.php
new file mode 100644
index 0000000..292f5b4
--- /dev/null
+++ b/system/subscription-manager.php
@@ -0,0 +1,272 @@
+<?php
+
+/**
+ * Vvveb
+ *
+ * Copyright (C) 2022 Ziadin Givan
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+namespace Vvveb\System;
+
+class SubscriptionManager {
+ /**
+ * Extract the gateway-side subscription reference from a local row.
+ *
+ * @param array<string, mixed> $subscription Local subscription row.
+ *
+ * @return array{0: string, 1: string}|null [gateway, reference] or null when not provisioned.
+ */
+ public static function gatewayReference(array $subscription): ?array {
+ $reference = (string)($subscription['payment_method'] ?? '');
+
+ if (!str_contains($reference, ':')) {
+ return null;
+ }
+
+ [$gateway, $id] = explode(':', $reference, 2);
+
+ if ($gateway === '' || $id === '') {
+ return null;
+ }
+
+ return [$gateway, $id];
+ }
+
+ /**
+ * Add one billing interval to a date (`day|week|month|year` x cycle).
+ *
+ * @param string $date Base datetime (`Y-m-d H:i:s`).
+ * @param string $period Interval unit.
+ * @param int $cycle Interval multiplier.
+ *
+ * @return string Resulting datetime (`Y-m-d H:i:s`), input on failure.
+ */
+ public static function addInterval(string $date, string $period, int $cycle): string {
+ $cycle = max(1, $cycle);
+ $spec = match ($period) {
+ 'day' => "P{$cycle}D",
+ 'week' => "P{$cycle}W",
+ 'month' => "P{$cycle}M",
+ 'year' => "P{$cycle}Y",
+ default => '',
+ };
+
+ if ($spec === '') {
+ return $date;
+ }
+
+ try {
+ return (new \DateTimeImmutable($date))->add(new \DateInterval($spec))->format('Y-m-d H:i:s');
+ } catch (\Throwable $e) {
+ return $date;
+ }
+ }
+
+ /**
+ * Fetch the offer (price + interval) of a plan for a product.
+ *
+ * @param int $productId Local product id.
+ * @param int $planId Local subscription plan id.
+ * @param int $languageId Language id for plan names.
+ *
+ * @return array<string, mixed> Offer row or empty array<array-key, mixed>.
+ */
+ public static function planOffer(int $productId, int $planId, int $languageId = 1): array {
+ try {
+ $rows = \Vvveb\model('product_subscription')->getAll([
+ 'product_id' => $productId,
+ 'subscription_plan_id' => $planId,
+ 'language_id' => $languageId,
+ ]);
+ } catch (\Throwable $e) {
+ return [];
+ }
+
+ foreach ((array)$rows as $list) {
+ if (is_array($list) && $list && is_array(reset($list))) {
+ return reset($list);
+ }
+ }
+
+ return [];
+ }
+
+ /** Failed payment retry policy: attempt => days after the previous attempt. */
+ public const DUNNING_RETRY_DAYS = [1 => 0, 2 => 1, 3 => 3, 4 => 7];
+
+ public const DUNNING_MAX_ATTEMPTS = 4;
+
+ /**
+ * Canonical dunning note for a failed payment attempt.
+ *
+ * @param int $attempt Attempt number (1-based).
+ * @param string $invoice Gateway invoice reference.
+ *
+ * @return string Note text.
+ */
+ public static function dunningNote(int $attempt, string $invoice): string {
+ return sprintf('Dunning attempt %d/%d for invoice %s', $attempt, self::DUNNING_MAX_ATTEMPTS, $invoice);
+ }
+
+ /**
+ * Parse a dunning note back into attempt data.
+ *
+ * @param string $note Log note text.
+ *
+ * @return array{attempt: int, invoice: string}|null
+ */
+ public static function parseDunningNote(string $note): ?array {
+ if (preg_match('/Dunning attempt (\d+)\/\d+ for invoice (\S+)/', $note, $m)) {
+ return ['attempt' => (int)$m[1], 'invoice' => $m[2]];
+ }
+
+ return null;
+ }
+
+ /**
+ * Record a dunning attempt for a subscription invoice.
+ *
+ * Counts prior attempts for the same invoice from the log so retries
+ * across webhooks and cron runs share one ladder.
+ *
+ * @param int $subscriptionId Local subscription id.
+ * @param string $invoice Gateway invoice reference.
+ * @param int $statusId Status id for the log row.
+ *
+ * @return int Attempt number just recorded (1-based).
+ */
+ public static function recordDunningAttempt(int $subscriptionId, string $invoice, int $statusId = 3): int {
+ $attempt = 1;
+ $suffix = '';
+
+ try {
+ $logs = \Vvveb\model('subscription_log')->getAll(['subscription_id' => $subscriptionId]);
+ $rows = [];
+
+ foreach ((array)$logs as $list) {
+ if (is_array($list) && $list && is_array(reset($list))) {
+ $rows = array_merge($rows, array_values($list));
+ }
+ }
+
+ foreach ($rows as $row) {
+ $parsed = self::parseDunningNote((string)($row['note'] ?? ''));
+
+ if ($parsed && $parsed['invoice'] === $invoice) {
+ $attempt = max($attempt, $parsed['attempt'] + 1);
+ }
+ }
+
+ \Vvveb\model('subscription_log')->add(['subscription_log' => [
+ 'subscription_id' => $subscriptionId,
+ 'subscription_status_id' => $statusId,
+ 'notify' => 0,
+ 'note' => mb_substr(self::dunningNote($attempt, $invoice) . $suffix, 0, 500),
+ 'created_at' => date('Y-m-d H:i:s'),
+ ]]);
+ } catch (\Throwable $e) {
+ }
+
+ return $attempt;
+ }
+
+ /**
+ * Latest dunning attempt across log rows.
+ *
+ * @param array<int, array<string, mixed>> $logs Subscription log rows.
+ *
+ * @return array{attempt: int, invoice: string, created_at: string}|null
+ */
+ public static function latestDunning(array $logs): ?array {
+ $latest = null;
+
+ foreach ($logs as $row) {
+ $parsed = self::parseDunningNote((string)($row['note'] ?? ''));
+
+ if (!$parsed) {
+ continue;
+ }
+
+ $created = (string)($row['created_at'] ?? '');
+
+ if ($latest === null || $created >= $latest['created_at']) {
+ $latest = $parsed + ['created_at' => $created];
+ }
+ }
+
+ return $latest;
+ }
+
+ /**
+ * Run a gateway lifecycle operation for a local subscription row.
+ *
+ * Returns null when there is nothing to do at a gateway (not
+ * provisioned, method unavailable, operation unsupported) so callers
+ * keep the legacy local-only behavior. Returns an error message when
+ * the gateway call failed: callers must NOT change local status then.
+ *
+ * @param string $operation One of cancelSubscription, pauseSubscription,
+ * resumeSubscription, swapSubscription, skipSubscription.
+ * @param array<string, mixed> $subscription Local subscription row.
+ * @param array<string, mixed>|null $order Original order row (authoritative payment method).
+ * @param array<string, mixed> $extra Extra context (e.g. price_id for swaps).
+ *
+ * @return string|null Null on success/local-only, error message on gateway failure.
+ */
+ public static function gatewayOperation(string $operation, array $subscription, ?array $order = null, array $extra = []): ?string {
+ $reference = self::gatewayReference($subscription);
+
+ if (!$reference) {
+ return null;
+ }
+
+ [$gateway, $gatewayId] = $reference;
+ $method = $order['payment_method'] ?? $gateway;
+
+ if (!$method) {
+ return null;
+ }
+
+ try {
+ $payment = Payment::getInstance();
+ $instance = $payment->getMethodInstance((string)$method);
+ } catch (\Throwable $e) {
+ return null;
+ }
+
+ if (!$instance || !$instance->supports($operation)) {
+ return null;
+ }
+
+ $info = [
+ 'gateway_subscription_id' => $gatewayId,
+ 'subscription_id' => $subscription['subscription_id'] ?? 0,
+ 'order_id' => $subscription['order_id'] ?? ($order['order_id'] ?? 0),
+ 'user_id' => $subscription['user_id'] ?? ($order['user_id'] ?? 0),
+ ] + $extra;
+
+ try {
+ if ($instance->{$operation}($info)) {
+ return null;
+ }
+ } catch (\Throwable $e) {
+ return $e->getMessage();
+ }
+
+ return $instance->getError() ?: \Vvveb\__('Gateway operation failed!');
+ }
+}
diff --git a/system/traits/crud.php b/system/traits/crud.php
old mode 100644
new mode 100755
index c4f3f92..2defe3f
--- a/system/traits/crud.php
+++ b/system/traits/crud.php
@@ -29,39 +29,65 @@ use function Vvveb\sanitizeHTML;
use Vvveb\System\Images;
trait Crud {
- protected $module;
+ /** @var string Module name (e.g. 'blog', 'shop'). */
+ protected string $module = '';
- protected $type;
+ /** @var string Entity type name used as the primary key suffix. */
+ protected string $type = '';
- protected $controller;
+ /** @var string Controller name; defaults to when null. */
+ protected string $controller = '';
- protected $redirect = true;
+ /** @var string|bool Redirect target after save. true = auto-redirect, false = no redirect, string = custom URL. */
+ protected string|bool $redirect = true;
- protected $data_id;
+ /** @var string Current entity primary key value. */
+ protected string $data_id = '';
- protected $type_id;
+ /** @var string Column name used as primary key; defaults to "{type}_id". */
+ protected string $type_id = '';
- protected $model;
+ /** @var string Slug from the request. */
+ protected string $slug = '';
- protected $options = [];
+ /** @var object|null Model instance. */
+ protected ?object $model = null;
- protected $data = [];
+ /** @var array<string, mixed> Additional options merged into every query. */
+ protected array $options = [];
- //protected $fullPost;
+ /** @var array<string, mixed> Request data being processed. */
+ protected array $data = [];
- protected $userFilter = false;
-
- protected $adminFilter = true;
-
- function delete() {
- if (APP == 'admin') {
+ /** @var bool Whether to apply user_id filter in queries. */
+ protected bool $userFilter = false;
+
+ /** @var bool Whether to apply admin_id filter in queries. */
+ protected bool $adminFilter = true;
+
+ /** @var string Model class name; set by the controller. */
+ protected string $modelName = '';
+
+ /** @var bool When true, the full POST array<array-key, mixed> is used instead of->post[$type]. */
+ protected bool $fullPost = false;
+
+ /**
+ * Delete one or more entities by primary key.
+ *
+ * Reads the type ID from the request, calls the model delete method,
+ * and displays a success or error message via the view.
+ *
+ * @return array<string, mixed> The index data after deletion.
+ */
+ public function delete(): array {
+ if (APP === 'admin') {
$this->checkCsrf();
}
$type = $this->type;
- $type_id = $this->type_id ?? "{$type}_id";
+ $type_id = $this->type_id ?: "{$type}_id";
- if (APP == 'admin') {
+ if (APP === 'admin') {
$data_id = $this->request->post[$type_id];
} else {
$data_id = $this->request->post[$type_id] ?? $this->request->get[$type_id] ?? false;
@@ -72,9 +98,7 @@ trait Crud {
$data_id = [$data_id];
}
- if (! isset($this->modelName)) {
- $modelName = $type;
- }
+ $modelName = $this->modelName ?: $type;
$model = model($modelName);
$options = [$type_id => $data_id] + $this->global;
@@ -85,7 +109,7 @@ trait Crud {
if ($result[$type]) {
$this->view->success[] = sprintf(__('%s(s) deleted!'), humanReadable($name));
} else {
- $this->view->info[] = sprintf(__('No rows affected!'), humanReadable($name));
+ $this->view->info[] = __('No rows affected!');
}
} else {
$this->view->errors[] = sprintf(__('Error deleting %s!'), humanReadable($name));
@@ -95,34 +119,43 @@ trait Crud {
return $this->index();
}
- function save() {
+ /**
+ * Save (create or update) an entity from submitted POST data.
+ *
+ * Determines whether to insert or update based on the presence of a
+ * primary key value in the request. Handles timestamps, sanitisation,
+ * and optional redirect after save.
+ *
+ * @return array<string, mixed> The model result or index data.
+ */
+ public function save(): array {
$type = $this->type;
$module = $this->module;
- $controller = $this->controller ?? $type;
+ $controller = $this->controller ?: $type;
$result = [];
- $type_id = $this->type_id ?? "{$type}_id";
+ $type_id = $this->type_id ?: "{$type}_id";
$this->data_id = $this->request->get[$type_id] ?? false;
- if (isset($this->fullPost) && $this->fullPost) {
+ if ($this->fullPost) {
$this->data = $this->request->post ?? [];
} else {
$this->data = $this->request->post[$type] ?? [];
}
if ($this->data) {
- if (! isset($this->modelName)) {
+ if (empty($this->modelName)) {
$this->modelName = $type;
}
$this->model = model($this->modelName);
- if (! $this->data_id) {
- $this->data['created_at'] = $this->data['created_at'] ?? date('Y-m-d H:i:s');
+ if (!$this->data_id) {
+ $this->data['created_at'] ??= date('Y-m-d H:i:s');
}
- $this->data['updated_at'] = $this->data['updated_at'] ?? date('Y-m-d H:i:s');
+ $this->data['updated_at'] ??= date('Y-m-d H:i:s');
- if (isset($this->fullPost) && $this->fullPost) {
+ if ($this->fullPost) {
$options = $this->data + $this->global;
} else {
$options = [$type => $this->data] + $this->global;
@@ -148,7 +181,7 @@ trait Crud {
$this->view->success['get'] = $successMessage;
$this->session->set('success', ['get' => $successMessage]);
- if (! $this->data_id && $this->redirect) {
+ if (!$this->data_id && $this->redirect) {
if ($this->redirect === true) {
$this->redirect(['module' => "$module/$controller", $type_id => $result[$type], 'success' => $successMessage]);
} else {
@@ -161,21 +194,30 @@ trait Crud {
}
if ($this->redirect) {
- return $this->index();
+ $this->index();
}
return $result;
}
- protected function index() {
+ /**
+ * Load a single entity or an empty data set for the edit/create form.
+ *
+ * When a primary key or slug is present in the request, the model is
+ * queried for the corresponding record. Otherwise an empty array is
+ * returned so the view can render a "create new" form.
+ *
+ * @return array<string, mixed> The entity data array<array-key, mixed>.
+ */
+ protected function index(): array {
$type = $this->type;
- $type_id = $this->type_id ?? "{$type}_id";
+ $type_id = $this->type_id ?: "{$type}_id";
$this->data_id = $this->request->get[$type_id] ?? false;
- $this->slug = $this->request->get['slug'] ?? false;
+ $this->slug = $this->request->get['slug'] ?? '';
$this->data = [];
if ($this->data_id || $this->slug) {
- if (! isset($this->modelName)) {
+ if (empty($this->modelName)) {
$this->modelName = $type;
}
@@ -190,13 +232,12 @@ trait Crud {
}
$this->options += $this->global + $this->request->get;
- //unset($this->options['user_id']);
- if (! $this->userFilter) {
+ if (!$this->userFilter) {
unset($this->options['user_id']);
}
- if (! $this->adminFilter) {
+ if (!$this->adminFilter) {
unset($this->options['admin_id']);
}
diff --git a/system/traits/edit.php b/system/traits/edit.php
new file mode 100644
index 0000000..eff8f4d
--- /dev/null
+++ b/system/traits/edit.php
@@ -0,0 +1,447 @@
+<?php
+
+/**
+ * Vvveb
+ *
+ * Copyright (C) 2022 Ziadin Givan
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+namespace Vvveb\System\Traits;
+
+use function Vvveb\__;
+use function Vvveb\getSetting;
+use function Vvveb\model;
+use function Vvveb\sanitizeHTML;
+use function Vvveb\setSetting;
+use function Vvveb\slugify;
+use Vvveb\Sql\CategorySQL;
+use Vvveb\System\CacheManager;
+use Vvveb\System\Event;
+use Vvveb\System\Images;
+use Vvveb\System\Validator;
+
+trait Edit {
+ /**
+ * Resolve list/index routes for an object type.
+ *
+ * @param string $object Object name (post, product, ...).
+ * @param string $type Post type, may equal $object.
+ *
+ * @return array{0: string, 1: string, 2: string} Route, alternate route and controller group.
+ */
+ protected function editContentRoutes(string $object, string $type): array {
+ if ($object == 'product') {
+ $route = "product/{$type}/index";
+ $altRoute = "product/{$object}/index";
+ $controller = 'product';
+ } else {
+ $route = "content/{$type}/index";
+ $altRoute = "content/{$object}/index";
+ $controller = 'content';
+ }
+
+ return [$route, $altRoute, $controller];
+ }
+
+ /**
+ * Load a post record with image URLs plus its content URLs and revisions.
+ *
+ * @param string $object Object name (post, product, ...).
+ * @param string $type Post type, may equal $object.
+ * @param int|string|false $postId Record id, or false for a new record.
+ * @param string|false $slug Slug lookup when no id is given.
+ * @param string|null $typeParam Type override, null to keep $type.
+ * @param array<string,mixed> $global Global context (site_id, host, path, admin_id, ...).
+ * @param array<int,mixed> $languagesList Languages list keyed by code.
+ * @param bool $canViewOthers Whether records of other admins may be loaded.
+ *
+ * @return array{0: array<string,mixed>|null, 1: mixed, 2: string, 3: string, 4: string} Post (null when not found), id, resolved type, default-language name and revisions url.
+ */
+ protected function getEditPostData(string $object, string $type, int|string|false $postId, string|false $slug, ?string $typeParam, array $global, array $languagesList, bool $canViewOthers): array {
+ $post = [];
+ $postOptions = [];
+
+ if ($typeParam) {
+ $type = $typeParam;
+ }
+
+ if ($postId) {
+ $postOptions[$object . '_id'] = (int)$postId;
+ } else {
+ if ($slug) {
+ $postOptions['slug'] = $slug;
+ }
+ }
+
+ if ($postOptions) {
+ $posts = model($object);
+
+ $postOptions['type'] = $type;
+ $options = $postOptions + $global;
+
+ if ($canViewOthers) {
+ unset($options['admin_id']);
+ } else {
+ $options['admin_id'] = $global['admin_id'];
+ }
+
+ //get all languages
+ //unset($options['language_id']);
+ $post = $posts->get($options);
+
+ if (!$post) {
+ return ['post' => null, 'post_id' => $postId, 'type' => $type];
+ }
+
+ //featured image
+ if (isset($post['image'])) {
+ $post['image_url'] = Images::image($post['image'], $object);
+ }
+
+ //gallery
+ if (isset($post[$object . '_image'])) {
+ $post['images'] = Images::images($post[$object . '_image'], $object);
+ }
+
+ //$productImages = $posts->getImages($postOptions);
+ } else {
+ $post['image_url'] = Images::image('', $object);
+ $post['updated_at'] = date('Y-m-d H:i:s', time());
+ }
+
+ $type = $post['type'] ?? $type;
+
+ [$route, $altRoute, $controller] = $this->editContentRoutes($object, $type);
+
+ if ($object != 'product') {
+ $stickyPosts = getSetting('posts', 'sticky') ?? [];
+ //$post['sticky'] = in_array($post['post_id'], $stickyPosts);
+ $post['sticky'] = isset($post['post_id'], $stickyPosts[$post['post_id']]);
+ }
+
+ if ($this->editRevisionsEnabled($object)) {
+ $revisions = model($object . '_content_revision');
+ } else {
+ $revisions = false;
+ }
+
+ //get site host for current selected site to use for absolute url
+ $url = ['host' => $global['host'], 'path' => $global['path'] ? '/' . $global['path'] : null];
+
+ if ($type != $object) {
+ $url['type'] = $type;
+ }
+
+ $revisionsUrl = \Vvveb\url(['module' => "$controller/revisions", 'object' => $object, 'type' => $type, $object . '_id' => $postId]);
+ $name = '';
+
+ if (isset($post[$object . '_content'])) {
+ foreach ($post[$object . '_content'] as &$content) {
+ if (!isset($post['url'])) {
+ $post['url'] = \Vvveb\url($route, ['slug' => $content['slug'], $object . '_id' => $postId] + $url);
+ $post['relative-url'] = \Vvveb\url($route, ['slug' => $content['slug'], $object . '_id' => $postId]);
+
+ if (!$post['url'] || $post['url'] == '//' . $global['site_url']) {
+ $post['url'] = \Vvveb\url($altRoute, ['slug' => $content['slug'], $object . '_id' => $postId] + $url);
+ $post['relative-url'] = \Vvveb\url($altRoute, ['slug' => $content['slug'], $object . '_id' => $postId]);
+ }
+ }
+ $language = [];
+
+ if ($content['language_id'] != $global['default_language_id']) {
+ $code = 'en_US';
+
+ foreach ($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'] == '//' . $global['site_url']) {
+ $content['url'] = \Vvveb\url($altRoute, $content + $language + $url);
+ }
+
+ if ($revisions) {
+ $revision = $revisions->getAll([$object . '_id' => $postId, 'language_id' => $content['language_id']]);
+
+ if ($revision) {
+ foreach ($revision[$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[$object . '_content_revision'];
+ }
+ }
+ }
+ }
+
+ [$post, $postId, $type] = Event :: trigger(__CLASS__, 'index', $post, $postId, $type);
+
+ return [$post, $postId, $type, $name, $revisionsUrl];
+ }
+
+ /**
+ * Whether content revisions apply. Controllers override the $revisions
+ * property; extracted so the trait stays decoupled from controller state.
+ *
+ * @param string $object Object name (unused, kept for overrides).
+ *
+ * @return bool True when revisions should be loaded and saved.
+ */
+ protected function editRevisionsEnabled(string $object): bool {
+ return (bool)($this->revisions ?? true);
+ }
+
+ /**
+ * Adds a new category taxonomy item.
+ *
+ * @param int $taxonomy_id The taxonomy ID.
+ * @param string $name The category name.
+ * @param array<string,mixed> $global Global context.
+ *
+ * @return int The new taxonomy_item ID.
+ */
+ protected function addEditCategory(int $taxonomy_id, string $name, array $global): int {
+ $categories = new CategorySQL();
+ $cat = $categories->addCategory([
+ 'taxonomy_item' => $global + [
+ 'taxonomy_id' => $taxonomy_id,
+ ],
+ 'taxonomy_item_content' => $global + ['slug' => slugify($name), 'name' => $name, 'content' => ''],
+ ] + $global);
+
+ return $category_id = $cat['taxonomy_item'];
+ }
+
+ /**
+ * Resolve new tag names to taxonomy_item ids, appending them to the post.
+ *
+ * @param array<string,mixed> $post Post input with optional tag lists.
+ * @param array<string,mixed> $global Global context.
+ *
+ * @return array<string,mixed> Post input with taxonomy_item_id list filled.
+ */
+ protected function processEditTags(array $post, array $global): array {
+ //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->addEditCategory($listId, $tag, $global);
+ }
+ $post['taxonomy_item_id'][] = $tagId;
+ }
+ }
+ }
+
+ return $post;
+ }
+
+ /**
+ * Flatten custom field input to post_field_value rows.
+ *
+ * @param mixed $fields Field input keyed by language then field id.
+ *
+ * @return list<array<string,mixed>> Field value rows.
+ */
+ protected function flattenEditFieldValues(mixed $fields): array {
+ $post_field_value = [];
+
+ if (isset($fields) && is_array($fields)) {
+ foreach ($fields as $language_id => $fieldList) {
+ foreach ($fieldList 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];
+ }
+ }
+ }
+
+ return $post_field_value;
+ }
+
+ /**
+ * Validate and save post/page content: tags, fields, images, revisions and cache.
+ *
+ * @param string $object Object name (post, product, ...).
+ * @param string $type Post type.
+ * @param array<string,mixed> $input Raw post input (request post equivalent).
+ * @param array<string,mixed> $global Global context.
+ * @param bool $canEditOthers Whether records of other admins may be edited.
+ * @param bool $withRevisions Whether to store content revisions.
+ *
+ * @return array{ok: bool, post: array<string,mixed>, post_id: mixed, new: bool, message: string|null, errors: array<array-key, mixed>|null} Save outcome.
+ */
+ protected function saveEditData(string $object, string $type, array $input, array $global, bool $canEditOthers, bool $withRevisions): array {
+ $post_id = $input[$object . '_id'] ?? false;
+ $validator = new Validator([$object]);
+ $validatorContent = new Validator([$object . '_content']);
+
+ $postContent = $input[$object . '_content'] ?? [];
+
+ if (!is_array($postContent)) {
+ $postContent = [];
+ }
+
+ if (
+ (($errors = $validator->validate($input)) === true) &&
+ (($errors = $validatorContent->validate(current($postContent))) === true)
+ ) {
+ $posts = model($object);
+
+ $post = $input;
+
+ foreach ($post[$object . '_content'] as &$content) {
+ $content['name'] = strip_tags($content['name']);
+ $content['content'] = sanitizeHTML($content['content']);
+
+ if (isset($content['excerpt'])) {
+ $content['excerpt'] = sanitizeHTML($content['excerpt']);
+ }
+ }
+
+ $post = $this->processEditTags($post, $global);
+
+ //process fields
+ $post_field_value = $this->flattenEditFieldValues($post['field'] ?? null);
+
+ $site_id = $input['site'] ?? []; //[$global['site_id']];
+
+ $post += $global;
+ $new = false;
+
+ if ($post_id) {
+ if (!$canEditOthers) {
+ return ['ok' => false, 'post' => $post, 'post_id' => $post_id, 'new' => false, 'message' => null, 'errors' => [__('Permission denied!')]];
+ }
+
+ $post[$object . '_id'] = (int)$post_id;
+ $data = [
+ $object => $post,
+ $object . '_id' => $post_id,
+ $object . '_content' => $post[$object . '_content'],
+ 'taxonomy_item_id' => $post['taxonomy_item_id'] ?? [],
+ 'post_field_value' => $post_field_value,
+ 'site_id' => $site_id,
+ ] + $global;
+
+ $result = $posts->edit($data);
+
+ if ($result >= 0) {
+ $message = ucfirst($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 ($withRevisions) {
+ $revisions = model($object . '_content_revision');
+
+ foreach ($input[$object . '_content'] as &$content) {
+ if (isset($content['has_changes']) && $content['has_changes'] == 1) {
+ $revisions->add(['revision' => [
+ $object . '_id' => $post_id,
+ 'language_id' => $content['language_id'],
+ 'content' => $content['content'],
+ 'created_at' => date("Y-m-d\TH:i:s", time()),
+ ] + $global]);
+ }
+ }
+ }
+ } else {
+ return ['ok' => false, 'post' => $post, 'post_id' => $post_id, 'new' => false, 'message' => null, 'errors' => [$posts->error]];
+ }
+ } else {
+ $post['type'] = $type;
+
+ if (isset($post['updated_at']) && !$post['updated_at']) {
+ unset($post['updated_at'], $post[$object . '_id']);
+ }
+
+ $add = [
+ $object => $post,
+ $object . '_content' => $post[$object . '_content'],
+ 'taxonomy_item_id' => $post['taxonomy_item_id'] ?? [],
+ 'post_field_value' => $post_field_value,
+ 'site_id' => $site_id,
+ ] + $global;
+
+ $return = $posts->add($add);
+ $id = $return[$object] ?? false;
+
+ if (!$id) {
+ return ['ok' => false, 'post' => $post, 'post_id' => $post_id, 'new' => false, 'message' => null, 'errors' => [$posts->error]];
+ }
+
+ $post_id = $id;
+ $new = true;
+
+ $message = ucfirst($type) . ' ' . __('saved') . '!';
+
+ if (isset($post['sticky'])) {
+ $stickyPosts = getSetting('posts', 'sticky') ?? [];
+ $stickyPosts[$post_id] = $post_id;
+ setSetting('posts', 'sticky', $stickyPosts);
+ }
+ }
+
+ if (isset($post[$object . '_image'])) {
+ $publicPath = \Vvveb\publicUrlPath();
+ $productImage = $object . 'Image';
+
+ foreach ($post[$object . '_image'] as &$image) {
+ $image = str_replace($publicPath . 'media/', '', $image);
+ }
+
+ $posts->$productImage([$object . '_id' => $post_id ? $post_id : 0, $object . '_image' => $post[$object . '_image']]);
+ }
+
+ [$post, $post_id, $type] = Event :: trigger(__CLASS__, 'save', $post, $post_id, $type);
+
+ CacheManager::clearObjectCache('component', $object);
+ CacheManager::clearObjectCache('component', $object . 's');
+ CacheManager::clearPageCache();
+
+ return ['ok' => true, 'post' => $post, 'post_id' => $post_id, 'new' => $new, 'message' => $message ?? null, 'errors' => null];
+ }
+
+ return ['ok' => false, 'post' => $input, 'post_id' => $post_id, 'new' => false, 'message' => null, 'errors' => $errors];
+ }
+}
diff --git a/system/traits/field-group.php b/system/traits/field-group.php
index 07996f3..0ac9427 100644
--- a/system/traits/field-group.php
+++ b/system/traits/field-group.php
@@ -25,7 +25,14 @@ namespace Vvveb\System\Traits;
use function Vvveb\__;
trait FieldGroup {
- function renderFields2($fields) {
+ /**
+ * Render a fields array to HTML using the field-group template.
+ *
+ * @param array<array-key, mixed> $fields The fields configuration array.
+ *
+ * @return string The rendered HTML (body content only).
+ */
+ public function renderFields2(array $fields): string {
$htmlView = new \Vvveb\System\Core\View();
$htmlView->setTheme();
$htmlView->template('field/field-group/renderfields.html');
@@ -34,35 +41,51 @@ trait FieldGroup {
$html = $htmlView->render(true, false, true);
//return only content inside <body>
- $html = preg_replace('@<!DOCTYPE[^>]+>|</?html>|</?body>@', '', $html);
-
- return $html;
+ return (string)preg_replace('@<!DOCTYPE[^>]+>|</?html>|</?body>@', '', $html);
}
- function field() {
+ /**
+ * Handle AJAX field rendering requests.
+ *
+ * Reads the field type and ID from the POST request, renders the field,
+ * and returns JSON.
+ *
+ * @return string JSON-encoded field rendering result.
+ */
+ public function field(): string {
$type = $this->request->post['type'] ?? 'text';
- $field_id = $this->request->post['field_id'];
+
+ $field_id = $this->request->post['field_id'] ?? '';
$json = $this->renderField($type, $field_id);
$this->response->setType('json');
- return $json;
+ return is_string($json) ? $json : json_encode($json);
}
- private function renderField($type, $field_id, $input = []) {
+ /**
+ * Render a single field's settings, validation, and presentation sections.
+ *
+ * @param string $type The field type (e.g. 'text', 'image', 'select').
+ * @param int|string $field_id Unique field identifier.
+ * @param array<string, mixed> $input Optional pre-filled input values for the field sections.
+ *
+ * @return array<string, string>|null Rendered HTML sections keyed by section name, or null on error.
+ */
+ private function renderField(string $type, int|string $field_id, array $input = []): ?array {
$fields = [];
$data = [];
$json = [];
foreach (['settings', 'validation', 'presentation', 'conditionals'] as $section) {
- $input[$section] = $input[$section] ?? $this->request->post['field'][$field_id][$section] ?? [];
+ $input[$section] ??= $this->request->post['field'][$field_id][$section] ?? [];
}
$field = ucfirst($type);
$fieldClass = "Vvveb\System\Fields\\$field";
- if (! class_exists($fieldClass)) {
- return;
+ if (!class_exists($fieldClass)) {
+ return null;
}
$fieldObj = new $fieldClass();
@@ -70,34 +93,32 @@ trait FieldGroup {
$data['validation'] = $fieldObj->getValidation();
$data['presentation'] = $fieldObj->getPresentation();
- foreach ($data as $section => $field) {
- foreach ($field as $name => $value) {
- if (! $value) {
+ foreach ($data as $section => $fieldData) {
+ foreach ($fieldData as $name => $value) {
+ if (!$value) {
continue;
}
- /*
- if (isset($this->request->post['field'][$field_id][$section][$name])) {
- $data[$section][$name]['value'] = $this->request->post['field'][$field_id][$section][$name];
- }
- */
+
if (isset($input[$section][$name])) {
$data[$section][$name]['value'] = $input[$section][$name];
}
$data[$section][$name]['id'] = $name;
$data[$section][$name]['name'] = "field[$field_id][$section][$name]";
- $data[$section][$name]['class'] = ($value['type'] != 'hidden') ? 'row mb-3' : '';
+ $data[$section][$name]['class'] = ($value['type'] !== 'hidden') ? 'row mb-3' : '';
$data[$section][$name]['label-class'] = 'col-sm-2 col-form-label py-0';
$data[$section][$name]['input-class'] = 'col-sm-10 col-xl-8 col-xxl-6';
- if ($value['type'] == 'checkbox' && (isset($this->request->post['field'][$field_id][$section][$name]) || isset($input[$section][$name]))) {
+ if ($value['type'] === 'checkbox' && (isset($this->request->post['field'][$field_id][$section][$name]) || isset($input[$section][$name]))) {
$data[$section][$name]['checked'] = true;
}
}
}
//check if we have a complex value (json array) or a single value
+ $value = null;
if ($fieldClass::valueType) {
+ $value = [];
foreach ($fieldClass::valueType as $name) {
$value[$name] = $data['settings'][$name]['value'] ?? '';
}
@@ -109,21 +130,14 @@ trait FieldGroup {
'label' => $data['settings']['label']['value'] ?? __('Label'),
'instructions' => $data['presentation']['instructions']['value'] ?? __('Instructions'),
'name' => 'label',
- //'id' => 'input-' . $field_id,
'type' => $type,
'label-class' => 'form-label',
'placeholder' => $data['settings']['label']['value'] ?? __('Placeholder'),
'readonly' => true,
'value' => $value,
- //'required' => $data['validation']['required']['checked'] ?? '',
] + $input['presentation'] + $input['settings'];
- foreach ($field as $name => $value) {
- /*
- if (isset($this->request->post['field'][$field_id]['settings'][$name])) {
- $field[$name] = $this->request->post['field'][$field_id]['settings'][$name];
- }*/
-
+ foreach ($field as $name => $fieldValue) {
if (isset($input[$section][$name])) {
$field[$name] = $input[$section][$name];
}
@@ -139,18 +153,27 @@ trait FieldGroup {
return $json;
}
- function renderFields() {
+ /**
+ * Render field configuration forms for the admin UI.
+ *
+ * Handles two modes:
+ * - 'field': returns a specific field type's settings/validation/presentation sections.
+ * - 'input': returns a generic input field definition.
+ *
+ * @return void
+ */
+ public function renderFields(): void {
$type = $this->request->get['type'] ?? '';
$fields = [];
- if ($type == 'field') {
+ if ($type === 'field') {
$field = $this->request->get['field'] ?? 'text';
$section = $this->request->get['section'] ?? 'settings';
$field = ucfirst($field);
$fieldClass = "Vvveb\System\Fields\\$field";
- if (! class_exists($fieldClass)) {
+ if (!class_exists($fieldClass)) {
return;
}
@@ -164,15 +187,16 @@ trait FieldGroup {
case 'validation':
$fields = $fieldObj->getValidation();
-
+ // fall through to presentation (missing break is intentional)
+ // no break
case 'presentation':
$fields = $fieldObj->getPresentation();
break;
}
- foreach ($fields as $fieldName => $field) {
- foreach ($field as $name => $value) {
+ foreach ($fields as $fieldName => $fieldData) {
+ foreach ($fieldData as $name => $value) {
if (isset($this->request->post[$fieldName][$name])) {
$fields[$fieldName][$name] = $this->request->post[$fieldName][$name];
}
@@ -180,7 +204,7 @@ trait FieldGroup {
}
}
- if ($type == 'input') {
+ if ($type === 'input') {
$field = [
'label' => __('Label'),
'instructions' => __('Instructions'),
@@ -188,7 +212,6 @@ trait FieldGroup {
'type' => 'text',
'class' => 'form-label',
'placeholder' => 'placeholder',
- //'value' => 'value',
];
foreach ($field as $name => $value) {
diff --git a/system/traits/field.php b/system/traits/field.php
new file mode 100755
index 0000000..d392ff0
--- /dev/null
+++ b/system/traits/field.php
@@ -0,0 +1,54 @@
+<?php
+
+/**
+ * Vvveb
+ *
+ * Copyright (C) 2022 Ziadin Givan
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+namespace Vvveb\System\Traits;
+
+trait Field {
+ /** @var array<string, mixed> */
+ protected array $settings = [];
+
+ /** @var array<string, mixed> */
+ protected array $validation = [];
+
+ /** @var array<string, mixed> */
+ protected array $presentation = [];
+
+ /** @var array<string, mixed> */
+ protected array $defaultSettings = [];
+
+ /** @var array<string, mixed> */
+ protected array $defaultValidation = [];
+
+ /** @var array<string, mixed> */
+ protected array $defaultPresentation = [];
+
+ /**
+ * Extend current field configuration by merging defaults.
+ *
+ * @return void
+ */
+ public function extend(): void {
+ $this->settings = $this->defaultSettings + $this->settings;
+ $this->validation = $this->defaultValidation + $this->validation;
+ $this->presentation = $this->defaultPresentation + $this->presentation;
+ }
+}
diff --git a/system/traits/listing.php b/system/traits/listing.php
index 2b77b62..9412168 100644
--- a/system/traits/listing.php
+++ b/system/traits/listing.php
@@ -28,39 +28,70 @@ use function Vvveb\model;
use Vvveb\System\Images;
trait Listing {
- protected $module;
+ /** @var string Module name (e.g. 'blog', 'shop'). */
+ protected string $module = '';
- protected $type;
+ /** @var string Entity type name used as the primary key suffix. */
+ protected string $type = '';
- protected $list;
+ /** @var string List identifier; defaults to when null. */
+ protected string $list = '';
- protected $type_id;
+ /** @var string Column name used as primary key; defaults to "{type}_id". */
+ protected string $type_id = '';
- protected $data_id;
+ /** @var string Column name used as a secondary data identifier. */
+ protected string $data_id = '';
- protected $model;
+ /** @var object|null Model instance. */
+ protected ?object $model = null;
- protected $modelName;
+ /** @var string Model class name; set by the controller. */
+ protected string $modelName = '';
- protected $userFilter = false;
-
- protected $adminFilter = true;
+ /** @var bool Whether to apply user_id filter in queries. */
+ protected bool $userFilter = false;
- protected $options = [];
+ /** @var bool Whether to apply admin_id filter in queries. */
+ protected bool $adminFilter = true;
- function init() {
- if (isset($this->request->get['type'])) {
- //$this->type = $this->request->get['type'];
- }
+ /** @var array<string, mixed> Additional options merged into every query. */
+ protected array $options = [];
+
+ /** @var string Controller name; defaults to when null. */
+ protected string $controller = '';
+
+ /** @var string List controller name; defaults to when null. */
+ protected string $listController = '';
+
+ /** @var array<string, mixed> Current filter parameters from the request. */
+ protected array $filter = [];
+ /** @var string Slug from the request. */
+ protected string $slug = '';
+
+ /**
+ * Initialise the listing controller.
+ *
+ * @return mixed Parent init result.
+ */
+ public function init(): ?string {
return parent::init();
}
- function delete() {
+ /**
+ * Delete one or more entities by primary key.
+ *
+ * Reads the type ID from the request, calls the model delete method,
+ * and displays a success or error message via the view.
+ *
+ * @return array<string, mixed> The listing data after deletion.
+ */
+ public function delete(): void {
$type = $this->type;
- $type_id = $this->type_id ?? "{$type}_id";
+ $type_id = $this->type_id ?: "{$type}_id";
- if (APP == 'admin') {
+ if (APP === 'admin') {
$data_id = $this->request->post[$type_id];
} else {
$data_id = $this->request->post[$type_id] ?? $this->request->get[$type_id] ?? false;
@@ -71,17 +102,17 @@ trait 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;
- if (! $this->adminFilter) {
+ if (!$this->adminFilter) {
unset($options['admin_id']);
}
-
+
$result = $model->delete($options);
$name = ucfirst(__($type));
@@ -89,7 +120,7 @@ trait Listing {
if ($result[$type]) {
$this->view->success[] = sprintf(__('%s(s) deleted!'), humanReadable($name));
} else {
- $this->view->info[] = sprintf(__('No rows affected!'), humanReadable($name));
+ $this->view->info[] = __('No rows affected!');
}
} else {
$this->view->errors[] = sprintf(__('Error deleting %s!'), humanReadable($name));
@@ -98,43 +129,44 @@ trait Listing {
unset($this->request->get[$type_id]);
- return $this->index();
+ $this->index();
}
- function index() {
+ /**
+ * Fetch and return a paginated list of entities.
+ *
+ * Applies pagination, filters, and optional image URL resolution from
+ * the model results.
+ *
+ * @return array<string, mixed> Results array<array-key, mixed> keyed by entity type, plus query options.
+ */
+ public function index(): array {
$type = $this->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;
$this->filter = $this->request->get['filter'] ?? [];
- if (! isset($this->modelName)) {
+ if (empty($this->modelName)) {
$this->modelName = $type;
}
$model = model($this->modelName);
- $page = max($this->request->get['page'] ?? 1, 1);
+ $page = max((int)($this->request->get['page'] ?? 1), 1);
$limit = (int)($this->request->get['limit'] ?? 10);
$start = ($page - 1) * $limit;
$options = [
'start' => $start,
'limit' => $limit,
- //'type' => $this->type,
] + $this->global + $this->filter + $this->request->get;
- if (! $this->userFilter) {
+ if (!$this->userFilter) {
unset($options['user_id']);
}
- if (! $this->adminFilter) {
+ if (!$this->adminFilter) {
unset($options['admin_id']);
}
-
+
if ($this->data_id && ($id = $this->request->get[$this->data_id] ?? false)) {
$options[$this->data_id] = $id;
}
@@ -144,10 +176,12 @@ trait Listing {
if (isset($results[$type])) {
foreach ($results[$type] as $id => &$row) {
if (isset($row['images'])) {
- $row['images'] = json_decode($row['images'], 1);
+ $row['images'] = json_decode($row['images'], true);
- foreach ($row['images'] as &$image) {
- $image = Images::image($image, $type);
+ if (is_array($row['images'])) {
+ foreach ($row['images'] as &$image) {
+ $image = Images::image($image, $type);
+ }
}
} else {
if (isset($row['image'])) {
diff --git a/system/traits/permission.php b/system/traits/permission.php
index 2284148..8f7d39e 100644
--- a/system/traits/permission.php
+++ b/system/traits/permission.php
@@ -27,66 +27,108 @@ use Vvveb\System\Core\FrontController;
use Vvveb\System\User\Admin;
trait Permission {
- /*
- * Permission check for each module/action
+ /** @var string Module name override. */
+ protected string $module = '';
+
+ /** @var string Action name override. */
+ protected string $action = '';
+
+ /** @var string[]|null List of additional permission strings to check. */
+ protected ?array $additionalPermissionCheck = null;
+
+ /**
+ * Permissions map keyed by full "module/action" paths.
+ *
+ * @var array<string, bool>
+ */
+ protected array $modulePermissions = [];
+
+ /**
+ * Permissions map keyed by action name only (module prefix stripped).
+ *
+ * @var array<string, bool>
*/
- protected function permission($permission = null) {
+ protected array $actionPermissions = [];
+
+ /**
+ * Verify that the current admin user has the given permission.
+ *
+ * If the permission is denied, a 403 error page is shown and execution stops.
+ *
+ * @param string|null $permission The permission string (e.g. 'blog/edit'). When null it
+ * is derived from the current module/action.
+ *
+ * @return void
+ */
+ protected function permission(?string $permission = null): void {
$module = strtolower(FrontController::getModuleName());
$action = strtolower(FrontController::getActionName());
- $action = ($action && $action != 'index') ? '/' . $action : '';
- $permission = $permission ?? ($module . $action);
+ $action = ($action && $action !== 'index') ? '/' . $action : '';
+ $permission ??= ($module . $action);
- //if current module/action does not have permission then show permission denied page
- if (! Admin::hasPermission($permission)) {
+ if (!Admin::hasPermission($permission)) {
$message = __('Your role does not have permission to access this action!');
$this->view->errors[] = $message;
$adminPath = \Vvveb\adminPath();
$data = ['message' => $message];
- if (APP == 'admin') {
+ if (APP === 'admin') {
$data['adminPath'] = $adminPath;
}
- $this->notFound($data, 403);
+ $this->notFound($data, 403, true);
- die();
+ exit();
}
}
- protected function setPermissions() {
- $module = $this->module ?? strtolower(FrontController::getModuleName());
- $action = $this->action ?? strtolower(FrontController::getActionName());
- $action = ($action && $action != 'index') ? '/' . $action : '';
+ /**
+ * Build permission arrays for the current controller's methods.
+ *
+ * Populates $this->modulePermissions and $this->actionPermissions so
+ * that views can conditionally render UI elements.
+ *
+ * @return void
+ */
+ protected function setPermissions(): void {
+ $module = $this->module ?: strtolower(FrontController::getModuleName());
+ $action = $this->action ?: strtolower(FrontController::getActionName());
+ $action = ($action && $action !== 'index') ? '/' . $action : '';
- //get current controller methods to check for permission
$methods = get_class_methods($this);
- //$methods = array_map(fn ($value) => "$module/$value", $methods);
- $methods = array_map(function ($value) use ($module) {return ($value == 'index') ? $module : "$module/$value"; }, $methods);
+ $methods = array_map(fn (string $value): string => ($value === 'index') ? $module : "$module/$value", $methods);
- //check if controller requires additional permission check
- if (isset($this->additionalPermissionCheck)) {
+ if ($this->additionalPermissionCheck !== null) {
$methods = array_merge($methods, $this->additionalPermissionCheck);
}
$permissions = Admin::hasPermission($methods);
- //set a permission array only with action keys for easier permission check in html
$this->modulePermissions = $permissions;
- foreach ($permissions as $permission => &$value) {
+ $actionPermissions = [];
+ foreach ($permissions as $permission => $value) {
$key = str_replace("$module/", '', $permission);
$actionPermissions[$key] = $value;
}
$this->actionPermissions = $actionPermissions;
}
- protected function getPermissionsFromUrl(&$array, &$permissions) {
+ /**
+ * Recursively extract permission strings from URL menu entries.
+ *
+ * @param array<int|string, mixed> $array The menu array to inspect.
+ * @param array<string, string> $permissions Populated with url => permission mappings.
+ *
+ * @return void
+ */
+ protected function getPermissionsFromUrl(array &$array, array &$permissions): void {
foreach ($array as $k => $v) {
if (is_array($v)) {
if (isset($v['url'])) {
if (isset($v['module'])) {
- $permissions[$v['url']] = ($v['module'] ?? '') . ((isset($v['action']) && $v['action'] != 'index') ? '/' . $v['action'] : '');
+ $permissions[$v['url']] = $v['module'] . ((isset($v['action']) && $v['action'] !== 'index') ? '/' . $v['action'] : '');
} else {
$permissions[$v['url']] = \Vvveb\pregMatch('/module=([^&$]+)/', $v['url'], 1);
}
@@ -96,7 +138,15 @@ trait Permission {
}
}
- protected function setPermissionsFromUrl(&$array, &$permissions) {
+ /**
+ * Recursively assign permission values into menu entries based on their URL.
+ *
+ * @param array<int|string, mixed> $array The menu array to modify.
+ * @param array<string, string> $permissions url => permission mappings.
+ *
+ * @return void
+ */
+ protected function setPermissionsFromUrl(array &$array, array &$permissions): void {
foreach ($array as $k => &$v) {
if (is_array($v)) {
if (isset($v['url'])) {
diff --git a/system/traits/post.php b/system/traits/post.php
index 1a65de2..d93dcca 100644
--- a/system/traits/post.php
+++ b/system/traits/post.php
@@ -28,7 +28,15 @@ use Vvveb\System\Images;
use function Vvveb\url;
trait Post {
- function posts(&$posts, &$options = []) {
+ /**
+ * Process an array of posts through the single-post formatter.
+ *
+ * @param list<array<string, mixed>> $posts Array of post data arrays, passed by reference.
+ * @param array<string, mixed> $options Formatting options (image_size, excerpt_limit, etc.).
+ *
+ * @return list<array<string, mixed>> The formatted posts array<array-key, mixed>.
+ */
+ public function posts(array &$posts, array &$options = []): array {
foreach ($posts as &$post) {
$post = $this->post($post, $options);
}
@@ -36,32 +44,55 @@ trait Post {
return $posts;
}
- function post(&$post, &$options = []) {
- if (! $post) {
+ /**
+ * Format a single post with image URLs, taxonomy links, dates, and URLs.
+ *
+ * @param array<string, mixed> $post The raw post data array, passed by reference.
+ * @param array<string, mixed> $options Formatting options. Expected keys include:
+ * - type (string): post type override.
+ * - image_size (string): image size variant.
+ * - image_resize (string): resize mode ('cs' = crop/scale).
+ * - taxonomy (string): custom taxonomy route.
+ * - categories (int): max categories to include.
+ * - tags (int): max tags to include.
+ * - excerpt_limit (int): max excerpt characters.
+ * - date_format (string): 'human' or a PHP date format.
+ * - default_language_id (int): fallback language ID.
+ * - default_lang_slug (string): fallback language slug.
+ * - language (string): current language slug.
+ *
+ * @return array<string, mixed> The formatted post data.
+ */
+ public function post(array &$post, array &$options = []): array {
+ if (!$post) {
return $post;
}
$type = $post['type'] ?? $options['type'] ?? 'post';
if (isset($post['images'])) {
- $post['images'] = json_decode($post['images'], 1);
+ $post['images'] = json_decode($post['images'], true);
- foreach ($post['images'] as &$image) {
- $image = Images::image($image, 'post', $options['image_size'] ?? 'medium', $options['image_resize'] ?? 'cs');
+ if (is_array($post['images'])) {
+ foreach ($post['images'] as &$image) {
+ $image = Images::image($image, 'post', $options['image_size'] ?? 'medium', $options['image_resize'] ?? 'cs');
+ }
}
}
- foreach (['categories' => 'category', 'tags' => 'tag', 'taxonomy' => $options['taxonomy'] ?? ''] as $taxonomy => $route) {
+ $taxonomies = ['categories' => 'category', 'tags' => 'tag', 'taxonomy' => $options['taxonomy'] ?? ''];
+ foreach ($taxonomies as $taxonomy => $route) {
if (isset($post[$taxonomy])) {
- $post[$taxonomy] = json_decode($post[$taxonomy], 1);
- $count = $options[$taxonomy];
+ $decoded = json_decode($post[$taxonomy], true);
+ $post[$taxonomy] = $decoded;
+ $count = $options[$taxonomy] ?? 0;
- if (! $post[$taxonomy]) {
+ if (!$post[$taxonomy]) {
continue;
}
if (is_numeric($count) && is_array($post[$taxonomy])) {
- $post[$taxonomy] = array_slice($post[$taxonomy], 0, $count);
+ $post[$taxonomy] = array_slice($post[$taxonomy], 0, (int)$count);
}
foreach ($post[$taxonomy] as &$cat) {
@@ -78,15 +109,15 @@ trait Post {
$post['avatar_url'] = Images::image($post['avatar'], 'admin');
}
- if (empty($post['excerpt']) && ! empty($post['content'])) {
- $post['excerpt'] = substr(strip_tags($post['content']), 0, $options['excerpt_limit'] ?? 250);
+ if (empty($post['excerpt']) && !empty($post['content'])) {
+ $post['excerpt'] = substr(strip_tags($post['content']), 0, (int)($options['excerpt_limit'] ?? 250));
}
//comments translations
if (isset($post['comment_count'])) {
- $post['comment_text'] = sprintf(__('%d comment', '%d comments', (int)$post['comment_count']), $post['comment_count']);
+ $post['comment_text'] = sprintf(__('%d comment', '%d comments', (int)$post['comment_count']), $post['comment_count']);
} else {
- $post['comment_text'] = '';
+ $post['comment_text'] = '';
$post['comment_count'] = 0;
}
@@ -105,45 +136,45 @@ trait Post {
if (($post['language_id'] != $options['default_language_id'])) {
$language = ['language' => $options['language']];
- if ($post['name'] === null && isset($post['post_content'][$this->options['default_language_id']])) {
- $langFallback = $post['product_content'][$this->options['default_language_id']];
- $post['name'] = $langFallback['name'];
- $post['slug'] = $langFallback['slug'];
- $post['content'] = $langFallback['content'];
- $post['language_id'] = $langFallback['language_id'];
+ if ($post['name'] === null && isset($post['post_content'][$options['default_language_id']])) {
+ $langFallback = $post['post_content'][$options['default_language_id']];
+ $post['name'] = $langFallback['name'];
+ $post['slug'] = $langFallback['slug'];
+ $post['content'] = $langFallback['content'];
+ $post['language_id'] = $langFallback['language_id'];
} else {
- if (! $post['name']) {
- $post['name'] = '[' . __('No translation') . ']';
+ if (!$post['name']) {
+ $post['name'] = '[' . __('No translation') . ']';
}
}
} else {
- if (self :: $global['default_lang_slug']) {
+ if ($options['default_lang_slug'] ?? '') {
$language = ['language' => $options['language']];
}
}
//rfc
- $createdTime = strtotime($post['created_at'] ?? '');
- $updatedTime = strtotime($post['updated_at'] ?? '');
+ $createdTime = strtotime((string)($post['created_at'] ?? '')) ?: time();
+ $updatedTime = strtotime((string)($post['updated_at'] ?? '')) ?: $createdTime;
$post['pubDate'] = date('r', $createdTime);
$post['modDate'] = date('r', $updatedTime);
$post['lastMod'] = date('Y-m-d\TH:i:sP', $updatedTime);
- if (! isset($options['date_format']) || $options['date_format'] == 'human') {
+ if (!isset($options['date_format']) || ($options['date_format'] ?? 'human') === 'human') {
$post['created_at_formatted'] = friendlyDate($createdTime);
} else {
- $post['created_at_formatted'] = date($options['date_format'], $createdTime);
+ $post['created_at_formatted'] = date((string)$options['date_format'], $createdTime);
}
//url
- $url = $language;
+ $url = $language;
- if ($type != 'post' && $type != 'page') {
+ if ($type !== 'post' && $type !== 'page') {
$url['type'] = $post['type'];
$type = 'post';
}
-
+
//if translation is missing slug is not available
if (isset($post['slug']) && $post['slug']) {
$url['slug'] = $post['slug'];
@@ -153,7 +184,7 @@ trait Post {
$post['url'] = url("content/$type/index", $url);
$post['full-url'] = url("content/$type/index", $url + ['host' => SITE_URL, 'scheme' => $_SERVER['REQUEST_SCHEME'] ?? 'http']);
- $post['author-url'] = url('content/user/index', ['username' => $post['username']]);
+ $post['author-url'] = url('content/user/index', ['username' => $post['username'] ?? '']);
$post['comments-url'] = $post['url'] . '#comments';
diff --git a/system/traits/product.php b/system/traits/product.php
index 69e77fd..b983bb4 100644
--- a/system/traits/product.php
+++ b/system/traits/product.php
@@ -30,14 +30,43 @@ use Vvveb\System\Locale;
use function Vvveb\url;
trait Product {
- function products(&$products, $options = []) {
- if (! $products) {
+ /**
+ * Currency code for the current session (e.g. 'USD', 'EUR').
+ *
+ * @var string
+ */
+ protected string $currentCurrency = '';
+
+ /**
+ * Tax calculator instance.
+ *
+ * @var \Vvveb\System\Cart\Tax
+ */
+ protected ?Tax $tax = null;
+
+ /**
+ * Currency formatter instance.
+ *
+ * @var \Vvveb\System\Cart\Currency
+ */
+ protected ?Currency $currency = null;
+
+ /**
+ * Process an array of products through the single-product formatter.
+ *
+ * @param list<array<string, mixed>>|null $products Array of product data arrays, passed by reference.
+ * @param array<string, mixed> $options Formatting options (image_size, default_language_id, etc.).
+ *
+ * @return list<array<string, mixed>>|null The formatted products array<array-key, mixed>.
+ */
+ public function products(?array &$products, array $options = []): ?array {
+ if (!$products) {
return $products;
}
- if (! isset($this->currentCurrency)) {
- $this->currentCurrency = Locale :: getCurrency();
- $this->tax = Tax::getInstance($options);
+ if (!isset($this->currentCurrency) || $this->currentCurrency === '') {
+ $this->currentCurrency = Locale::getCurrency();
+ $this->tax = Tax::getInstance();
$this->currency = Currency::getInstance($options);
}
@@ -48,32 +77,45 @@ trait Product {
return $products;
}
- function product(&$product, $options = []) {
- $language = [];
-
- if (! isset($this->currentCurrency)) {
- $this->currentCurrency = Locale :: getCurrency();
- $this->tax = Tax::getInstance($options);
+ /**
+ * Format a single product with image URLs, prices, taxes, and URLs.
+ *
+ * @param array<string, mixed> $product The raw product data array, passed by reference.
+ * @param array<string, mixed> $options Formatting options. Expected keys include:
+ * - default_language_id (int): fallback language ID.
+ * - default_lang_slug (string): fallback language slug.
+ * - language (string): current language slug.
+ * - image_size (string): image size variant.
+ * - image_resize (string): resize mode ('cs' = crop/scale).
+ * - tax_type_id (int): tax type identifier.
+ *
+ * @return array<string, mixed> The formatted product data.
+ */
+ public function product(array &$product, array $options = []): array {
+ $language = [];
+
+ if (!isset($this->currentCurrency) || $this->currentCurrency === '') {
+ $this->currentCurrency = Locale::getCurrency();
+ $this->tax = Tax::getInstance();
$this->currency = Currency::getInstance($options);
}
-
if (($product['language_id'] != $options['default_language_id'])) {
$language = ['language' => $options['language']];
- if ($product['name'] === null && isset($product['post_content'][$this->options['default_language_id']])) {
- $langFallback = $product['product_content'][$this->options['default_language_id']];
- $product['name'] = $langFallback['name'];
- $product['slug'] = $langFallback['slug'];
- $product['content'] = $langFallback['content'];
+ if ($product['name'] === null && isset($product['product_content'][$options['default_language_id']])) {
+ $langFallback = $product['product_content'][$options['default_language_id']];
+ $product['name'] = $langFallback['name'];
+ $product['slug'] = $langFallback['slug'];
+ $product['content'] = $langFallback['content'];
$product['language_id'] = $langFallback['language_id'];
} else {
- if (! $product['name']) {
- $product['name'] = '[' . __('No translation') . ']';
+ if (!$product['name']) {
+ $product['name'] = '[' . __('No translation') . ']';
}
}
} else {
- if (self :: $global['default_lang_slug']) {
+ if ($options['default_lang_slug'] ?? '') {
$language = ['language' => $options['language']];
}
}
@@ -88,17 +130,18 @@ trait Product {
if (isset($product['image']) && $product['image']) {
$product['image'] = Images::image($product['image'], 'product', $options['image_size'] ?? 'medium', $options['image_resize'] ?? 'cs');
- //$product['images'][] = ['image' => Images::image($product['image'], 'product')];
}
//rfc
- $product['pubDate'] = date('r', strtotime($product['created_at']));
- $product['modDate'] = date('r', strtotime($product['updated_at']));
- $product['lastMod'] = date('Y-m-d\TH:i:sP', strtotime($product['updated_at']));
+ $createdTime = strtotime((string)($product['created_at'] ?? '')) ?: time();
+ $updatedTime = strtotime((string)($product['updated_at'] ?? '')) ?: $createdTime;
+ $product['pubDate'] = date('r', $createdTime);
+ $product['modDate'] = date('r', $updatedTime);
+ $product['lastMod'] = date('Y-m-d\TH:i:sP', $updatedTime);
- $url = $language;
+ $url = $language;
- if ($product['type'] != 'product') {
+ if (($product['type'] ?? 'product') !== 'product') {
$url['type'] = $product['type'];
}
@@ -109,7 +152,7 @@ trait Product {
$url['product_id'] = $product['product_id'];
}
- $product['url'] = url('product/product/index', $url);
+ $product['url'] = url('product/product/index', $url);
$product['add_cart_url'] = url('cart/cart/add', ['product_id' => $product['product_id']]);
$product['buy_url'] = url('checkout/checkout/index', ['product_id' => $product['product_id']]);
$product['add_wishlist_url'] = url('user/wishlist/add', ['product_id' => $product['product_id']]);
@@ -120,12 +163,12 @@ trait Product {
$amount = 0;
if (isset($product[$price]) && $product[$price]) {
- $amount = $product[$price];
+ $amount = (float)$product[$price];
}
- $product["{$price}_tax"] = $amount ? $this->tax->addTaxes($amount, $product['tax_type_id']) : 0;
- $product["{$price}_formatted"] = $this->currency->format($amount);
- $product["{$price}_tax_formatted"] = $this->currency->format($product["{$price}_tax"]);
- $product["{$price}_currency"] = $this->currentCurrency;
+ $product["{$price}_tax"] = $amount ? $this->tax->addTaxes($amount, $product['tax_type_id'] ?? 0) : 0;
+ $product["{$price}_formatted"] = $this->currency->format($amount);
+ $product["{$price}_tax_formatted"] = $this->currency->format($product["{$price}_tax"]);
+ $product["{$price}_currency"] = $this->currentCurrency;
}
$product['has_variants'] = false;
diff --git a/system/traits/spam.php b/system/traits/spam.php
index 1568552..7d6c206 100644
--- a/system/traits/spam.php
+++ b/system/traits/spam.php
@@ -23,33 +23,56 @@
namespace Vvveb\System\Traits;
trait Spam {
- //these must be empty, they are hidden in html and only bots will fill them
- //todo: add dynamic field name
-
- protected $spamFields = [
+ /**
+ * Hidden field names used as spam traps.
+ *
+ * These must be empty in legitimate submissions; bots typically fill them.
+ *
+ * @var list<string>
+ */
+ protected array $spamFields = [
'firstname-empty',
'lastname-empty',
'subject-empty',
'contact-form',
];
- function checkIfSpam(&$message) {
+ /**
+ * Check if a message is spam (stub — override in subclass for real logic).
+ *
+ * @param array<string, mixed> $message The submitted message data.
+ *
+ * @return array<string, mixed> The message data, potentially filtered.
+ */
+ public function checkIfSpam(array &$message): array {
return $message;
}
- function isSpam(&$message) {
- $spam = false;
-
+ /**
+ * Determine whether a submitted message contains spam honeypot data.
+ *
+ * @param array<string, mixed> $message The submitted message data.
+ *
+ * @return bool True if spam is detected, false otherwise.
+ */
+ public function isSpam(array &$message): bool {
foreach ($this->spamFields as $field) {
- if (isset($message[$field]) && ! empty($message[$field])) {
- return $spam = true;
+ if (!empty($message[$field])) {
+ return true;
}
}
- return $spam;
+ return false;
}
- function removeSpamCatchFields(&$message) {
+ /**
+ * Remove honeypot fields from a message array.
+ *
+ * @param array<string, mixed> $message The submitted message data.
+ *
+ * @return array<string, mixed> The message data with spam trap fields removed.
+ */
+ public function removeSpamCatchFields(array &$message): array {
foreach ($this->spamFields as $field) {
if (isset($message[$field])) {
unset($message[$field]);
diff --git a/system/update.php b/system/update.php
index d174334..b35cf67 100755
--- a/system/update.php
+++ b/system/update.php
@@ -32,13 +32,24 @@ define('CHMOD_DIR', (0755 & ~umask()));
define('CHMOD_FILE', (0644 & ~umask()));
class Update {
- protected $url = 'https://www.vvveb.com/update.json';
-
- protected $workDir = DIR_STORAGE . 'upgrade';
-
- protected $zipFile = false;
-
- function checkUpdates($type = 'core', $force = false) {
+ /** @var string URL to check for updates. */
+ protected string $url = 'https://www.vvveb.com/update.json';
+
+ /** @var string Working directory for upgrade extraction. */
+ protected string $workDir = DIR_STORAGE . 'upgrade';
+
+ /** @var string|false Path to the downloaded zip file. */
+ protected string|false $zipFile = false;
+
+ /**
+ * Check for available updates.
+ *
+ * @param string $type Update type ('core').
+ * @param bool $force Force re-fetch, skipping cache.
+ *
+ * @return array<string, mixed> Update information with 'hasUpdate' and optional 'error' keys.
+ */
+ public function checkUpdates(string $type = 'core', bool $force = false): array {
if ($force) {
//delete update cache
$cacheKey = md5($this->url);
@@ -48,6 +59,7 @@ class Update {
$error = '';
$result = false;
+
//cache results for one week
try {
$result = getUrl($this->url, true);
@@ -76,7 +88,14 @@ class Update {
return $info;
}
- private function checkFolderPermissions($dir) {
+ /**
+ * Recursively check folder permissions and attempt to fix them.
+ *
+ * @param string $dir Directory to check.
+ *
+ * @return string|true True if all permissions are fine, or the first unwritable path.
+ */
+ private function checkFolderPermissions(string $dir): string|true {
$skip = ['install', 'locale', 'vendor', 'plugins', 'config'];
$unwritable = [];
@@ -86,10 +105,10 @@ class Update {
$full = $dir . DS . $file;
if (($file != '.') &&
- ($file != '..') && ! in_array($file, $skip)) {
+ ($file != '..') && !in_array($file, $skip)) {
if (is_dir($full)) {
- if (! is_writable($full)) {
- if (! @chmod($full, CHMOD_DIR)) {
+ if (!is_writable($full)) {
+ if (!@chmod($full, CHMOD_DIR)) {
return $full;
}
}
@@ -100,9 +119,8 @@ class Update {
return $result;
}
}
- //if (str_ends_with($full, '.php') && ! is_writable($full)) {
- if ((substr_compare($full,'.php', -4) === 0) && ! is_writable($full)) {
- if (! @chmod($full, CHMOD_FILE)) {
+ if ((substr_compare($full, '.php', -4) === 0) && !is_writable($full)) {
+ if (!@chmod($full, CHMOD_FILE)) {
return $full;
}
}
@@ -112,32 +130,46 @@ class Update {
return true;
}
- function checkPermissions() {
- $check = $this->checkFolderPermissions(DIR_ROOT);
-
- return $check;
+ /**
+ * Check if all files are writable, fixing permissions where possible.
+ *
+ * @return string|true True if OK, or the first unwritable path.
+ */
+ public function checkPermissions(): string|true {
+ return $this->checkFolderPermissions(DIR_ROOT);
}
- static function backup() {
+ /**
+ * Create a backup of the current installation.
+ *
+ * @return void
+ */
+ public static function backup(): void {
$skipFolders = ['plugins', 'public', 'storage', 'install'];
$backupFolder = DIR_BACKUP . 'update-' . V_VERSION . '-' . date('Y-m-d_H:i:s');
rcopy(DIR_ROOT, $backupFolder, $skipFolders);
}
- static function download($url) {
- $f = false;
+ /**
+ * Download a file from a URL to a temporary location.
+ *
+ * @param string $url URL to download.
+ *
+ * @return string|false Path to the downloaded file, or false on failure.
+ */
+ public static function download(string $url): string|false {
$temp = @tempnam(sys_get_temp_dir(), 'vvveb_update');
if (!$temp) {
$temp = @tmpfile();
}
-
+
//if temp still fails use cache dir, some shared hosting have this issue
if (!$temp) {
- $temp = DIR_CACHE . APP . '.update.' . md5($url) . 'zip';
+ $temp = DIR_CACHE . APP . '.update.' . md5($url) . '.zip';
}
-
+
if ($content = download($url)) {
$f = file_put_contents($temp, $content, LOCK_EX);
if ($f) {
@@ -145,10 +177,15 @@ class Update {
}
}
- return $f;
+ return false;
}
- function setPermissions() {
+ /**
+ * Set permissions on core folders and files.
+ *
+ * @return bool Always returns true.
+ */
+ public function setPermissions(): bool {
$folders = [DIR_ROOT . 'app', DIR_ROOT . 'admin', DIR_ROOT . 'system'];
$files = [DIR_ROOT . 'index.php', DIR_ROOT . 'admin' . DS . 'index.php', DIR_ROOT . 'install' . DS . 'index.php'];
@@ -163,67 +200,188 @@ class Update {
return true;
}
- private function copyFolder($src, $dest, $skipFolders = []) {
+ /**
+ * Copy files from one folder to another, skipping specified folders.
+ *
+ * @param string $src Source directory.
+ * @param string $dest Destination directory.
+ * @param string[] $skipFolders Folder names to skip.
+ *
+ * @return bool Result of rcopy.
+ */
+ private function copyFolder(string $src, string $dest, array $skipFolders = []): bool {
ignore_user_abort(true);
- if (! is_writable($dest)) {
+ if (!is_writable($dest)) {
throw new \Exception(sprintf('Folder "%s" not writable!', $dest));
}
return rcopy($src, $dest, $skipFolders);
}
- function copyAdmin() {
- //$skipFolders = ['plugins', 'public', 'storage'];
+ /**
+ * Move folders from working dir to root folder and move existing folders to backup.
+ *
+ * @return bool Result of rcopy.
+ */
+ public function moveFolders(): bool {
+ ignore_user_abort(true);
+
+ $skipFolders = ['plugins', 'public', 'storage', 'install', 'config', 'locale'];
+ $backupFolder = DIR_BACKUP . 'update-' . V_VERSION . '-' . date('Y-m-d_H-i-s');
+
+ if (!is_dir($backupFolder) && !@mkdir($backupFolder, 0755, true)) {
+ throw new \Exception(sprintf('Could not create backup folder %s', $backupFolder));
+ }
+
+ $success = true;
+ $files = scandir($this->workDir, SCANDIR_SORT_NONE);
+ foreach ($files as $file) {
+ if ($file[0] == '.') {
+ continue;
+ }
+ if (in_array($file, $skipFolders)) {
+ continue;
+ }
+
+ $source = $this->workDir . DS . $file;
+ $dest = DIR_ROOT . DS . $file;
+ $backup = $backupFolder . DS . $file;
+
+ if (file_exists($dest) || is_link($dest)) {
+ if (!@rename($dest, $backup)) {
+ if (!@rename($source, $dest)) {
+ throw new \Exception(sprintf('Could not move %s to %s', $source, $dest));
+ }
+
+ continue;
+ }
+
+ //backup succeeded: copy the new entry into place
+ if (is_dir($source) && !is_link($source)) {
+ $success = rcopy($source, $dest, []);
+ } else {
+ $success = copy($source, $dest);
+ }
+
+ if (!$success) {
+ throw new \Exception(sprintf('Could not move %s to %s', $source, $dest));
+ }
+ } else {
+ //new top-level entry introduced by this update
+ if (is_dir($source) && !is_link($source)) {
+ $success = rcopy($source, $dest, []);
+ } else {
+ $success = @rename($source, $dest) || copy($source, $dest);
+ }
+
+ if (!$success) {
+ throw new \Exception(sprintf('Could not move %s to %s', $source, $dest));
+ }
+ }
+ }
+
+ return $success;
+ }
+
+ /**
+ * Copy admin files from the update package.
+ *
+ * @return bool Result of copyFolder.
+ */
+ public function copyAdmin(): bool {
return $this->copyFolder($this->workDir . DS . 'admin', DIR_ROOT . DS . 'admin');
}
- function copyApp() {
- //$skipFolders = ['plugins', 'public', 'storage'];
+ /**
+ * Copy app files from the update package.
+ *
+ * @return bool Result of copyFolder.
+ */
+ public function copyApp(): bool {
return $this->copyFolder($this->workDir . DS . 'app', DIR_ROOT . DS . 'app');
}
- function copySystem() {
+ /**
+ * Copy system files from the update package.
+ *
+ * @return bool Result of copyFolder.
+ */
+ public function copySystem(): bool {
return $this->copyFolder($this->workDir . DS . 'system', DIR_ROOT . DS . 'system');
}
- function copyInstall() {
- //$skipFolders = ['plugins', 'public', 'storage'];
+ /**
+ * Copy install files from the update package.
+ *
+ * @return bool Result of copyFolder.
+ */
+ public function copyInstall(): bool {
return $this->copyFolder($this->workDir . DS . 'install', DIR_ROOT . DS . 'install');
}
- function copyCore() {
+ /**
+ * Copy core files from the update package, skipping specific folders.
+ *
+ * @return bool Result of copyFolder.
+ */
+ public function copyCore(): bool {
$skipFolders = ['plugins', 'public', 'storage', 'system', 'app', 'admin', 'install', 'config', 'vendor', 'env.php'];
return $this->copyFolder($this->workDir, DIR_ROOT, $skipFolders);
}
- function copyConfig() {
- $skip = ['plugins.php', 'mail.php', 'sites.php', 'app.php', 'admin.php', 'rest.php', 'graphql.php', 'app-routes.php'];
+ /**
+ * Copy config files from the update package, skipping specific files.
+ *
+ * @return bool Result of copyFolder.
+ */
+ public function copyConfig(): bool {
+ $skip = ['plugins.php', 'mail.php', 'sites.php', 'app.php', 'admin.php', 'rest.php', 'graphql.php'];
return $this->copyFolder($this->workDir . DS . 'config', DIR_ROOT . DS . 'config', $skip);
}
- function copyPublic() {
+ /**
+ * Copy public files from the update package.
+ *
+ * @return bool Result of copyFolder.
+ */
+ public function copyPublic(): bool {
$skipFolders = ['plugins', 'themes', 'admin', 'media'];
return $this->copyFolder($this->workDir . DS . 'public', DIR_PUBLIC, $skipFolders);
}
- function copyPublicAdmin() {
+ /**
+ * Copy public admin files from the update package.
+ *
+ * @return bool Result of copyFolder.
+ */
+ public function copyPublicAdmin(): bool {
ignore_user_abort(true);
- $skipFolders = ['plugins'];
+ $skipFolders = ['demo'];
return $this->copyFolder($this->workDir . DS . 'public' . DS . 'admin', DIR_PUBLIC . DS . 'admin', $skipFolders);
}
- function copyPublicMedia() {
+ /**
+ * Copy public media files from the update package.
+ *
+ * @return bool Result of copyFolder.
+ */
+ public function copyPublicMedia(): bool {
$skipFolders = ['plugins', 'themes', 'admin'];
return $this->copyFolder($this->workDir . DS . 'public' . DS . 'media', DIR_PUBLIC . DS . 'media', $skipFolders);
}
- function createNewTables() {
+ /**
+ * Create new database tables that exist in SQL files but not in the database.
+ *
+ * @return bool Always returns true.
+ */
+ public function createNewTables(): bool {
$db = \Vvveb\System\Db::getInstance();
$tableNames = $db->getTableNames();
@@ -258,13 +416,19 @@ class Update {
return true;
}
- function tableColumns($sql) {
+ /**
+ * Parse CREATE TABLE SQL to extract table name and column definitions.
+ *
+ * @param string $sql CREATE TABLE SQL statement.
+ *
+ * @return array{0: string, 1: array<string, string>} Table name and column definitions.
+ */
+ public function tableColumns(string $sql): array {
$cols = [];
$tableName = '';
if (preg_match('/CREATE TABLE ([^\s]+?)\s*\((.+)\).*;/ms', $sql, $matches)) {
$tableName = trim($matches[1], ' "\'`');
- //$columns = explode("\n", $matches[2]);
$columns = preg_split('/\r\n|\r|\n/', trim($matches[2]));
foreach ($columns as $key => &$column) {
@@ -283,9 +447,15 @@ class Update {
return [$tableName, $cols];
}
- function addNewColumns() {
+ /**
+ * Add, modify, or drop database columns based on SQL file changes.
+ *
+ * @return bool Always returns true.
+ */
+ public function addNewColumns(): bool {
$db = \Vvveb\System\Db::getInstance();
$tableNames = $db->getTableNames();
+ $q = $db->quote;
$driver = DB_ENGINE;
$sqlPath = DIR_ROOT . "install/sql/$driver/";
@@ -306,21 +476,21 @@ class Update {
$tableName = $currentTable[0];
$columns = $currentTable[1];
- if (! $columns) {
+ if (!$columns) {
continue;
}
$newSql = file_get_contents($newFilename);
$newColumns = $this->tableColumns($newSql)[1];
- if (! $newColumns) {
+ if (!$newColumns) {
continue;
}
//newly added columns
$tableColumns = $db->getColumnsMeta($tableName);
//if table does not exist yet skip, it will be created
- if (! $tableColumns) {
+ if (!$tableColumns) {
continue;
}
@@ -336,16 +506,15 @@ class Update {
$changedColumns[$name] = $newColumns[$name];
}
} else {
- $deletedColumns[$name] = $column[$name];
+ $deletedColumns[$name] = $column;
}
}
//check deleted columns agains existing table
$deletedColumns += array_diff_key($tableColumns, $newColumns);
- $tableColumns = [];
//add new columns
if ($addedColumns) {
- if (! $db) {
+ if (!$db) {
//don't connect to db unless we need to alter table
$db = Db::getInstance();
}
@@ -357,39 +526,39 @@ class Update {
}
$definition = $newColumns[$name];
- $query = "ALTER TABLE $tableName ADD $definition";
+ $query = "ALTER TABLE $q$tableName$q ADD $definition";
$result = $db->query($query);
}
}
//change columns
if ($changedColumns) {
- if (! $db) {
+ if (!$db) {
//don't connect to db unless we need to alter table
$db = Db::getInstance();
}
foreach ($changedColumns as $name => $definition) {
- if (! isset($tableColumns[$name])) {
+ if (!isset($tableColumns[$name])) {
//column does not exist skip
continue;
}
- $query = "ALTER TABLE $tableName MODIFY COLUMN $definition";
+ $query = "ALTER TABLE $q$tableName$q MODIFY COLUMN $definition";
$result = $db->query($query);
}
}
//delete columns
//disabled to avoid deleting user added columns
- if (false && $deletedColumns) {
- if (! $db) {
+ if (false/*$deletedColumns*/) {
+ if (!$db) {
//don't connect to db unless we need to alter table
$db = Db::getInstance();
}
foreach ($deletedColumns as $name => $definition) {
- if (! isset($tableColumns[$name])) {
+ if (!isset($tableColumns[$name])) {
//column does not exist skip
continue;
}
@@ -404,11 +573,21 @@ class Update {
return true;
}
- function clearCache() {
+ /**
+ * Clear all caches.
+ *
+ * @return bool Result of CacheManager::delete.
+ */
+ public function clearCache(): bool {
return CacheManager::delete();
}
- function cleanup() {
+ /**
+ * Clean up temporary update files.
+ *
+ * @return bool Always returns true.
+ */
+ public function cleanup(): bool {
rrmdir($this->workDir);
if ($this->zipFile) {
@@ -418,24 +597,47 @@ class Update {
return true;
}
- function install($zipFile) {
- $this->unzip($zipFile, $this->workDir);
+ /**
+ * Install an update from a zip file.
+ *
+ * @param string $zipFile Path to the update zip file.
+ *
+ * @return void
+ */
+ public function install(string $zipFile): void {
+ if (!$this->unzip($zipFile)) {
+ return;
+ }
- $success = true;
- //$dest = substr(DIR_ROOT,0, -1); //remove trailing slash
- rrmdir($this->workDir);
//plugins and themes are updated individually
$skipFolders = ['plugins', 'public' . DS . 'themes', 'storage', 'vendor'];
rcopy($this->workDir, DIR_ROOT, $skipFolders);
- rrmdir($this->workDir);
- unlink($zipFile);
+
+ //remove the extracted package and the downloaded archive
+ $this->cleanup();
CacheManager::delete();
}
- function unzip($zipFile) {
- if (! is_dir($this->workDir)) {
- mkdir($this->workDir);
+ /**
+ * Extract a zip file to the work directory.
+ *
+ * @param string $zipFile Path to the zip file.
+ *
+ * @return bool True on success, false on failure.
+ */
+ public function unzip(string $zipFile): bool {
+ if (!is_file($zipFile)) {
+ return false;
+ }
+
+ //start from a clean work dir so stale files/symlinks cannot be reused
+ if (is_dir($this->workDir) || is_link($this->workDir)) {
+ rrmdir($this->workDir);
+ }
+
+ if (!is_dir($this->workDir) && !@mkdir($this->workDir, 0755, true)) {
+ return false;
}
$result = false;
diff --git a/system/user/admin.php b/system/user/admin.php
index 3382d0a..f8996e2 100755
--- a/system/user/admin.php
+++ b/system/user/admin.php
@@ -29,9 +29,21 @@ use Vvveb\System\PageCache;
use Vvveb\System\Session;
class Admin extends Auth {
- private static $namespace = 'admin';
+ /**
+ * Session namespace key for admin data.
+ *
+ * @var string
+ */
+ private static string $namespace = 'admin';
- private static function setUserData(&$data) {
+ /**
+ * Prepare admin data for storage: hash password and encode site_access.
+ *
+ * @param array<string, mixed> $data Reference to the admin data array.
+ *
+ * @return array<string, mixed> The modified data array<array-key, mixed>.
+ */
+ private static function setUserData(array &$data): array {
if (isset($data['password'])) {
$data['password'] = self :: password($data['password']);
}
@@ -47,17 +59,24 @@ class Admin extends Auth {
return $data;
}
- public static function add($data) {
+ /**
+ * Add a new admin user.
+ *
+ * @param array<string, mixed> $data Admin data including username, email, etc.
+ *
+ * @return array<array-key, mixed>|false Existing admin info if already registered, new admin record on success, or false on validation failure.
+ */
+ public static function add(array $data): array|false {
$admin = new AdminSQL();
- if (! isset($data['username']) || ! $data['username']) {
+ if (!isset($data['username']) || !$data['username']) {
return false;
}
self::sanitize($data);
//check if email or username is already registered
- $check = ['email'=> $data['email']];
+ $check = ['email' => $data['email']];
if (isset($data['username'])) {
$check['username'] = $data['username'];
@@ -67,7 +86,7 @@ class Admin extends Auth {
return $adminInfo;
}
- $data['status'] = 1; //0
+ $data['status'] = 1; //0
$data['last_ip'] = $_SERVER['REMOTE_ADDR'] ?? '';
self::setUserData($data);
@@ -75,30 +94,58 @@ class Admin extends Auth {
return $admin->add([self :: $namespace => $data]);
}
- public static function hasCapability($capability, $app = APP) {
+ /**
+ * Check if the current admin has a specific capability.
+ *
+ * @param string $capability The capability name to check.
+ * @param string $app The application context.
+ *
+ * @return bool True if the admin has the capability.
+ */
+ public static function hasCapability(string $capability, string $app = APP): bool {
$admin = sess(self :: $namespace, false);
$capabilities = $admin['permissions'][$app]['capabilities'] ?? $admin['permissions']['capabilities'] ?? [];
return in_array($capability, $capabilities);
}
- public static function siteAccess() {
+ /**
+ * Get the site access list for the current admin.
+ *
+ * @return array<int|string, mixed> Array of site IDs the admin can access.
+ */
+ public static function siteAccess(): array {
$admin = sess(self :: $namespace, false);
return $site_access = $admin['site_access'] ?? [];
}
- public static function hasSiteAccess($site_id) {
+ /**
+ * Check if the current admin has access to a specific site.
+ *
+ * @param int|string $site_id The site ID to check.
+ *
+ * @return bool True if the admin has access to the site.
+ */
+ public static function hasSiteAccess(int|string $site_id): bool {
$admin = sess(self :: $namespace, false);
$site_access = $admin['site_access'] ?? [];
return in_array($site_id, $site_access);
}
- public static function hasPermission($permission, $app = APP) {
+ /**
+ * Check if the current admin has a specific permission.
+ *
+ * @param string|array<array-key, mixed> $permission The permission identifier to check.
+ * @param string $app The application context.
+ *
+ * @return array<array-key, mixed>|bool True if the admin has the permission.
+ */
+ public static function hasPermission(string|array $permission, string $app = APP): array|bool {
$admin = sess(self :: $namespace, false);
- if (! $admin) {
+ if (!$admin) {
return false;
}
@@ -109,22 +156,37 @@ class Admin extends Auth {
return Role::has($permission, $allow, $deny, $admin['role_id']);
}
- public static function update($data, $condition) {
+ /**
+ * Update an existing admin record.
+ *
+ * @param array<string, mixed> $data The data to update.
+ * @param array<string, mixed> $condition The WHERE conditions for the update.
+ *
+ * @return mixed The result of the update operation.
+ */
+ public static function update(array $data, array $condition): mixed {
$admin = new AdminSQL();
self::setUserData($data);
self::sanitize($data);
- $data['updated_at'] = $data['updated_at'] ?? date('Y-m-d H:i:s', time());
+ $data['updated_at'] ??= date('Y-m-d H:i:s', time());
return $admin->edit(array_merge([self :: $namespace => $data], $condition));
}
- public static function get($data) {
+ /**
+ * Retrieve admin info by login credentials or identifiers.
+ *
+ * @param array<string, mixed> $data Lookup criteria (email, username, token, etc.).
+ *
+ * @return array<string, mixed> Admin info array, or empty array if not found.
+ */
+ public static function get(array $data): array {
$loginInfo = []; //['status' => 1];
$adminInfo = false;
- foreach (['email', 'user', 'username', 'role_id', 'admin_id', 'token', 'admin_auth_token', 'admin_auth_token', 'status'] as $key) {
+ foreach (['email', 'user', 'username', 'role_id', 'admin_id', 'token', 'admin_auth_token', 'status'] as $key) {
if (isset($data[$key])) {
$loginInfo[$key] = $data[$key];
}
@@ -143,25 +205,35 @@ class Admin extends Auth {
}
}
- if (! $adminInfo) {
+ if (!$adminInfo) {
return [];
}
return $adminInfo;
}
- public static function auth($admin_auth_token, $additionalInfo = [], &$feedback = []) {
+ /**
+ * Authenticate an admin using an auth token.
+ *
+ * @param string $admin_auth_token The authentication token.
+ * @param array<string, mixed> $additionalInfo Additional data to store in the session.
+ * @param array<string, mixed> &$feedback Feedback message and code on failure.
+ *
+ * @return array<string, mixed>|false Admin info on success, false on failure.
+ */
+ public static function auth(string $admin_auth_token, array $additionalInfo = [], array &$feedback = []): array|false {
//check admin email and that status is active
$data['status'] = 1;
$data['admin_auth_token'] = $admin_auth_token;
$adminInfo = self::get($data);
$userExists = ($adminInfo && isset($adminInfo['password']));
+ $passwordCorrect = false;
if ($userExists) {
- $passwordCorrect = $data['admin_auth_token'] == $admin_auth_token;
+ $passwordCorrect = hash_equals($data['admin_auth_token'], $admin_auth_token);
}
- if (! $userExists || ! $passwordCorrect) {
+ if (!$userExists || !$passwordCorrect) {
if ($userExists) {
$message = __('Token incorrect!');
$code = 0;
@@ -185,7 +257,16 @@ class Admin extends Auth {
return $adminInfo;
}
- public static function login($data, $additionalInfo = [], &$feedback = []) {
+ /**
+ * Authenticate an admin using email/username and password.
+ *
+ * @param array<string, mixed> $data Login credentials (email/username, password).
+ * @param array<string, mixed> $additionalInfo Additional data to store in the session.
+ * @param array<string, mixed> &$feedback Feedback message and code on failure.
+ *
+ * @return array<string, mixed>|false Admin info on success, false on failure.
+ */
+ public static function login(array $data, array $additionalInfo = [], array &$feedback = []): array|false {
//check admin email and that status is active
$data['status'] = 1;
$adminInfo = self::get($data);
@@ -193,10 +274,10 @@ class Admin extends Auth {
$userExists = ($adminInfo && isset($adminInfo['password']));
if ($userExists) {
- $passwordCorrect = self::checkPassword($data['password'], $adminInfo['password']);
+ $passwordCorrect = self::checkPassword($data['password'] ?? '', $adminInfo['password']);
}
- if (! $userExists || ! $passwordCorrect) {
+ if (!$userExists || !$passwordCorrect) {
if ($userExists) {
$message = __('Password incorrect!');
$code = 0;
@@ -215,20 +296,30 @@ class Admin extends Auth {
unset($adminInfo['password']);
$session->set(self :: $namespace, $adminInfo + $additionalInfo);
$lastIp = $_SERVER['REMOTE_ADDR'] ?? '';
- self::update(['last_ip' => $lastIp], ['admin_id' => $adminInfo['admin_id']]);
+ self::update(['last_ip' => $lastIp], ['admin_id' => $adminInfo['admin_id']]);
PageCache::disable('user');
return $adminInfo;
}
- public static function logout() {
+ /**
+ * Log out the current admin by clearing session data and enabling page cache.
+ *
+ * @return void
+ */
+ public static function logout(): void {
PageCache::enable('user');
- return sess([self :: $namespace => false]);
+ sess([self :: $namespace => []]);
}
- public static function current() {
+ /**
+ * Get the currently logged-in admin's session data.
+ *
+ * @return array<string, mixed> Current admin session data, or empty array if not logged in.
+ */
+ public static function current(): array {
$current = sess(self :: $namespace, []);
if ($current) {
@@ -237,22 +328,23 @@ class Admin extends Auth {
PageCache::enable('admin');
}
- return $current;
+ return $current ?? [];
}
/**
- * @ Update admin session data
- * @param mixed $data
+ * Update the current admin's session data by merging new values.
+ *
+ * @param array<string, mixed>|null $data Key-value pairs to merge into the session.
*
- * @return mixed
+ * @return array<array-key, mixed>|false Merged session data on success, false if no current session or invalid data.
*/
- public static function session($data) {
+ public static function session(?array $data): array|false {
$current = self :: current();
- if ($current && $data && is_array($data)) {
+ if ($current && $data) {
$current = array_merge($current, $data);
- return sess([self :: $namespace => $current]);
+ return sess([self :: $namespace => $current], $current);
}
return false;
diff --git a/system/user/auth.php b/system/user/auth.php
index b48ee1b..43138e0 100755
--- a/system/user/auth.php
+++ b/system/user/auth.php
@@ -21,14 +21,27 @@
*/
namespace Vvveb\System\User;
-use function Vvveb\stripChars;
+
use function Vvveb\sanitizeHTML;
+use function Vvveb\stripChars;
class Auth {
- static $options = ['cost' => 11];
+ /**
+ * Password hashing options.
+ *
+ * @var array{cost: int}
+ */
+ private static array $options = ['cost' => 11];
- public static function sanitize(&$data) {
- foreach ($data as $name => &$val) {
+ /**
+ * Sanitize user data by stripping unwanted characters and validating fields.
+ *
+ * @param array<string, mixed> $data Reference to the data array to sanitize.
+ *
+ * @return void
+ */
+ public static function sanitize(array &$data): void {
+ foreach ($data as $name => &$val) {
if (is_string($val) && !in_array($name, ['created_at', 'updated_at', 'bio'])) {
$val = stripChars($val);
}
@@ -43,11 +56,25 @@ class Auth {
}
if (isset($data['email'])) {
- $data['email'] = filter_var($data['email'], FILTER_VALIDATE_EMAIL);
+ $email = filter_var($data['email'], FILTER_VALIDATE_EMAIL);
+
+ if ($email === false) {
+ unset($data['email']);
+ } else {
+ $data['email'] = $email;
+ }
}
}
- public static function checkPassword($password, $hash) {
+ /**
+ * Verify a password against a hash, rehashing if needed.
+ *
+ * @param string $password The plain-text password to verify.
+ * @param string $hash The stored password hash.
+ *
+ * @return string|bool New hash string if rehash was needed, true if valid, false otherwise.
+ */
+ public static function checkPassword(string $password, string $hash): string|bool {
if (password_verify($password, $hash)) {
// Check if a newer hashing algorithm is available
// or the cost has changed
@@ -62,7 +89,14 @@ class Auth {
return false;
}
- public static function password($password) {
+ /**
+ * Generate a password hash using the configured options.
+ *
+ * @param string $password The plain-text password to hash.
+ *
+ * @return string The resulting password hash.
+ */
+ public static function password(string $password): string {
return password_hash($password, PASSWORD_DEFAULT, self :: $options);
}
}
diff --git a/system/user/role.php b/system/user/role.php
index 5c24dec..e741a1a 100755
--- a/system/user/role.php
+++ b/system/user/role.php
@@ -28,20 +28,28 @@ use Vvveb\System\Event;
use Vvveb\System\Sqlp\Sqlp;
class Role {
- static private $data = null;
-
- /*
- * Checks for permission
- *
- * $permission string or array
+ /**
+ * Cached controller list data.
+ *
+ * @var array<string, mixed>|null
+ */
+ private static ?array $data = null;
+
+ /**
+ * Check if a permission (or array of permissions) is allowed by the allow/deny rules.
+ *
+ * @param string|array<int, string> $permission Permission string or array of permission strings.
+ * @param array<int, string> $allowRules Array of allow rules (supports wildcards).
+ * @param array<int, string> $denyRules Array of deny rules (supports wildcards).
+ * @param int $role_id The role ID (unused in logic, reserved for context).
+ *
+ * @return array<string, bool>|bool Associative array<array-key, mixed> of permission=>bool when $permission is an array, or a single bool.
*/
- public static function has($permission, $allowRules = [], $denyRules = [], $role_id = 0) {
- //$allowRules = ['*', 'content/posts/*', 'settings'];
- //$denyRules = ['*/save', '*/delete', 'product/*', 'tools/*', 'users/*', 'theme/*', 'plugin/*'];
+ public static function has(string|array $permission, array $allowRules = [], array $denyRules = [], int $role_id = 0): array|bool {
//allow
- $allowRegex = '@^' . (str_replace('*', '.+?', implode('$|^', $allowRules))) . '$@m';
+ $allowRegex = '@^' . (str_replace('*', '.+?', implode('$|^', $allowRules))) . '$@mi';
//deny
- $denyRegex = '@^' . (str_replace('*', '.+?', implode('$|^', $denyRules))) . '$@m';
+ $denyRegex = '@^' . (str_replace('*', '.+?', implode('$|^', $denyRules))) . '$@mi';
$result = [];
@@ -74,26 +82,36 @@ class Role {
if (preg_match_all($allowRegex, $list, $matches)) {
//$allowList = array_map(fn ($value) => true, array_flip($matches[0]));
- $allowList = array_map(function ($value) { return true; }, array_flip($matches[0]));
+ $allowList = array_map(fn ($value) => true, array_flip($matches[0]));
}
$denyList = [];
if (preg_match_all($denyRegex, $list, $matches)) {
//$denyList = array_map(fn ($value) => false, array_flip($matches[0]));
- $denyList = array_map(function ($value) {return false; }, array_flip($matches[0]));
+ $denyList = array_map(fn ($value) => false, array_flip($matches[0]));
}
//rules that match exactly the permission takes precedence (does not have *)
- $exactAllow = array_intersect($allowRules, $permissions);
- $exactDeny = array_intersect($denyRules, $permissions);
+ //permission identifiers are generated from controller method names (camelCase)
+ //while request-time checks may lowercase the action, so compare
+ //case-insensitively but keep the original permission string as the result key
+ $permissionKeys = [];
+
+ foreach ($permissions as $value) {
+ $permissionKeys[strtolower($value)] = $value;
+ }
+
+ $exactAllow = [];
- if ($exactAllow) {
- $exactAllow = array_map(function ($value) { return true; }, array_flip($exactAllow));
+ foreach (array_intersect(array_map('strtolower', $allowRules), array_keys($permissionKeys)) as $match) {
+ $exactAllow[$permissionKeys[$match]] = true;
}
- if ($exactDeny) {
- $exactDeny = array_map(function ($value) { return false; }, array_flip($exactDeny));
+ $exactDeny = [];
+
+ foreach (array_intersect(array_map('strtolower', $denyRules), array_keys($permissionKeys)) as $match) {
+ $exactDeny[$permissionKeys[$match]] = false;
}
$result = $exactDeny + $exactAllow + $denyList + $allowList;
@@ -105,7 +123,16 @@ class Role {
}
}
- public static function mkmap($dir, &$path = [], $app = 'admin') {
+ /**
+ * Recursively build a permission map from the controller directory tree.
+ *
+ * @param string $dir The directory path to scan.
+ * @param array<string, mixed> &$path Reference to the path tree being built.
+ * @param string $app The application context (e.g. 'admin').
+ *
+ * @return void
+ */
+ public static function mkmap(string $dir, array &$path = [], string $app = 'admin'): void {
if ($dir[0] == '.') {
return;
}
@@ -120,20 +147,22 @@ class Role {
$name = basename($dir);
$filename = str_replace('.php', '', $file);
+ if (!isset($path[$name])) {
+ $path[$name] = [];
+ }
+
if (is_dir($dir . '/' . $file)) {
self::mkmap($dir . '/' . $file, $path[$name], $app);
} else {
- if (! in_array($filename, ['base', 'crud', 'listing', 'error404', 'error403', 'error500'])) {
- //$path[$name][$filename] = self::getActions2($dir . '/' . $file);
+ if (!in_array($filename, ['base', 'crud', 'listing', 'error404', 'error403', 'error500'])) {
$class = str_replace(DIR_ROOT . $app . DS . 'controller' . DS, '', $dir . DS . $filename);
$class = str_replace('/', '\\', $class);
- //echo $class;
if ($app == APP) {
$actions = self::getActions($class, $filename, $dir . DS . $file);
} else {
$actions = self::getActions2($dir . DS . $file);
}
-
+
if ($actions) {
$path[$name][$filename] = $actions;
}
@@ -143,22 +172,36 @@ class Role {
closedir($dh);
}
}
-
- return [];
}
- public static function controllers($app = 'admin') {
+ /**
+ * Get the controller permission map for an application.
+ *
+ * @param string $app The application context (e.g. 'admin').
+ *
+ * @return array<string, array<string, string>> Associative array<array-key, mixed> of controller => actions.
+ */
+ public static function controllers(string $app = 'admin'): array {
$tree = [];
self::mkmap(DIR_ROOT . $app . DS . 'controller', $tree, $app);
return $tree['controller'] ?? [];
}
- public static function getActions($file, $filename, $path) {
+ /**
+ * Extract permission actions from a controller class using reflection.
+ *
+ * @param string $file The fully-qualified controller class name.
+ * @param string $filename The base filename without extension.
+ * @param string $path The full file path to the controller.
+ *
+ * @return array<string, string> Associative array of method => permission path, or empty array.
+ */
+ public static function getActions(string $file, string $filename, string $path): array {
//echo $file;
$permission = str_replace('\\', '/', $file);
- $class = '\\Vvveb\\Controller\\' . $file;
+ $class = '\Vvveb\Controller\\' . $file;
//if plugin add namespace
if (strpos($file, 'plugins/')) {
$pluginName = pregMatch('@/plugins/(.+?)/@', $file, 1);
@@ -193,7 +236,14 @@ class Role {
return [];
}
- public static function getActions2($file) {
+ /**
+ * Extract permission actions from a controller file using regex parsing.
+ *
+ * @param string $file The full file path to the controller.
+ *
+ * @return array<string, string> Associative array<array-key, mixed> of method => permission path.
+ */
+ public static function getActions2(string $file): array {
$permission = substr($file, strpos($file, '/controller/') + 12);
//remove extension
$permission = substr($permission, 0, strrpos($permission, '.'));
@@ -231,7 +281,14 @@ class Role {
return $data;
}
- public static function getControllerList($app = 'admin') {
+ /**
+ * Get the full controller list with all permissions for an application.
+ *
+ * @param string $app The application context (e.g. 'admin').
+ *
+ * @return array{permissions: array<int, string>} Array with a 'permissions' key containing all permission strings.
+ */
+ public static function getControllerList(string $app = 'admin'): array {
if (self :: $data) {
return self :: $data;
}
@@ -242,13 +299,13 @@ class Role {
while (count($path) > 0) {
$next = array_shift($path);
- foreach (glob("$next/*") as $file) {
+ foreach (glob("$next/*") ?: [] as $file) {
if (is_dir($file)) {
$path[] = $file;
}
if (is_file($file)) {
- if (! in_array(basename($file, '.php'), ['base', 'crud', 'listing', 'error404', 'error403', 'error500'])) {
+ if (!in_array(basename($file, '.php'), ['base', 'crud', 'listing', 'error404', 'error403', 'error500'])) {
$files[] = $file;
}
}
@@ -299,15 +356,30 @@ class Role {
return $data;
}
- public static function getCapabilitiesList($app = 'admin') {
+ /**
+ * Get the list of available capabilities for an application.
+ *
+ * @param string $app The application context (e.g. 'admin').
+ *
+ * @return array<string, mixed> Capabilities configuration array<array-key, mixed>.
+ */
+ public static function getCapabilitiesList(string $app = 'admin'): array {
$capabilities = include DIR_SYSTEM . 'data' . DS . 'capabilities.php';
- list($capabilities) = Event :: trigger(__CLASS__,__FUNCTION__, $capabilities);
+ [$capabilities] = Event :: trigger(__CLASS__, __FUNCTION__, $capabilities);
return $capabilities;
}
- public static function routes($app = 'app') {
+ /**
+ * Build a route schema tree from the application route configuration.
+ *
+ * @param string $app The application context (e.g. 'app').
+ *
+ * @return array<string, mixed> Nested array<array-key, mixed> representing the route schema tree.
+ */
+ public static function routes(string $app = 'app'): array {
$routes = \Vvveb\config("$app-routes");
+ /** @var array<string, mixed> $routeSchemas string-keyed trie accumulated below */
$routeSchemas = [];
foreach ($routes as $route => $options) {
@@ -316,7 +388,7 @@ class Role {
//$path = $options['module'];//str_replace('/rest/', '/', $route);
$path = str_replace('/rest/', '', $route);
- if (! $path) {
+ if (!$path) {
$path = 'index';
}
@@ -327,15 +399,13 @@ class Role {
if (strpos($path, '/')) {
$slash = explode('/', $path);
- if ($slash) {
- $current = &$routeSchemas;
+ $current = &$routeSchemas;
- foreach ($slash as $name) {
- if (! isset($current[$name])) {
- $current[$name] = [];
- }
- $current = &$current[$name];
+ foreach ($slash as $name) {
+ if (!isset($current[$name])) {
+ $current[$name] = [];
}
+ $current = &$current[$name];
}
} else {
$current = &$routeSchemas[$path];
@@ -353,13 +423,19 @@ class Role {
return $routeSchemas;
}
- public static function models($app = 'admin') {
+ /**
+ * Get the list of database models and their methods from SQL files.
+ *
+ * @param string $app The application context (e.g. 'admin').
+ *
+ * @return array<string, array<string, string>> Associative array<array-key, mixed> of model => method => permission path.
+ */
+ public static function models(string $app = 'admin'): array {
$dirSQL = DIR_ROOT . 'admin' . DS . 'sql' . DS . DB_ENGINE . DS;
$sqlp = new Sqlp();
$models = [];
$files = glob("$dirSQL*.sql");
- //var_dump($files);
foreach ($files as $file) {
$sqlp->parseSqlPfile($file);
diff --git a/system/user/user.php b/system/user/user.php
index 0e8696c..5f2f49a 100755
--- a/system/user/user.php
+++ b/system/user/user.php
@@ -41,19 +41,19 @@ class User extends Auth {
*
* @param array<string, mixed> $data User data including username, email, password, etc.
*
- * @return array|false Existing user info if already registered, new user record on success, or false on validation failure.
+ * @return array<array-key, mixed>|false Existing user info if already registered, new user record on success, or false on validation failure.
*/
- public static function add(array $data) : array|false {
+ public static function add(array $data): array|false {
$user = new UserSQL();
- if (! isset($data['username']) || ! $data['username']) {
+ if (!isset($data['username']) || !$data['username']) {
return false;
}
self::sanitize($data);
//check if email or username is already registered
- $check = ['username'=> $data['username']];
+ $check = ['username' => $data['username']];
if (isset($data['email'])) {
$check['email'] = $data['email'];
@@ -69,7 +69,7 @@ class User extends Auth {
$data['password'] = self :: password($data['password']);
}
- $data['status'] = 1; //0
+ $data['status'] = 1; //0
$data['last_ip'] = $_SERVER['REMOTE_ADDR'] ?? '';
return $user->add([self :: $namespace => $data]);
@@ -83,7 +83,7 @@ class User extends Auth {
*
* @return mixed The result of the update operation.
*/
- public static function update(array $data, array $condition) : mixed {
+ public static function update(array $data, array $condition): mixed {
$user = new UserSQL();
if (empty($data['password'])) {
@@ -94,7 +94,7 @@ class User extends Auth {
//$data['status'] = 0;
self::sanitize($data);
- $data['updated_at'] = $data['updated_at'] ?? date('Y-m-d H:i:s', time());
+ $data['updated_at'] ??= date('Y-m-d H:i:s', time());
return $user->edit(array_merge([self :: $namespace => $data], $condition));
}
@@ -106,11 +106,10 @@ class User extends Auth {
*
* @return array<string, mixed> User info array, or empty array if not found.
*/
- public static function get(array $data) : array {
+ public static function get(array $data): array {
$user = new UserSQL();
//check user email and that status is active
$loginInfo = []; //['status' => 1];
- $userInfo = false;
if (isset($data['email'])) {
$loginInfo['email'] = $data['email'];
@@ -138,7 +137,7 @@ class User extends Auth {
$userInfo = $user->get($loginInfo);
- if (! $userInfo) {
+ if (!$userInfo) {
return [];
}
@@ -148,23 +147,23 @@ class User extends Auth {
/**
* Authenticate a user using email/username and password.
*
- * @param array<string, mixed> $data Login credentials (email, username, password).
- * @param array<string, mixed> $additionalInfo Additional data to store in the session.
- * @param array<string, mixed> &$feedback Feedback message and code on failure.
+ * @param array<string, mixed> $data Login credentials (email, username, password).
+ * @param array<string, mixed> $additionalInfo Additional data to store in the session.
+ * @param array<string, mixed> &$feedback Feedback message and code on failure.
*
* @return array<string, mixed>|false User info on success, false on failure.
*/
- public static function login(array $data, array $additionalInfo = [], array &$feedback = []) : array|false {
+ public static function login(array $data, array $additionalInfo = [], array &$feedback = []): array|false {
$data['status'] = 1;
$userInfo = self::get($data);
$passwordCorrect = false;
$userExists = ($userInfo && isset($userInfo['password']));
if ($userExists) {
- $passwordCorrect = self::checkPassword($data['password'], $userInfo['password']);
+ $passwordCorrect = self::checkPassword($data['password'] ?? '', $userInfo['password']);
}
- if (! $userExists || ! $passwordCorrect) {
+ if (!$userExists || !$passwordCorrect) {
if ($userExists) {
$message = __('Password incorrect!');
$code = 0;
@@ -184,7 +183,7 @@ class User extends Auth {
$session->set(self :: $namespace, $userInfo + $additionalInfo);
$lastIp = $_SERVER['REMOTE_ADDR'] ?? '';
- self::update(['last_ip' => $lastIp], ['user_id' => $userInfo['user_id']]);
+ self::update(['last_ip' => $lastIp], ['user_id' => $userInfo['user_id']]);
PageCache::disable('user');
@@ -196,7 +195,7 @@ class User extends Auth {
*
* @return void
*/
- public static function logout() : void {
+ public static function logout(): void {
PageCache::enable(self :: $namespace);
sess([self :: $namespace => false]);
@@ -210,7 +209,7 @@ class User extends Auth {
*
* @return string The HMAC-MD5 hash.
*/
- public static function hash(string $data, string $salt) : string {
+ public static function hash(string $data, string $salt): string {
return hash_hmac('md5', $data, $salt);
}
@@ -221,8 +220,12 @@ class User extends Auth {
*
* @return bool True if the cookie hash is valid.
*/
- public static function generateCookie(string $cookieValue) : bool {
- list($value, $hash) = explode(':', $cookieValue, 2);
+ public static function generateCookie(string $cookieValue): bool {
+ if (!defined('SECRET_KEY')) {
+ return false;
+ }
+
+ [$value, $hash] = explode(':', $cookieValue, 2);
if (hash_equals(md5($value . '-' . SECRET_KEY), $hash)) {
return true;
@@ -240,17 +243,26 @@ class User extends Auth {
*
* @return bool True if the cookie HMAC is valid.
*/
- public static function checkCookie(string $cookieValue, string $hmac, string $scheme) : bool {
- list($username, $hash, $expiration, $token) = explode('|', $cookieValue, 4);
+ /**
+ * Validate a signed login cookie.
+ *
+ * Expected format: username|expiration|token|hmac
+ * The HMAC is computed with sha256 over username|expiration|token keyed by
+ * a hash of the username, scheme and application secret.
+ */
+ public static function checkCookie(string $cookieValue, string $hmac, string $scheme): bool {
+ $parts = explode('|', $cookieValue);
- $key = hash($username . '|' . $hash . '|' . $expiration . '|' . $token, $scheme);
+ if (count($parts) < 3) {
+ return false;
+ }
- $algo = function_exists('hash') ? 'sha256' : 'sha1';
- $hash = hash_hmac($algo, $username . '|' . $expiration . '|' . $token, $key);
+ [$username, $expiration, $token] = $parts;
- $valid = hash_equals($hash, $hmac);
+ $key = hash_hmac('md5', $username . '|' . $expiration . '|' . $token, $scheme);
+ $h = hash_hmac('sha256', $username . '|' . $expiration . '|' . $token, $key);
- return $valid;
+ return hash_equals($h, $hmac);
}
/**
@@ -258,7 +270,7 @@ class User extends Auth {
*
* @return array<string, mixed> Current user session data, or empty array if guest.
*/
- public static function current() : array {
+ public static function current(): array {
$current = sess(self :: $namespace, []);
if ($current) {
@@ -275,15 +287,15 @@ class User extends Auth {
*
* @param array<string, mixed>|null $data Key-value pairs to merge into the session.
*
- * @return array|false Merged session data on success, false if no current session or invalid data.
+ * @return array<array-key, mixed>|false Merged session data on success, false if no current session or invalid data.
*/
- public static function session(?array $data) : array|false {
+ public static function session(?array $data): array|false {
$current = self :: current();
- if ($current && $data && is_array($data)) {
+ if ($current && $data) {
$current = array_merge($current, $data);
- return sess([self :: $namespace => $current]);
+ return sess([self :: $namespace => $current], $current);
}
return false;
diff --git a/system/validator.php b/system/validator.php
index 1dca004..19a8e05 100755
--- a/system/validator.php
+++ b/system/validator.php
@@ -26,63 +26,82 @@ use function Vvveb\__;
use function Vvveb\arrayPath;
class Validator {
- private $rules;
-
- private $defaultMessages = [];
-
- /*
- [
- 'notEmpty' => '%s is empty',
- 'allowed_values' => '%s is invalid, valid options are %s',
- 'maxLength' => '%s is longer than %d'
- ];
- */
- function __construct($rules) {
+ /** @var array<string, array<string, mixed>> Validation rules keyed by input name. */
+ private array $rules = [];
+
+ /** @var array<string, string> Default error messages for each rule type. */
+ private array $defaultMessages = [];
+
+ /**
+ * Initialize the validator with rule file paths.
+ *
+ * @param list<string> $ruleFiles List of rule file identifiers to load.
+ */
+ public function __construct(array $ruleFiles) {
$this->defaultMessages = [
- 'notEmpty' => __('%s is empty'),
- 'allowedValues' => __('%s is invalid, valid options are %s'),
- 'maxLength' => __('%s is longer than %d'),
- 'minLength' => __('%s is shorter than %d'),
- 'match' => __('%s does not match %s'),
- 'captcha' => __('%s is invalid'),
- 'session' => __('%s is invalid'),
- 'email' => __('%s invalid email'),
- 'integer' => __('%s not numeric'),
- 'passwordComplexity' => __('%s not complex enough, include uppercase letters and digits'),
+ 'notEmpty' => __('%s is empty'),
+ 'allowedValues' => __('%s is invalid, valid options are %s'),
+ 'maxLength' => __('%s is longer than %d'),
+ 'minLength' => __('%s is shorter than %d'),
+ 'match' => __('%s does not match %s'),
+ 'digit' => __('%s is invalid'),
+ 'captcha' => __('%s is invalid'),
+ 'session' => __('%s is invalid'),
+ 'email' => __('%s invalid email'),
+ 'integer' => __('%s not numeric'),
+ 'passwordComplexity' => __('%s not complex enough, include uppercase letters and digits'),
];
- $this->rules($rules);
+ $this->rules($ruleFiles);
}
- function rules($ruleFiles) {
+ /**
+ * Load validation rules from PHP files.
+ *
+ * @param list<string> $ruleFiles Rule file identifiers.
+ *
+ * @return void
+ */
+ public function rules(array $ruleFiles): void {
$rules = [];
foreach ($ruleFiles as $rule) {
- if (strpos($rule,'plugins.') !== false) {
- //$plugin = 'plugins.()'
+ if (str_contains($rule, 'plugins.')) {
$options = \Vvveb\pregMatch('/plugins\.(?<plugin>[^\.]+)\.(?<rule>[^\.]+)/', $rule);
$file = DIR_PLUGINS . $options['plugin'] . '/' . APP . '/validate/' . $options['rule'] . '.php';
} else {
$file = DIR_APP . 'validate/' . $rule . '.php';
}
- $rules = array_merge($rules, include($file));
+ $rules = array_merge($rules, include ($file));
}
$this->rules = $rules;
}
- //remove rule
- function removeRule($rule) {
+ /**
+ * Remove a validation rule by input name.
+ *
+ * @param string $rule Input name to remove.
+ *
+ * @return void
+ */
+ public function removeRule(string $rule): void {
unset($this->rules[$rule]);
}
- //remove keys that are not in the validation list
- function filter($input) {
+ /**
+ * Filter input to only include keys present in the validation rules.
+ *
+ * @param array<string, mixed> $input Raw input data.
+ *
+ * @return array<string, mixed> Filtered input.
+ */
+ public function filter(array $input): array {
$validKeys = array_keys($this->rules);
$filter = [];
foreach ($validKeys as $key) {
- if (strpos($key, '.') != false) {
+ if (str_contains($key, '.')) {
$keys = explode('.', $key);
$filter[$keys[0]][$keys[1]] = arrayPath($input, $key);
} else {
@@ -93,13 +112,16 @@ class Validator {
}
return $filter;
- /*
- return array_filter($input, function ($key) use ($validKeys) {
- return in_array($key, $validKeys);
- }, ARRAY_FILTER_USE_KEY);*/
}
- function validate($input) {
+ /**
+ * Validate input data against loaded rules.
+ *
+ * @param array<string, mixed> $input Input data to validate.
+ *
+ * @return true|array<string, string> True if valid, or array<array-key, mixed> of input-name => error-message pairs.
+ */
+ public function validate(array $input): true|array {
$errors = [];
$errorMessage = false;
@@ -109,9 +131,21 @@ class Validator {
if ($value !== null && $value !== false) {
foreach ($rules as $rule => $options) {
- if (is_array($options)) {
+ //message and name are field metadata, not rules
+ if ($rule === 'message' || $rule === 'name') {
+ continue;
+ }
+
+ $errorMessage = false;
+
+ //rules can be declared as 'ruleName' => options
+ //or as a list of ['ruleName' => options] pairs
+ if (method_exists($this, 'rule' . $rule)) {
+ $ruleName = $rule;
+ $ruleOptions = $options;
+ } elseif (is_array($options)) {
$ruleName = key($options);
- $ruleOptions = $rule[$ruleName] ?? [];
+ $ruleOptions = $options[$ruleName] ?? [];
} else {
$ruleName = $rule;
$ruleOptions = $options;
@@ -127,6 +161,8 @@ class Validator {
if (isset($options['message'])) {
$message = $options['message'];
+ } elseif (is_array($ruleOptions) && isset($ruleOptions['message'])) {
+ $message = $ruleOptions['message'];
}
if (isset($options['name'])) {
@@ -135,6 +171,9 @@ class Validator {
if (method_exists($this, $ruleMethod)) {
$errorMessage = $this->$ruleMethod($value, $ruleOptions, $name, $message, $input);
+ } else {
+ //unknown rules must fail closed instead of silently skipping validation
+ $errorMessage = sprintf('Unknown validation rule "%s" for "%s"', $ruleName, $name);
}
if ($errorMessage) {
@@ -142,25 +181,27 @@ class Validator {
}
}
} else {
- //if (isset($rules['notEmpty'])) {
- //$rule = $rules['notEmpty'];
- $message = $this->defaultMessages['notEmpty']; // $rule['message'] ?? __('%s is empty');
- $name = $rule['name'] ?? $name;
- //}
+ $message = $this->defaultMessages['notEmpty'];
+ $name = $rules['name'] ?? $name;
$errors[$inputName] = sprintf($message, $name);
}
}
- return (empty($errors) ? true : $errors);
+ return empty($errors) ? true : $errors;
}
- function getJSON() {
+ /**
+ * Get validation rules as JSON with default messages injected.
+ *
+ * @return string JSON-encoded rules.
+ */
+ public function getJSON(): string {
foreach ($this->rules as $inputName => &$rules) {
foreach ($rules as $rule => &$value) {
$ruleName = $rule;
- if (! is_array($value)) {
+ if (!is_array($value)) {
if (empty($value)) {
$value = [];
} else {
@@ -168,7 +209,7 @@ class Validator {
}
}
- if (! isset($value['message']) && isset($this->defaultMessages[$ruleName])) {
+ if (!isset($value['message']) && isset($this->defaultMessages[$ruleName])) {
$rules[$ruleName]['message'] = $this->defaultMessages[$ruleName];
}
}
@@ -177,13 +218,35 @@ class Validator {
return json_encode($this->rules);
}
- /* rules */
-
- function ruleOptional($value, $options, $name, $message, $input) {
+ // rules
+
+ /**
+ * Rule: allow optional/empty values.
+ *
+ * @param mixed $value The input value.
+ * @param mixed $options Rule options.
+ * @param string $name Human-readable field name.
+ * @param string $message Error message template.
+ * @param array<string, mixed> $input Full input array.
+ *
+ * @return false Always returns false (no error).
+ */
+ public function ruleOptional(mixed $value, mixed $options, string $name, string $message, array $input): false {
return false;
}
- function ruleNotEmpty($value, $options, $name, $message, $input) {
+ /**
+ * Rule: value must not be empty.
+ *
+ * @param mixed $value The input value.
+ * @param mixed $options Rule options.
+ * @param string $name Human-readable field name.
+ * @param string $message Error message template.
+ * @param array<string, mixed> $input Full input array.
+ *
+ * @return string|false Error message or false if valid.
+ */
+ public function ruleNotEmpty(mixed $value, mixed $options, string $name, string $message, array $input): string|false {
if ($value === '' || $value === false || $value === null) {
return sprintf(__($message), $name);
}
@@ -191,47 +254,113 @@ class Validator {
return false;
}
- function ruleEmail($value, $options, $name, $message, $input) {
- if (! filter_var($value, FILTER_VALIDATE_EMAIL)) {
+ /**
+ * Rule: value must be a valid email address.
+ *
+ * @param mixed $value The input value.
+ * @param mixed $options Rule options.
+ * @param string $name Human-readable field name.
+ * @param string $message Error message template.
+ * @param array<string, mixed> $input Full input array.
+ *
+ * @return string|false Error message or false if valid.
+ */
+ public function ruleEmail(mixed $value, mixed $options, string $name, string $message, array $input): string|false {
+ if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
return sprintf(__($message), $name);
}
return false;
}
- function rule($value, $options, $name, $message, $input) {
- if (! in_array($value, $options)) {
- return sprintf(__($message), $name, implode(', ',$options));
+ /**
+ * Rule: value must be in the allowed options list.
+ *
+ * @param mixed $value The input value.
+ * @param array<int, mixed> $options Allowed values.
+ * @param string $name Human-readable field name.
+ * @param string $message Error message template.
+ * @param array<string, mixed> $input Full input array.
+ *
+ * @return string|false Error message or false if valid.
+ */
+ public function rule(mixed $value, array $options, string $name, string $message, array $input): string|false {
+ if (!in_array($value, $options)) {
+ return sprintf(__($message), $name, implode(', ', $options));
}
return false;
}
- function ruleMaxLength($value, $options, $name, $message, $input) {
- if (! is_string($value) || (strlen($value) > $options)) {
- return sprintf(__($message), $name, $options);
+ /**
+ * Rule: string length must not exceed the maximum.
+ *
+ * @param mixed $value The input value.
+ * @param int $options Maximum length.
+ * @param string $name Human-readable field name.
+ * @param string $message Error message template.
+ * @param array<string, mixed> $input Full input array.
+ *
+ * @return string|false Error message or false if valid.
+ */
+ public function ruleMaxLength(mixed $value, int $options, string $name, string $message, array $input): string|false {
+ if (!is_string($value) || (strlen($value) > $options)) {
+ return sprintf(__($message), $name, $options);
}
return false;
}
- function ruleMinLength($value, $options, $name, $message, $input) {
- if (! is_string($value) || (strlen($value) < $options)) {
+ /**
+ * Rule: string length must meet the minimum.
+ *
+ * @param mixed $value The input value.
+ * @param int $options Minimum length.
+ * @param string $name Human-readable field name.
+ * @param string $message Error message template.
+ * @param array<string, mixed> $input Full input array.
+ *
+ * @return string|false Error message or false if valid.
+ */
+ public function ruleMinLength(mixed $value, int $options, string $name, string $message, array $input): string|false {
+ if (!is_string($value) || (strlen($value) < $options)) {
return sprintf(__($message), $name, $options);
}
return false;
}
- function ruleAllowedValues($value, $options, $name, $message, $input) {
- if (! is_string($value) || (strlen($value) > $options)) {
- return sprintf(__($message), $name, implode(', ' ,$options));
+ /**
+ * Rule: value must be one of the allowed values.
+ *
+ * @param mixed $value The input value.
+ * @param array<array-key, mixed> $options Allowed values list.
+ * @param string $name Human-readable field name.
+ * @param string $message Error message template.
+ * @param array<string, mixed> $input Full input array.
+ *
+ * @return string|false Error message or false if valid.
+ */
+ public function ruleAllowedValues(mixed $value, array $options, string $name, string $message, array $input): string|false {
+ if (!in_array($value, $options)) {
+ return sprintf(__($message), $name, implode(', ', $options));
}
return false;
}
- function ruleSession($value, $options, $name, $message, $input) {
+ /**
+ * Rule: value must match a session value.
+ *
+ * @param mixed $value The input value.
+ * @param string $options Session key to compare against.
+ * @param string $name Human-readable field name.
+ * @param string $message Error message template.
+ * @param array<string, mixed> $input Full input array.
+ *
+ * @return string|false Error message or false if valid.
+ */
+ public function ruleSession(mixed $value, string $options, string $name, string $message, array $input): string|false {
if (\Vvveb\session($options) != $value) {
return sprintf(__($message), $name, $options);
}
@@ -239,64 +368,112 @@ class Validator {
return false;
}
- function ruleCaptcha($value, $options, $name, $message, $input) {
- if ($input[$options] != $value) {
+ /**
+ * Rule: value must match the captcha input.
+ *
+ * @param mixed $value The input value.
+ * @param string $options Name of the captcha input field.
+ * @param string $name Human-readable field name.
+ * @param string $message Error message template.
+ * @param array<string, mixed> $input Full input array.
+ *
+ * @return string|false Error message or false if valid.
+ */
+ public function ruleCaptcha(mixed $value, string $options, string $name, string $message, array $input): string|false {
+ if (($input[$options] ?? null) != $value) {
return sprintf(__($message), $name, $options);
}
return false;
}
- function ruleMatch($value, $options, $name, $message, $input) {
- if ($input[$options] != $value) {
+ /**
+ * Rule: value must match another input field value.
+ *
+ * @param mixed $value The input value.
+ * @param string $options Name of the field to match.
+ * @param string $name Human-readable field name.
+ * @param string $message Error message template.
+ * @param array<string, mixed> $input Full input array.
+ *
+ * @return string|false Error message or false if valid.
+ */
+ public function ruleMatch(mixed $value, string $options, string $name, string $message, array $input): string|false {
+ if (($input[$options] ?? null) != $value) {
return sprintf(__($message), $name, $options);
}
return false;
}
- function ruleNumeric($value, $options, $name, $message, $input) {
- if (! is_numeric($value)) {
- return sprintf(__($message), $name, $options);
+ /**
+ * Rule: value must contain only decimal digits.
+ *
+ * @param mixed $value The input value.
+ * @param mixed $options Rule options.
+ * @param string $name Human-readable field name.
+ * @param string $message Error message template.
+ * @param array<string, mixed> $input Full input array.
+ *
+ * @return string|false Error message or false if valid.
+ */
+ public function ruleDigit(mixed $value, mixed $options, string $name, string $message, array $input): string|false {
+ if (!is_scalar($value) || !ctype_digit((string)$value)) {
+ return sprintf(__($message), $name);
}
return false;
}
- function rulePasswordComplexity($value, $options, $name, $message, $input) {
- switch ($options) {
- case 'low':
- $regex =
- '/^' . // Start anchor
- '(?=.*[A-Z])' . // Ensure string has one uppercase letters.
- '(?=.*[0-9])' . // Ensure string has one digits.
- '(?=.*[a-z].*[a-z].*[a-z])' . // Ensure string has three lowercase letters.
- '.*$/';
+ /**
+ * Rule: value must be numeric.
+ *
+ * @param mixed $value The input value.
+ * @param mixed $options Rule options.
+ * @param string $name Human-readable field name.
+ * @param string $message Error message template.
+ * @param array<string, mixed> $input Full input array.
+ *
+ * @return string|false Error message or false if valid.
+ */
+ public function ruleNumeric(mixed $value, mixed $options, string $name, string $message, array $input): string|false {
+ if (!is_numeric($value)) {
+ return sprintf(__($message), $name, $options);
+ }
- break;
+ return false;
+ }
- case 'medium':
- $regex =
- '/^' . // Start anchor
- '(?=.*[A-Z].*[A-Z])' . // Ensure string has two uppercase letters.
- '(?=.*[!@#$&*%])' . // Ensure string has one special case letter.
- '(?=.*[0-9].*[0-9])' . // Ensure string has two digits.
+ /**
+ * Rule: password must meet complexity requirements.
+ *
+ * @param string $value The password value.
+ * @param string $options Complexity level ('low', 'medium', 'high').
+ * @param string $name Human-readable field name.
+ * @param string $message Error message template.
+ * @param array<string, mixed> $input Full input array.
+ *
+ * @return string|false Error message or false if valid.
+ */
+ public function rulePasswordComplexity(string $value, string $options, string $name, string $message, array $input): string|false {
+ $regex = match ($options) {
+ 'low' => '/^' . // Start anchor
+ '(?=.*[A-Z])' . // Ensure string has one uppercase letters.
+ '(?=.*[0-9])' . // Ensure string has one digits.
'(?=.*[a-z].*[a-z].*[a-z])' . // Ensure string has three lowercase letters.
- '.*$/';
+ '.*$/',
- case 'high':
- $regex =
- '/^' . // Start anchor
+ 'medium', 'high' => '/^' . // Start anchor
'(?=.*[A-Z].*[A-Z])' . // Ensure string has two uppercase letters.
'(?=.*[!@#$&*%])' . // Ensure string has one special case letter.
'(?=.*[0-9].*[0-9])' . // Ensure string has two digits.
'(?=.*[a-z].*[a-z].*[a-z])' . // Ensure string has three lowercase letters.
- '.*$/';
+ '.*$/',
- break;
- }
+ default => '',
+ };
- if (($result = preg_match($regex, $value)) == false) {
+ if (!$regex || !preg_match($regex, $value)) {
return sprintf(__($message), $name, $options);
}
diff --git a/system/vtpl/debug.php b/system/vtpl/debug.php
index af81860..f2c34fa 100755
--- a/system/vtpl/debug.php
+++ b/system/vtpl/debug.php
@@ -21,7 +21,10 @@
*/
/**
- * Vvveb.
+ * VtplDebug - Debug logging and console output for the Vtpl template engine.
+ *
+ * Provides methods to log template processing events and render them as
+ * an HTML debug console overlay.
*
* Copyright (C) 2022 Ziadin Givan
*
@@ -40,174 +43,233 @@
*
*/
class VtplDebug {
- private $enabled = false;
-
- private $debugLog = [];
-
- private $debugHtml;
-
- function enabled() {
+ /**
+ * Whether debug logging is enabled.
+ *
+ * @var bool
+ */
+ private bool $enabled = false;
+
+ /**
+ * Array of debug log entries.
+ *
+ * @var array<int, array{string: string}>
+ */
+ private array $debugLog = [];
+
+ /**
+ * Accumulated HTML output for the debug console.
+ *
+ * @var string
+ */
+ private string $debugHtml = '';
+
+ /**
+ * Check if debugging is active.
+ *
+ * @return bool True if debug is enabled or log entries exist.
+ */
+ public function enabled(): bool {
return $this->enabled || $this->debugLog;
}
- function enable($switch) {
+ /**
+ * Enable or disable debug logging.
+ *
+ * @param bool $switch Whether to enable debugging.
+ *
+ * @return void
+ */
+ public function enable(bool $switch): void {
$this->enabled = $switch;
}
- function log($type,$message) {
+ /**
+ * Log a debug message with a given type.
+ *
+ * @param string|int $type Log entry type (e.g. 'LOAD', 'SAVE', 'SELECTOR').
+ * @param string $message The debug message.
+ *
+ * @return void
+ */
+ public function log(string|int $type, string $message): void {
if ($this->enabled) {
- $this->debugLog[][$type]= $message;
+ $this->debugLog[][$type] = $message;
}
}
- function addDebugHtmlLine($command, $parameters, $break = '<br/>') {
+ /**
+ * Append an HTML line to the debug console output.
+ *
+ * @param string $command The command label (e.g. 'LOAD', 'SAVE').
+ * @param string $parameters The details to display.
+ * @param string $break The HTML line break string.
+ *
+ * @return void
+ */
+ public function addDebugHtmlLine(string $command, string $parameters, string $break = '<br/>'): void {
$this->debugHtml .= "<span>&nbsp;<b>$command</b> $parameters</span>$break";
}
- function debugLogToHtml() {
+ /**
+ * Convert the debug log entries to HTML output.
+ *
+ * @return void
+ */
+ public function debugLogToHtml(): void {
foreach ($this->debugLog as $line) {
$type = key($line);
$message = $line[$type];
switch ($type) {
case 'LOAD':
- $this->addDebugHtmlLine('LOAD',$message);
+ $this->addDebugHtmlLine('LOAD', $message);
- break;
+ break;
case 'SAVE':
- $this->addDebugHtmlLine('SAVE',$message);
+ $this->addDebugHtmlLine('SAVE', $message);
- break;
+ break;
case 'SELECTOR':
- $this->addDebugHtmlLine('SELECTOR',
- /*$this->cssToXpath($message) . */"<a href='#'
- onclick=\"return vtpl_selector_click('$message')\"
+ $this->addDebugHtmlLine(
+ 'SELECTOR',
+ // $this->cssToXpath($message) .
+ "<a href='#'
+ onclick=\"return vtpl_selector_click('$message')\"
onmouseover=\"return vtpl_selector_over('$message')\"
onmouseout=\"return vtpl_selector_out('$message')\">
- $message</a>", '');
+ $message</a>",
+ ''
+ );
- break;
+ break;
case 'SELECTOR_STRING':
- $this->addDebugHtmlLine('INJECT STRING',$message);
+ $this->addDebugHtmlLine('INJECT STRING', $message);
- break;
+ break;
case 'SELECTOR_PHP':
- $this->addDebugHtmlLine('INJECT PHP',htmlentities($message));
+ $this->addDebugHtmlLine('INJECT PHP', htmlentities($message));
- break;
+ break;
case 'SELECTOR_VARIABLE':
- $this->addDebugHtmlLine('INJECT VARIABLE',$message);
+ $this->addDebugHtmlLine('INJECT VARIABLE', $message);
- break;
+ break;
case 'SELECTOR_FROM':
- $this->addDebugHtmlLine('EXTERNAL HTML',$message);
+ $this->addDebugHtmlLine('EXTERNAL HTML', $message);
- break;
+ break;
case 'CSS_XPATH_TRANSFORM':
if (VTPL_DEBUG_SHOW_XPATH) {
- $this->addDebugHtmlLine('RESULTED XPATH',
- "<a href='#'
- onclick=\"return vtpl_selector_click('$message')\"
+ $this->addDebugHtmlLine(
+ 'RESULTED XPATH',
+ "<a href='#'
+ onclick=\"return vtpl_selector_click('$message')\"
onmouseover=\"return vtpl_selector_over('$message')\"
onmouseout=\"return vtpl_selector_out('$message')\">
- $message</a>");
+ $message</a>"
+ );
}
- break;
+ break;
case 'CSS_SELECTOR':
- $this->addDebugHtmlLine('INVALID CSS SELECTOR',htmlentities($message));
+ $this->addDebugHtmlLine('INVALID CSS SELECTOR', htmlentities($message));
- break;
+ break;
default:
- $this->addDebugHtmlLine('',$message);
+ $this->addDebugHtmlLine('', $message);
- break;
- }
+ break;
+ }
}
}
- function printLog() {
+ /**
+ * Print the debug console HTML output.
+ *
+ * @return void
+ */
+ public function printLog(): void {
$this->debugLogToHtml();
- echo
-<<<HTML
-<script>
-function vtplSelectorOver(selector)
-{
- jQuery(selector).addClass('vtpl_selected');
- return false;
-}
-function vtplSelectorOut(selector)
-{
- jQuery(selector).removeClass('vtpl_selected');
- return false;
-}
-
-//this needs firebug or equivalent
-function vtplSelectorClick(selector)
-{
- console.log(jQuery(selector));
- return false;
-}
-
-function vtplHide(selector)
-{
- if (jQuery(".vtpl_console_log_content").css('display') == 'none')
- {
- jQuery(".vtpl_console_log").css({height:"350px"});
- } else
- {
- jQuery(".vtpl_console_log").css({height:"30px"});
- }
- jQuery(".vtpl_console_log_content").toggle("slow");
- return false;
-}
-
-function vtplClose()
-{
- jQuery(".vtpl_console_log").remove();
- return false;
-}
-</script>
-<style>
-.vtpl_selected {
- border:5px solid red !important;
-}
-html {
- padding-bottom:350px;
-}
-.vtpl_console_log {
- background:#fff;
- z-index:10000;
- position:fixed;
- line-height: 1.6;
- left:0;
- bottom:0;
- width:100%;
- height:300px;
- padding:1rem;
- overflow:auto;
- border:1px dashed #ccc;
-}
-.vtpl_console_log_content {
- margin-top:1rem;
-}
-</style>
-<div class="vtpl_console_log">
- <a href="#" onclick="return vtplHide()">Toggle</a>
- <a href="#" onclick="return vtplClose()">Close</a>
- <div class="vtpl_console_log_content">
- $this->debugHtml;
- </div>
-</div>
-HTML;
+ echo <<<HTML
+ <script>
+ function vtplSelectorOver(selector)
+ {
+ jQuery(selector).addClass('vtpl_selected');
+ return false;
+ }
+ function vtplSelectorOut(selector)
+ {
+ jQuery(selector).removeClass('vtpl_selected');
+ return false;
+ }
+
+ //this needs firebug or equivalent
+ function vtplSelectorClick(selector)
+ {
+ console.log(jQuery(selector));
+ return false;
+ }
+
+ function vtplHide(selector)
+ {
+ if (jQuery(".vtpl_console_log_content").css('display') == 'none')
+ {
+ jQuery(".vtpl_console_log").css({height:"350px"});
+ } else
+ {
+ jQuery(".vtpl_console_log").css({height:"30px"});
+ }
+ jQuery(".vtpl_console_log_content").toggle("slow");
+ return false;
+ }
+
+ function vtplClose()
+ {
+ jQuery(".vtpl_console_log").remove();
+ return false;
+ }
+ </script>
+ <style>
+ .vtpl_selected {
+ border:5px solid red !important;
+ }
+ html {
+ padding-bottom:350px;
+ }
+ .vtpl_console_log {
+ background:#fff;
+ z-index:10000;
+ position:fixed;
+ line-height: 1.6;
+ left:0;
+ bottom:0;
+ width:100%;
+ height:300px;
+ padding:1rem;
+ overflow:auto;
+ border:1px dashed #ccc;
+ }
+ .vtpl_console_log_content {
+ margin-top:1rem;
+ }
+ </style>
+ <div class="vtpl_console_log">
+ <a href="#" onclick="return vtplHide()">Toggle</a>
+ <a href="#" onclick="return vtplClose()">Close</a>
+ <div class="vtpl_console_log_content">
+ $this->debugHtml;
+ </div>
+ </div>
+ HTML;
}
}
diff --git a/system/vtpl/macros.php b/system/vtpl/macros.php
old mode 100644
new mode 100755
index 09f6860..00c8bbd
--- a/system/vtpl/macros.php
+++ b/system/vtpl/macros.php
@@ -20,43 +20,65 @@
*
*/
-use Vvveb\System\Functions\Str;
-
-/*
- * Escape string
+/**
+ * Escape a character in a string by prepending a backslash.
+ *
* Ex: @@macro Escape("Escape ' this","'")@@
+ *
+ * @param Vtpl $vtpl The Vtpl instance.
+ * @param DOMNode $node The current DOM node.
+ * @param string $string The string to escape.
+ * @param string $char The character to escape.
+ *
+ * @return string The escaped string.
*/
-function vtplEscape($vtpl, $node, $string, $char = '\'') {
+function vtplEscape(Vtpl $vtpl, DOMNode $node, string $string, string $char = '\''): string {
return str_replace($char, '\\' . $char, $string);
}
-/*
- * Convert name[key] > ['name']['key']
+/**
+ * Convert a form field name with array notation to PHP array key notation.
+ *
* Ex: @@macro vtplpostNameToArrayKey("name[key]")@@
+ *
+ * @param Vtpl $vtpl The Vtpl instance.
+ * @param DOMNode $node The current DOM node.
+ * @param string $keyAttribute The form field name to convert.
+ *
+ * @return string The converted array<array-key, mixed> key string.
*/
-function vtplpostNameToArrayKey($vtpl, $node, $keyAttribute) {
+function vtplpostNameToArrayKey(Vtpl $vtpl, DOMNode $node, string $keyAttribute): string {
return Vvveb\postNameToArrayKey($keyAttribute);
}
-/*
- * Get attributes as a key => value array for elements specified by selector
+/**
+ * Get attributes as a key => value array for elements specified by a CSS selector.
+ *
* Ex: @@macro KeyValue(".settings input","data-v-option","data-v-option")@@
+ *
+ * @param Vtpl $vtpl The Vtpl instance.
+ * @param DOMNode $node The current DOM node.
+ * @param string $selector CSS selector to match elements.
+ * @param string $keyAttribute Attribute name to use as the array key.
+ * @param string $valueAttribute Attribute name to use as the array value.
+ *
+ * @return string A var_export'd array<array-key, mixed> of key => value pairs.
*/
-function vtplKeyValue($vtpl, $node, $selector, $keyAttribute, $valueAttribute) {
+function vtplKeyValue(Vtpl $vtpl, DOMNode $node, string $selector, string $keyAttribute, string $valueAttribute): string {
$values = [];
- $elements = $vtpl->xpath->query($vtpl->cssToXpath($selector));
+ $elements = $vtpl->query($selector);
if ($elements && $elements->length) {
foreach ($elements as $element) {
$key = $value = false;
foreach ($element->attributes as $attribute) {
- if ($attribute->name == $keyAttribute) {
+ if ($attribute->name === $keyAttribute) {
$key = $attribute->value;
}
- if ($attribute->name == $valueAttribute) {
+ if ($attribute->name === $valueAttribute) {
$value = $attribute->value;
}
}
@@ -67,96 +89,49 @@ function vtplKeyValue($vtpl, $node, $selector, $keyAttribute, $valueAttribute) {
}
}
- return var_export($values, 1);
+ return var_export($values, true);
}
-/*
- If macro enables elements with data-v-if="condition = true" to be visible only if condition is true also data-v-if-not="condition = true"
- Parameter can have the following formats
- variable = variable ex product.price = price this will result in $product['price'] == $price
- variable = 'string' ex this.stock = 'available' this will result in $this->price == $price
+/**
+ * Compile a conditional expression into a PHP if-condition string.
+ *
+ * Transforms variable dot-notation to PHP array syntax, handles operators,
+ * and wraps in isset() checks where needed.
+ *
+ * @param string $condition The conditional expression to compile.
+ *
+ * @return string The compiled PHP condition string.
*/
-/*
-function ifCondition($string = '') {
- $logic = ['&&', '\|\|', 'AND', 'OR'];
- $regex = '/\s+(' . implode(')\s+|\s+(', $logic) . ')\s+/i';
- $conditions = preg_split($regex, $string, 0, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
-
- $return = '( ';
-
- foreach ($conditions as $condition) {
- if (in_array(str_replace('|', '\|', $condition), $logic)) {
- $return .= " ) $condition ( ";
- } else {
- $operators = ['>', '<', '<=', '>=', '=', '!='];
- $operatorsMatch = implode('',array_unique(str_split(implode('', $operators))));
- $condition = html_entity_decode($condition);
-
- $key = $condition;
- $compare = $condition;
- $operator = false;
- $value = false;
-
- if ($key = strpbrk($condition, $operatorsMatch)) {
- $operator = trim(Str::match("/^([ $operatorsMatch]+)/", $key));
- $value = Str::match("/[ $operatorsMatch]+(.+)$/", $key);
- $compare = Str::match("/(.+?)[ $operatorsMatch]/", $condition);
- }
-
- if (strpos($value, 'this') === 0) {
- $value = str_replace('this.', 'this->', $value);
- }
-
- if (strpos($compare, 'this') === 0) {
- $compare = str_replace('this.', 'this->', $compare);
- }
-
- if (($compare && $compare[0] != "'") && ! is_numeric($compare) && $compare !== 'null') {
- $compare = '$' . $compare;
- }
-
- if (($value && $value[0] != "'") && ! is_numeric($value) && $value !== 'null') {
- $value = '$' . $value;
- }
-
- if ($operator == '=') {
- $operator = '==';
- }
-
- $value = Vvveb\dotToArrayKey($value);
- $compare = Vvveb\dotToArrayKey($compare);
-
- $return .= "(isset($compare) && ($compare $operator $value))";
- }
- }
- $return .= ' )';
-
- return $return;
-}
-*/
-
-function ifCondition($condition = '') {
+function ifCondition(string $condition = ''): string {
//remove php functions
$condition = preg_replace('/[a-zA-Z_][\w\\]*\([^\)]*\)/', '', $condition);
//transform variables to php variables
$array_keys = '';
- $condition = preg_replace_callback('/[\'"]?[a-zA-Z_][\w\.-]*[\'"]?/',
- function ($matches) use (&$array_keys) {
+ $condition = preg_replace_callback(
+ '/[\'"]?[a-zA-Z_][\w\.-]*[\'"]?/',
+ function($matches) use (&$array_keys) {
$value = $matches[0];
- $len = strlen($value) - 1;
-
- if ($value == 'null' || $value == 'NULL'
- || $value[0] == '\'' || $value[$len] == '\''
- || $value[0] == '"' || $value[$len] == '"') {
+ $len = strlen($value) - 1;
+
+ if ($value === 'null' || $value === 'NULL'
+ || $value === 'true' || $value === 'TRUE'
+ || $value === 'false' || $value === 'FALSE'
+ || $value === 'and' || $value === 'or' || $value === 'xor'
+ || $value[0] === '\'' || $value[$len] === '\''
+ || $value[0] === '"' || $value[$len] === '"') {
return $value;
}
- if (strpos($value, 'this') === 0) {
+ if ($value === 'this') {
+ return '$this';
+ }
+
+ if (str_starts_with($value, 'this')) {
$value = str_replace('this.', 'this->', $value);
}
- if (strpos($value, '.') !== 0) {
+ if (str_contains($value, '.')) {
$value = Vvveb\dotToArrayKey($value);
$value = '$' . $value;
@@ -166,10 +141,17 @@ function ifCondition($condition = '') {
$array_keys .= "isset($value)";
} else {
$value = '$' . $value;
+
+ if ($array_keys) {
+ $array_keys .= ' && ';
+ }
+ $array_keys .= "isset($value)";
}
return $value;
- }, $condition);
+ },
+ $condition
+ );
//double ==
$condition = preg_replace('/(?<![<>\!])=+/', ' == ', $condition);
@@ -181,38 +163,65 @@ function ifCondition($condition = '') {
return $array_keys . "($condition)";
}
-function vtplIfCondition($vtpl, $node, $string = '') {
+/**
+ * Macro wrapper for ifCondition() used in Vtpl templates.
+ *
+ * @param Vtpl $vtpl The Vtpl instance.
+ * @param DOMNode $node The current DOM node.
+ * @param string $string The conditional expression.
+ *
+ * @return string The compiled PHP condition string.
+ */
+function vtplIfCondition(Vtpl $vtpl, DOMNode $node, string $string = ''): string {
return ifCondition($string);
}
-/*
-Remove class from node, used by data-v-class-if
+/**
+ * Remove a CSS class from a DOM node.
+ *
+ * Used by data-v-class-if to strip classes before conditional re-application.
+ *
+ * @param Vtpl $vtpl The Vtpl instance.
+ * @param DOMNode $node The current DOM node.
+ * @param string $className The class name to remove.
+ *
+ * @return void
*/
-function vtplRemoveClass($vtpl, $node, $className = '') {
- if (! $className) {
+function vtplRemoveClass(Vtpl $vtpl, DOMNode $node, string $className = ''): void {
+ if (!$className) {
return;
}
$value = $node->getAttribute('class');
- if (strpos($value, $className) !== false) {
+ if (str_contains($value, $className)) {
$node->setAttribute('class', str_replace($className, '', $value));
}
}
-function vtplIfClass($vtpl, $node) {
+/**
+ * Process data-v-class-if-* and data-v-class-if-not-* attributes on a node.
+ *
+ * Generates PHP code that conditionally adds CSS classes based on expressions.
+ *
+ * @param Vtpl $vtpl The Vtpl instance.
+ * @param DOMNode $node The current DOM node.
+ *
+ * @return string PHP code snippet that echoes conditional class names.
+ */
+function vtplIfClass(Vtpl $vtpl, DOMNode $node): string {
$if = [];
$ifnot = [];
$length = $node->attributes->length;
- for ($i = 0; $i < $length; ++$i) {
+ for ($i = 0; $i < $length; $i++) {
if ($item = $node->attributes->item($i)) {
$name = $item->name;
- if (strpos($name, 'data-v-class-if-not-') !== false) {
+ if (str_contains($name, 'data-v-class-if-not-')) {
$name = str_replace('data-v-class-if-not-', '', $name);
$ifnot[$name] = $item->value;
} else {
- if (strpos($name, 'data-v-class-if-') !== false) {
+ if (str_contains($name, 'data-v-class-if-')) {
$name = str_replace('data-v-class-if-', '', $name);
$if[$name] = $item->value;
}
@@ -224,14 +233,14 @@ function vtplIfClass($vtpl, $node) {
$value = $node->getAttribute('class');
foreach ($ifnot as $class => $cond) {
- $value = str_replace($class, '',$value);
+ $value = str_replace($class, '', $value);
//$node->removeAttribute("data-v-class-if-not-$class");
$condition = ifCondition($cond);
$return .= "if (!($condition)) {echo ' $class';}";
}
foreach ($if as $class => $cond) {
- $value = str_replace($class, '',$value);
+ $value = str_replace($class, '', $value);
//$node->removeAttribute("data-v-class-if-$class");
$condition = ifCondition($cond);
$return .= "if ($condition) {echo ' $class';}";
@@ -244,20 +253,30 @@ function vtplIfClass($vtpl, $node) {
return $return;
}
-function vtplIfAttr($vtpl, $node) {
+/**
+ * Process data-v-attr-if-* and data-v-attr-if-not-* attributes on a node.
+ *
+ * Generates PHP code that conditionally outputs HTML attributes based on expressions.
+ *
+ * @param Vtpl $vtpl The Vtpl instance.
+ * @param DOMNode $node The current DOM node.
+ *
+ * @return void
+ */
+function vtplIfAttr(Vtpl $vtpl, DOMNode $node): void {
$if = [];
$ifnot = [];
$length = $node->attributes->length;
- for ($i = 0; $i < $length; ++$i) {
+ for ($i = 0; $i < $length; $i++) {
if ($item = $node->attributes->item($i)) {
$name = $item->name;
- if (strpos($name, 'data-v-attr-if-not-') !== false) {
+ if (str_contains($name, 'data-v-attr-if-not-')) {
$name = str_replace('data-v-attr-if-not-', '', $name);
$ifnot[$name] = $item->value;
} else {
- if (strpos($name, 'data-v-attr-if-') !== false) {
+ if (str_contains($name, 'data-v-attr-if-')) {
$name = str_replace('data-v-attr-if-', '', $name);
$if[$name] = $item->value;
}
@@ -274,8 +293,8 @@ function vtplIfAttr($vtpl, $node) {
$node->removeAttribute($value);
$condition = ifCondition($cond);
- $if = "<?php if (!($condition)) {echo '$attr';}?>";
- $vtpl->addNodeNewAttribute($node, $if);
+ $ifCode = "<?php if (!($condition)) {echo '$attr';}?>";
+ $vtpl->addNodeNewAttribute($node, $ifCode);
}
foreach ($if as $value => $cond) {
@@ -287,7 +306,7 @@ function vtplIfAttr($vtpl, $node) {
$node->removeAttribute($value);
$condition = ifCondition($cond);
- $if = "<?php if ($condition) {echo '$attr';}?>";
- $vtpl->addNodeNewAttribute($node, $if);
+ $ifCode = "<?php if ($condition) {echo '$attr';}?>";
+ $vtpl->addNodeNewAttribute($node, $ifCode);
}
}
diff --git a/system/vtpl/vtpl.php b/system/vtpl/vtpl.php
index 0269d74..844969d 100755
--- a/system/vtpl/vtpl.php
+++ b/system/vtpl/vtpl.php
@@ -31,73 +31,111 @@ define('VTPL_CLEAN_COMP_OPT', false);
define('VTPL_DEBUG_SHOW_XPATH', true);
define('VTPL_DONT_ALLOW_PHP', true); //don't set to false unless ABSOLUTELY NECESSARY!
+// PHP placeholder constants - used to embed PHP inside the DOM without triggering parsing.
+// These are replaced with real php tags in cleanHtml().
+define('VTPL_PHP_CDATA_OPEN', '<_script language="php"><![CDATA[');
+define('VTPL_PHP_CDATA_CLOSE', ']]></_script>');
+define('VTPL_PHP_OPEN', '<_script language="php">');
+define('VTPL_PHP_CLOSE', '</_script>');
+
include 'macros.php';
include 'debug.php';
+/**
+ * Vtpl template engine — compiles `.tpl` selector commands against plain-HTML documents.
+ *
+ * See each property declaration below for individual types.
+ */
#[\AllowDynamicProperties]
class Vtpl {
- private $template;
+ /** @var string */
+ private string $template = '';
- private $templatePath;
+ /** @var array<array-key, mixed> */
+ private array $templatePath = [];
- private $htmlPath;
+ /** @var string */
+ private string $htmlPath = '';
- private $relativePath;
+ /** @var string */
+ private string $relativePath = '';
- private $htmlSourceFile;
+ /** @var DOMDocument */
+ private Dom\HTMLDocument|DOMDocument $document;
- private $document;
+ /** @var bool */
+ private bool $legacy = true;
- private $xpath;
+ /** @var ?DOMXPath */
+ private ?DOMXPath $xpath = null;
- private $extension = 'tpl';
+ /** @var string */
+ private string $extension = 'tpl';
- private $translationFunction = '\Vvveb\__';
+ /** @var string */
+ private string $translationFunction = '\Vvveb\__';
- private $removeComments = true;
+ /** @var bool */
+ private bool $removeComments = true;
- private $removeWhitespace = false;
+ /** @var bool */
+ private bool $removeVattrs = false;
- private $removeVattrs = false;
-
- private $minifyHtml = VTPL_HTML_MINIFY;
+ /** @var bool */
+ private bool $minifyHtml = VTPL_HTML_MINIFY;
- private $documentType = 'html';
+ /** @var string */
+ private string $documentType = 'html';
- private $checkSyntax = true;
+ /** @var bool */
+ private bool $checkSyntax = true;
- private $selector;
+ /** @var ?string */
+ private ?string $selector = null;
- private $selectors;
+ /** @var array<array-key, mixed>|null */
+ private ?array $selectors = null;
- private $replaceConstants;
+ /** @var array<array-key, mixed>|null */
+ private ?array $replaceConstants = null;
- private $componentId;
+ /** @var ?int */
+ private ?int $componentId = null;
- private $componentContent;
+ /** @var ?string */
+ private ?string $componentContent = null;
- private $froms;
+ /** @var array<array-key, mixed>|null */
+ private ?array $froms = null;
- private $constants;
+ /** @var array<array-key, mixed> */
+ private array $constants = [];
- private $variables;
+ /** @var array<array-key, mixed> */
+ private array $variables = [];
- private $strings;
+ /** @var array<array-key, mixed> */
+ private array $strings = [];
- private $scripts;
+ /** @var array<array-key, mixed> */
+ private array $scripts = [];
- private $debug;
+ /** @var VtplDebug */
+ private VtplDebug $debug;
- private $phpCode;
+ /** @var array<array-key, mixed> */
+ private array $phpCode = [];
- private $modifiers = ['outerHTML', 'text', 'before', 'after', 'append', 'prepend', 'deleteAllButFirst', 'deleteAllButFirstChild', 'delete', 'if_exists', 'hide', 'addClass', 'removeClass'];
+ /** @var array<array-key, mixed> */
+ private array $modifiers = ['outerHTML', 'text', 'before', 'after', 'append', 'prepend', 'deleteAllButFirst', 'deleteAllButFirstChild', 'delete', 'if_exists', 'hide', 'addClass', 'removeClass'];
- private $variableFilters =
+ /** @var array<array-key, mixed> */
+ private array $variableFilters =
[
'capitalize' => 'ucfirst($$0)',
'html_to_text' => 'Vvveb\htmlToText($$0)',
- 'cdata' => 'CDATA_START . $$0. CDATA_END',
+ 'cdata' => 'CDATA_START . ( $$0 ). CDATA_END',
'friendly_date' => 'Vvveb\friendlyDate($$0)',
'friendly_number' => 'Vvveb\parseQuantity($$0)',
'human_readable' => 'Vvveb\humanReadable($$0)',
@@ -120,21 +158,33 @@ class Vtpl {
'without_decimals' => 'substr($$0, 0, strrpos($$0, \'.\'))',
];
- private $attributesIndex = 0;
+ /** @var int */
+ private int $attributesIndex = 0;
- private $newAttributesIndex = 0;
+ /** @var int */
+ private int $newAttributesIndex = 0;
- private $constantsIndex = 0;
+ /** @var array<array-key, mixed> */
+ private array $attributes = [];
- private $attributes = [];
+ /** @var array<array-key, mixed> */
+ private array $newAttributes = [];
- private $newAttributes = [];
+ /** @var bool */
+ private bool $externalElements = false;
- private $constatns = [];
+ /** @var bool */
+ public bool $escapeInline = false;
- private $external_elements = false;
+ /** @var array<array-key, mixed> */
+ private array $prefix = [];
- function __construct($selector = null, $componentId = null, $componentContent = null) {
+ /**
+ * @param ?string $selector
+ * @param ?int $componentId
+ * @param ?string $componentContent
+ */
+ public function __construct(?string $selector = null, ?int $componentId = null, ?string $componentContent = null) {
$this->templatePath = [];
$this->debug = new VtplDebug();
@@ -147,39 +197,82 @@ class Vtpl {
$this->componentId = $componentId;
$this->componentContent = $componentContent;
- // libxml_disable_entity_loader();
- $this->document = new DomDocument();
- $this->document->preserveWhiteSpace = true;
- $this->document->recover = true;
- $this->document->strictErrorChecking = false;
- $this->document->substituteEntities = false;
- $this->document->formatOutput = false;
- $this->document->resolveExternals = false;
- $this->document->validateOnParse = false;
- $this->document->xmlStandalone = true;
+ //libxml_disable_entity_loader();
+
+ $this->document = new DOMDocument();
+ $this->legacy = true;
+
+ $this->configureDomDocument($this->document);
}
- function removeVattrs($flag = true) {
+ /**
+ * Apply standard configuration options to a DOMDocument instance.
+ *
+ * @param DOMDocument $doc
+ *
+ * @return void
+ */
+ private function configureDomDocument(Dom\HTMLDocument|DOMDocument $doc): void {
+ if ($this->legacy) {
+ $doc->preserveWhiteSpace = true;
+ $doc->recover = true;
+ $doc->strictErrorChecking = false;
+ $doc->substituteEntities = false;
+ $doc->formatOutput = false;
+ $doc->resolveExternals = false;
+ $doc->validateOnParse = false;
+ $doc->xmlStandalone = true;
+ }
+ }
+
+ /**
+ * @param bool $flag
+ *
+ * @return void
+ */
+ public function removeVattrs(bool $flag = true): void {
$this->removeVattrs = $flag;
- }
-
- function setMinifyHtml($flag = true) {
+ }
+
+ /**
+ * @param bool $flag
+ *
+ * @return void
+ */
+ public function setMinifyHtml(bool $flag = true): void {
$this->minifyHtml = $flag;
}
- function getDocumentType() {
+ /**
+ * @return string
+ */
+ public function getDocumentType(): string {
return $this->documentType;
}
- function getDocument() {
+ /**
+ * @return Dom\Document|DOMDocument
+ */
+ public function getDocument(): Dom\Document|DOMDocument {
return $this->document;
}
- function addCommand($selector, $command = false) {
+ /**
+ * @param ?string $selector
+ * @param false|string $command
+ *
+ * @return void
+ */
+ public function addCommand(?string $selector, false|string $command = false): void {
if ($selector) {
$this->template .= "\n $selector";
if ($command) {
+ //if not php code then quote string
+ if (!str_starts_with($command, '<?')) {
+ $command = "'$command'";
+ }
+
$this->template .= " = $command\n";
} else {
$this->template .= "\n";
@@ -187,21 +280,42 @@ class Vtpl {
}
}
- function setHtmlPath($path) {
+ /**
+ * @param string $path
+ *
+ * @return void
+ */
+ public function setHtmlPath(string $path): void {
$this->htmlPath = $path;
}
- function setRelativePath($path) {
+ /**
+ * @param string $path
+ *
+ * @return void
+ */
+ public function setRelativePath(string $path): void {
$this->relativePath = $path;
}
- function addTemplatePath($path) {
+ /**
+ * @param string $path
+ *
+ * @return void
+ */
+ public function addTemplatePath(string $path): void {
if ($path) {
$this->templatePath[] = $path;
}
}
- function loadTemplateFile($templateFile, $before = false) {
+ /**
+ * @param string $templateFile
+ * @param bool $before
+ *
+ * @return void
+ */
+ public function loadTemplateFile(string $templateFile, bool $before = false): void {
if (file_exists($templateFile)) {
if ($before) {
$this->template = file_get_contents($templateFile) . "\n\n" . $this->template;
@@ -211,76 +325,82 @@ class Vtpl {
}
}
- function loadTemplateFileFromPath($templateFile, $extra = false) {
+ /**
+ * @param string $templateFile
+ * @param false|string $extra
+ *
+ * @return ?bool
+ */
+ public function loadTemplateFileFromPath(string $templateFile, false|string $extra = false): ?bool {
+ $path = '';
+
foreach ($this->templatePath as $path) {
$this->debug->log('LOAD', $path . $templateFile);
- if (! file_exists($path . $templateFile)) {
+ if (!file_exists($path . $templateFile)) {
$this->debug->log('LOAD', '<b>!EXISTS</b>' . $path . $templateFile);
continue;
}
+ //load from the first matching path only (paths are priority ordered,
+ //same semantics as the import loader); loading from every path would
+ //duplicate content when a theme overrides a base template
$this->template .= file_get_contents($path . $templateFile);
+
+ break;
}
if ($extra) {
$this->template .= $extra;
}
- if (! $this->template) {
+ if (!$this->template) {
$this->debug->log('LOAD', '<b>EMPTY</b>' . $path . $templateFile);
return false;
}
- /*
- if (function_exists('runkit_lint')) {
- if (! runkit_lint($this->template)) {
- die('There is a php synatx error in ' . $templateFile);
- }
- }
- */
+ return true;
}
- private function processPhpcode() {
- /**
- * Placeholders, replace variables, php code etc with placeholders.
- *
- */
+ /**
+ * @return void
+ */
+ private function processPhpcode(): void {
+ // Placeholders, replace variables, php code etc with placeholders.
//$this->template = preg_replace('@\/\/[^\n\r]+?(?:\*\)|[\n\r])@','', $this->template);
- //preg_match_all('/(?<!["\'])\/\*.*?\*\/|\s*(?<!["\'])\/\/[^\n]*/s', $this->template, $comments);
preg_match_all('/(?<!["\'])<\?php(.*?)\?>/s', $this->template, $phpCode);
- //preg_match_all("/([\"'])[^\\\\]*?(\\\\.[^\\\\]*?)*?\\1/s", $str, $matches);
- $phpCode[0] = array_values($phpCode[0]);
+ $patternsPhp = [];
+ $placeholdersPhp = [];
- for ($i=0; $i < count($phpCode[1]); $i++) {
- $patternsPhp[] = '/' . preg_quote($phpCode[0][$i], '/') . '/';
- $placeholdersPhp[]="replace_php_code-$i";
+ for ($i = 0; $i < count($phpCode[1]); $i++) {
+ $patternsPhp[] = '/' . preg_quote($phpCode[0][$i], '/') . '/';
+ $placeholdersPhp[] = "replace_php_code-{$i}";
// double backslashes must be escaped if we want to use them in the replacement argument
$phpCode[0][$i] = str_replace('\\\\', '\\\\\\\\', $phpCode[1][$i]);
}
- if (isset($placeholdersPhp)) {
+ if ($placeholdersPhp) {
$this->template = preg_replace($patternsPhp, $placeholdersPhp, $this->template);
}
$this->phpCode = $phpCode[0];
}
- private function processFroms() {
- /*
- *Froms - from(index.html|#element)
- */
+ /**
+ * @return void
+ */
+ private function processFroms(): void {
+ // Froms - from(index.html|#element)
preg_match_all('/from\(([^\|]+)\|(.+)\)/', $this->template, $froms);
+ $patternsFroms = [];
+ $placeholdersFroms = [];
- $froms[0] = array_values($froms[0]);
-
- for ($i=0; $i < count($froms[1]); $i++) {
- $patternsFroms[] = '/' . preg_quote($froms[0][$i], '/') . '/';
- // $patterns[] = preg_quote($matches[0][$i], '/');
- $placeholdersFroms[]="replace_from-$i\n";
+ for ($i = 0; $i < count($froms[1]); $i++) {
+ $patternsFroms[] = '/' . preg_quote($froms[0][$i], '/') . '/';
+ $placeholdersFroms[] = "replace_from-{$i}\n";
// double backslashes must be escaped if we want to use them in the replacement argument
$froms[0][$i] = str_replace('\\\\', '\\\\\\\\', $froms[1][$i]);
}
@@ -292,24 +412,26 @@ class Vtpl {
$this->froms = $froms;
}
- private function processStrings() {
- /* strings */
+ /**
+ * @return void
+ */
+ private function processStrings(): void {
+ // strings
//single quote
- preg_match_all("/=\s+'[^'\\\r\n]*(?:\\.[^'\\\r\n]*)*'(?!\])/s", $this->template, $stringsSingle);
- //preg_match_all("/=\s*'[^']+'\s*$/s", $this->template, $stringsSingle);
+ preg_match_all("/=\\s+'[^'\\\r\n]*(?:\\.[^'\\\r\n]*)*'(?!\\])/s", $this->template, $stringsSingle);
//doube quote
- preg_match_all('/=\s+"[^"\\\r\n]*(?:\\.[^"\\\r\n]*)*"(?!\])/s', $this->template, $strings);
- //preg_match_all('/=\s*"[^"]+"\s*$/s', $this->template, $strings);
-
- $strings = array_values(array_unique($strings[0]));
- $stringsSingle = array_values(array_unique($stringsSingle[0]));
- $strings = array_merge((array)$strings, (array)$stringsSingle);
-
- for ($i=0; $i < count($strings); $i++) {
- $string = trim($strings[$i], '= ');
- $patternsStrings[] = '/' . preg_quote($string, '/') . '/';
- // $patterns[] = preg_quote($matches[0][$i], '/');
- $placeholdersStrings[]="replace_string-$i";
+ preg_match_all('/=\s+"[^"\\\r\n]*(?:\.[^"\\\r\n]*)*"(?!\])/s', $this->template, $strings);
+
+ $strings = array_values(array_unique($strings[0]));
+ $stringsSingle = array_values(array_unique($stringsSingle[0]));
+ $strings = array_merge((array)$strings, (array)$stringsSingle);
+ $patternsStrings = [];
+ $placeholdersStrings = [];
+
+ for ($i = 0; $i < count($strings); $i++) {
+ $string = trim($strings[$i], '= ');
+ $patternsStrings[] = '/' . preg_quote($string, '/') . '/';
+ $placeholdersStrings[] = "replace_string-{$i}";
// double backslashes must be escaped if we want to use them in the replacement argument
$strings[$i] = str_replace('\\\\', '\\\\\\\\', $string);
}
@@ -321,63 +443,74 @@ class Vtpl {
$this->strings = $strings;
}
- private function processVariables() {
- //preg_match_all('/(?<!["\'\[])(\\$[a-zA-Z0-9->\[\]\'"_\(\)\$\:]*)/s', $this->template, $variables);
+ /**
+ * @return void
+ */
+ private function processVariables(): void {
preg_match_all('/(?<!["\'\[])(\$.+)/', $this->template, $variables);
- //$variables[0] = array_values($variables[0]);
$patternsVariables = [];
$placeholdersVariables = [];
$variables[1] = array_unique($variables[1]);
- //usort($variables[1],fn($a,$b) => strlen($b) <=> strlen($a));
- usort($variables[1],function ($a,$b) {return strlen($b) <=> strlen($a); });
+ usort($variables[1], fn ($a, $b) => strlen($b) <=> strlen($a));
- for ($i=0; $i < count($variables[1]); $i++) {
- $patternsVariables[] = '/' . preg_quote($variables[1][$i], '/') . '/';
- $placeholdersVariables[]="replace_variable-$i";
+ for ($i = 0; $i < count($variables[1]); $i++) {
+ $patternsVariables[] = '/' . preg_quote($variables[1][$i], '/') . '/';
+ $placeholdersVariables[] = "replace_variable-{$i}";
// double backslashes must be escaped if we want to use them in the replacement argument
- //$variables[0][$i] = str_replace('\\\\', '\\\\\\\\', $variables[1][$i]);
}
- //if ($variables[1]) {
$this->template = preg_replace($patternsVariables, $placeholdersVariables, $this->template);
- //}
$this->variables = $variables[1];
}
- private function processTemplateFile() {
- /*
- * imports - import(common.tpl)
- *
- * */
- if (! $this->template || ! $this->xpath) {
+ /**
+ * Process the raw template commands: expand imports, extract php/variable/
+ * from/string placeholders into lookup tables, then parse selector lines.
+ */
+ private function processTemplateFile(): void {
+ if (!$this->template) {
return;
}
+ $this->expandImports();
+ $this->processPhpcode();
+ $this->processVariables();
+ $this->processFroms();
+ $this->processStrings();
+
+ $this->parseSelectorLines();
+ }
+
+ /**
+ * Expand import(file.tpl) directives by inlining the referenced files,
+ * repeating until no imports remain (imports may nest).
+ */
+ private function expandImports(): void {
$foundImports = true;
//expand imports
while ($foundImports) {
- $foundImports = preg_match_all("/import\(([^\&%'`\@{}~!#\(\)&\^\+,=\[\]]*?\.$this->extension)\,?(.+)?\);?/", $this->template, $imports);
+ $foundImports = preg_match_all("/import\\(([^\\&%'`\\@{}~!#\\(\\)&\\^\\+,=\\[\\]]*?\\.{$this->extension})\\,?(.+)?\\);?/", $this->template, $imports);
- for ($i=0; $i < count($imports[0]); $i++) {
+ for ($i = 0; $i < count($imports[0]); $i++) {
$content = '';
$importContent = '';
foreach ($this->templatePath as $path) {
$import = $imports[1][$i];
- if (strncmp($import,'/plugins/', 9) === 0) {
+ if (str_starts_with($import, '/plugins/')) {
$importFile = DIR_PLUGINS . substr($import, 9);
} else {
- if ($import[0] == '/') {
+ if ($import[0] === '/') {
$importFile = DIR_ROOT . $import;
} else {
$importFile = $path . $import;
}
}
- if (strpos($importFile, '*') !== false) {
+ if (str_contains($importFile, '*')) {
$files = glob($importFile);
} else {
$files = [$importFile];
@@ -386,47 +519,45 @@ class Vtpl {
$found = false;
foreach ($files as $importFile) {
- if (file_exists($importFile)) {
- $parameter = trim($imports[2][$i]);
- $this->debug->log('LOAD', $importFile);
+ if (file_exists($importFile)) {
+ $parameter = trim($imports[2][$i]);
+ $this->debug->log('LOAD', $importFile);
- if (! empty($parameter)) {
- //if php array then parameter is a template variables list
- if ($parameter[0] == '{'/* || $parameter[0] == '['*/) {
- $importContent = file_get_contents($importFile);
+ if (!empty($parameter)) {
+ //if php array then parameter is a template variables list
+ if ($parameter[0] === '{'/* || $parameter[0] == '['*/) {
+ $importContent = file_get_contents($importFile);
- //process template
- $templateParams = json_decode($parameter, true);
+ //process template
+ $templateParams = json_decode($parameter, true);
- foreach ($templateParams as $name => $value) {
- $importContent = str_replace('{{' . $name . '}}' , $value, $importContent);
- }
- } else {
- //parameter is a css selector to check if the element exists and conditionally include template
- $elements = $this->xpath->query($this->cssToXpath($parameter));
- //remove true and process froms earlier
- if (true || $elements && $elements->length) {
- //found, load template below
- $importContent = file_get_contents($importFile);
+ foreach ($templateParams as $name => $value) {
+ $importContent = str_replace('{{' . $name . '}}', $value, $importContent);
+ }
} else {
- //not found, replace import with nothing
- $this->template = str_replace($imports[0][$i], '' , $this->template);
+ //parameter is a css selector to check if the element exists and conditionally include template
+ $elements = $this->query($parameter);
+ if ($elements && $elements->length) {
+ //found, load template below
+ $importContent = file_get_contents($importFile);
+ } else {
+ //not found, replace import with nothing
+ $this->template = str_replace($imports[0][$i], '', $this->template);
- continue;
+ continue;
+ }
}
+ } else {
+ $importContent = file_get_contents($importFile);
}
- } else {
- $importContent = file_get_contents($importFile);
- }
- //remove comments
- $importContent = preg_replace("/(?<![\"'])\/\*.*?\*\/|\s*(?<![\"'])\/\/[^\n]*/s", '', $importContent);
- $content .= $importContent . "\n";
+ //remove comments
+ $importContent = preg_replace("/(?<![\"'])\\/\\*.*?\\*\\/|\\s*(?<![\"'])\\/\\/[^\n]*/s", '', $importContent);
+ $content .= $importContent . "\n";
$found = true;
- } else {
- $this->debug->log('VTPL_IMPORT_FILE_NOT_EXIST', $importFile);
- //error_log($imports[0][$i] . " $importFile does not exists");
+ } else {
+ $this->debug->log('VTPL_IMPORT_FILE_NOT_EXIST', $importFile);
}
}
@@ -438,18 +569,19 @@ class Vtpl {
$this->template = str_replace($imports[0][$i], $content, $this->template);
}
}
+ }
- $this->processPhpcode();
- $this->processVariables();
- $this->processFroms();
- $this->processStrings();
-
+ /**
+ * Normalize template whitespace/comments and split the remaining command
+ * text into selector lines ("selector = value" pairs or bare selectors).
+ */
+ private function parseSelectorLines(): void {
//remove comments
- $this->template = preg_replace("/(?<![\"'])\/\*.*?\*\/|\s*(?<![\"'])\/\/[^\n]*/s", '', $this->template);
- $this->template = preg_replace('/\n+/',"\n", $this->template);
- $this->template = preg_replace('/(?<=\=)\s*\n/','', $this->template);
+ $this->template = preg_replace("/(?<![\"'])\\/\\*.*?\\*\\/|\\s*(?<![\"'])\\/\\/[^\n]*/s", '', $this->template);
+ $this->template = preg_replace('/\n+/', "\n", $this->template);
+ $this->template = preg_replace('/(?<=\=)\s*\n/', '', $this->template);
- $this->template = str_replace("\n\n","\n",trim($this->template));
+ $this->template = str_replace("\n\n", "\n", trim($this->template));
$lines = explode("\n", $this->template);
foreach ($lines as $line) {
@@ -471,11 +603,23 @@ class Vtpl {
/**
* Convert a CSS-selector into an xPath-query.
*
- * @return string
- * @param string $selector The CSS-selector
+ * @param string $selector The CSS-selector
+ *
+ * @return string
*/
- function cssToXpath($selector) {
- $selector = (string) $selector;
+ public function cssToXpath(string $selector): string {
+ $selector = (string)$selector;
+
+ //protect quoted literals so later rules (brackets/class/id) can't mangle
+ //attribute values like name="settings[frontend]" — placeholders carry no
+ //special css characters and are restored after the rule table runs
+ $quotedLiterals = [];
+ $selector = preg_replace_callback('/"[^"]*"/', function(array $m) use (&$quotedLiterals): string {
+ $key = '__QT' . count($quotedLiterals) . '__';
+ $quotedLiterals[$key] = substr($m[0], 1, -1);
+
+ return '"' . $key . '"';
+ }, $selector);
//convert , to | union operator to allow multiple queries
$selector = str_replace(',', '|', $selector);
@@ -502,15 +646,25 @@ class Vtpl {
// E:nth(2): Matches the nth element from the set
'/([a-z#\.]\w*):nth\((\d+)\)/', // \1[\2]
+ // E[foo=warning]: Matches any E element whose unquoted "foo" attribute value equals "warning"
+ // bracketed value first (name=settings[enabled] — invalid css but common in templates),
+ // so the plain unquoted rule can't stop at the inner ']'
+ '/([a-z]\w*|\*)\[([a-z][\w\-_]*)\=([\w\-\.]+)\[([\w\-_]+)\]\]/', // \1[ contains( concat( " ", @\2, " " ), concat( " ", "\3[\4]", " " ) ) ]
+ '/\[([a-z][\w\-_]*)\=([\w\-\.]+)\[([\w\-_]+)\]\]/', // *[ contains( concat( " ", @\1, " " ), concat( " ", "\2[\3]", " " ) ) ]
+ '/([a-z]\w*|\*)\[([a-z][\w\-_]*)\=([^\s\]"]+)\]/', // \1[ contains( concat( " ", @\2, " " ), concat( " ", "\3", " " ) ) ]
+
// E[foo="warning"]: Matches any E element whose "foo" attribute value is exactly equal to "warning"
'/([a-z]\w*)\[([a-z][\w\-_]*)\="([^"]*)"\]/', // \1[ contains( concat( " ", @\2, " " ), concat( " ", "\3", " " ) ) ]
// E[foo]: Matches any E element with the "foo" attribute set (whatever the value)
- '/([a-z]\w*)\[([a-z][\w_\-]*)\]/', // \1 [ @\2 ]'
+ '/(?<![\w"])([a-z]\w*)\[([a-z][\w_\-]*)\]/', // \1 [ @\2 ]'
// E[!foo]: Matches any E element without the "foo" attribute set
'/([a-z]\w*)\[!([a-z][\w\-_]*)\]/', // \1 [ not(@\2) ]
+ // [foo=warning]: Matches any element whose unquoted "foo" attribute value equals "warning"
+ '/\[([a-z][\w\-_]*)\=([^\s\]"]+)\]/', // *[ contains( concat( " ", @\1, " " ), concat( " ", "\2", " " ) ) ]
+
// [foo="warning"]: Matches any element whose "foo" attribute value is exactly equal to "warning"
'/\[([a-z][\w\-_]*)\=\"(.*)\"\]/', // *[@\1 = "\2"]
@@ -533,7 +687,7 @@ class Vtpl {
'/(?<=\])(?<! )\[([a-z][\w_\-]*)\]/', // [ @\1 ]
// [foo]: Matches any element with the "foo" attribute set (whatever the value)
- '/\[([a-z][\w_\-]*)\]/', // *[ @\1 ]
+ '/(?<![\w"])\[([a-z][\w_\-]*)\]/', // *[ @\1 ]
// [!foo]: Matches any element without the "foo" attribute set (whatever the value)
'/\[!([a-z][\w_\-]*)\]/', // *[ not(@\1) ]
@@ -567,6 +721,12 @@ class Vtpl {
// #myid: Matches any E element with id-attribute equal to "myid"
'/\#([a-z][\w\-_]*)/', // *[ @id = "\1" ]
+
+ // negation pseudo selector
+ '/\:not\(([^\)]+?)\)/', // :not(\1)
+
+ // empty pseudo selector
+ '/\:empty/', //:empty
];
$xpathQuery = [
@@ -577,9 +737,13 @@ class Vtpl {
'*[\2]/self::\1', //element:nth-child(2)
'\1[1]', //element:first
'\1[\2]', //element:nth(2)
+ '\1[ contains( concat( " ", @\2, " " ), concat( " ", "\3[\4]", " " ) ) ]', //element[attribute=bwarningacketed unquoted]
+ '*[ contains( concat( " ", @\1, " " ), concat( " ", "\2[\3]", " " ) ) ]', //[attribute=bracketed unquoted]
+ '\1[ contains( concat( " ", @\2, " " ), concat( " ", "\3", " " ) ) ]', //element[attribute=string unquoted]
'\1[ contains( concat( " ", @\2, " " ), concat( " ", "\3", " " ) ) ]', //element[attribute="string"]
'\1 [ @\2 ]', //element[attribute]
'\1 [ not(@\2) ]', //element[!attribute]
+ '*[ contains( concat( " ", @\1, " " ), concat( " ", "\2", " " ) ) ]', //[foo=warning unquoted]
'*[@\1 = "\2"]', //[foo="warning"]
'\1[ contains( @\2, "\3" ) ]', //element[foo*="warning"]
'[contains(@\1,"\2")]', //[foo*="warning"]
@@ -599,24 +763,52 @@ class Vtpl {
'*[ contains( concat( " ", @class, " " ), concat( " ", "\1", " " ) ) ]', //element[class~="string"]
'\1[ @id = "\2" ]', //element#id
'*[ @id = "\1" ]', //#id
+ //'(\1 except \2)', //negation pseudo selector
+ '[not(self::\1)]', //negation pseudo selector
+ '[not(text())]', //empty pseudo selector
];
- $result = (string) '//' . preg_replace($cssSelector, $xpathQuery, $selector);
+ $result = (string)'//' . preg_replace($cssSelector, $xpathQuery, $selector);
+ $result = strtr($result, $quotedLiterals);
$this->debug->log('CSS_XPATH_TRANSFORM', $result);
return $result;
}
- function query($selector) {
- $result = $this->xpath->query($this->cssToXpath($selector));
+ /**
+ * @param string $selector
+ *
+ * @return Dom\NodeList<\Dom\Node>|DOMNodeList<\DOMNode>|false
+ */
+ public function query(string $selector): Dom\NodeList|DOMNodeList|false {
+ if ($this->legacy) {
+ $xpath = $this->cssToXpath($selector);
+ $result = $this->xpath->query($xpath);
+ } else {
+ //missing css support for
+ //[data-v-menu-item-*] => [attribute-name^="data-v-menu-item-"]
+ $result = $this->document->querySelectorAll($selector);
+ }
return $result;
}
- private function processElements($modifier, $elements, $val) {
+ /**
+ * @param string $modifier
+ * @param Dom\NodeList<\Dom\Node>|DOMNodeList<\DOMNode>|false|null $elements
+ * @param array<array-key, mixed>|string $val
+ *
+ * @return void
+ */
+ private function processElements(string $modifier, null|Dom\NodeList|DOMNodeList|false $elements, array|string $val): void {
+ //no match (or invalid xpath expression) - nothing to modify
+ if (!$elements || !$elements->length) {
+ return;
+ }
+
switch ($modifier) {
case 'deleteAllButFirstChild':
- $this->deleteAllButFirstChild($elements, $val ?? false);
+ $this->deleteAllButFirstChild($elements);
break;
@@ -630,6 +822,7 @@ class Vtpl {
break;
+ case 'text':
case 'innerText':
$this->innerText($elements, $val);
@@ -700,32 +893,43 @@ class Vtpl {
}
}
- private function processTemplate() {
- if (isset($this->selectors) && isset($this->document) && isset($this->xpath)) {
- //check for multiple selectors
-
- $count = count($this->selectors);
- for ($i = 0; $i < $count - 1; $i++) {
- $data = $this->selectors[$i];
- //$data[0] = selector
- if (strpos($data[0], ',') !== false) {
- $selectorComponents = explode('|', $data[0]);
- $selector = $selectorComponents[0];
- $modifier = (isset($selectorComponents[1])) ? trim($selectorComponents[1]) : '';
-
- $selectors = explode(',', $selector);
- $newSelectors = [];
- foreach ($selectors as $selector) {
- $newSelectors[] = [trim($selector) . ($modifier ? '|' . $modifier : ''), $data[1] ?? ''];
- }
-
- $newCount = count($newSelectors) - 1;
+ /**
+ * @return void
+ */
+ /**
+ * Expands comma-separated selector lines ("a, b|mod = value") into one
+ * selector entry per selector, preserving the modifier and value.
+ */
+ private function expandCommaSelectors(): void {
+ $count = count($this->selectors);
+ for ($i = 0; $i < $count; $i++) {
+ $data = $this->selectors[$i];
+ //$data[0] = selector
+ if (str_contains($data[0], ',')) {
+ $selectorComponents = explode('|', $data[0]);
+ $selector = $selectorComponents[0];
+ $modifier = (isset($selectorComponents[1])) ? trim($selectorComponents[1]) : '';
- array_splice($this->selectors, $i, 1, $newSelectors);
- $count += $newCount;
- $i += $newCount;
+ $selectors = explode(',', $selector);
+ $newSelectors = [];
+ foreach ($selectors as $selector) {
+ $newSelectors[] = [trim($selector) . ($modifier ? '|' . $modifier : ''), $data[1] ?? ''];
}
+
+ $newCount = count($newSelectors) - 1;
+
+ array_splice($this->selectors, $i, 1, $newSelectors);
+ $count += $newCount;
+ $i += $newCount;
}
+ }
+ }
+
+ private function processTemplate(): void {
+ if (isset($this->selectors)) {
+ //check for multiple selectors
+
+ $this->expandCommaSelectors();
foreach ($this->selectors as &$data) {
$selector = $data[0];
@@ -733,70 +937,74 @@ class Vtpl {
$selector = $selectorComponents[0];
$modifier = (isset($selectorComponents[1])) ? trim($selectorComponents[1]) : '';
$value = (isset($data[1])) ? $data[1] : '';
- $this->external_elements = false;
+ $this->externalElements = false;
//enable disable debugging
- if (! $selector) {
+ if (!$selector) {
continue;
}
$isConstant = false;
- if (strpos($selector, '@@_CONSTANT_') !== false) {
+ if (str_contains($selector, '@@_CONSTANT_')) {
$isConstant = true;
}
$prefix = &$this->prefix;
$isPrefix = false;
- //get all set prefix and save values
- //@my-prefix = #selector .class[attribute]
- $selector = preg_replace_callback('/^@([a-zA-Z][a-zA-Z0-9_-]+)(?![a-zA-Z0-9_-])\s+=\s+(.+)$/',
- function ($matches) use (&$prefix, &$isPrefix) {
- if (isset($matches[1]) && isset($matches[2])) {
- $name = $matches[1];
- $value = $matches[2];
+ /**
+ get all set prefix and save values
+ @my-prefix = #selector .class[attribute]
+ */
+ $selector = preg_replace_callback(
+ '/^@([a-zA-Z][a-zA-Z0-9_-]+)(?![a-zA-Z0-9_-])\s+=\s+(.+)$/',
+ function($matches) use (&$prefix, &$isPrefix) {
+ $name = $matches[1];
+ $value = $matches[2];
- $prefix[$name] = $value;
- $isPrefix = true;
- }
+ $prefix[$name] = $value;
+ $isPrefix = true;
return trim($matches[0]);
- }, $selector);
+ },
+ $selector
+ );
//if the line is only for set prefix then skip further processing
if ($isPrefix) {
continue;
}
//replace all prefix with actual values
- $selector = preg_replace_callback('/@([a-zA-Z][a-zA-Z0-9_-]+)(?![a-zA-Z0-9_-])/',
- function ($matches) use (&$prefix) {
- if (isset($matches[1])) {
- $name = $matches[1];
+ $selector = preg_replace_callback(
+ '/@([a-zA-Z][a-zA-Z0-9_-]+)(?![a-zA-Z0-9_-])/',
+ function($matches) use (&$prefix) {
+ $name = $matches[1];
- if (isset($prefix[$name])) {
- return $prefix[$name];
- }
+ if (isset($prefix[$name])) {
+ return $prefix[$name];
}
return trim($matches[0]);
- }, $selector);
+ },
+ $selector
+ );
$this->debug->log('SELECTOR', $selector);
$val = $value;
- if ($selector == 'debug') {
- $this->debug->enable(($value == 'true') ? true : false);
+ if ($selector === 'debug') {
+ $this->debug->enable(($value === 'true') ? true : false);
} else {
$valueElements = explode('-', $value);
switch ($valueElements[0]) {
case 'replace_string':
$val = $value;
- $index = (int) $valueElements[1];
+ $index = (int)$valueElements[1];
if (isset($this->strings[$index])) {
- $val = trim($this->strings[$index],'"\'');
+ $val = trim($this->strings[$index], '"\'');
$this->debug->log('SELECTOR_STRING', $this->strings[$index]);
} else {
$this->debug->log('SELECTOR_STRING', "$index not found for $value");
@@ -805,24 +1013,26 @@ class Vtpl {
break;
case 'replace_php_code':
- $phpCode = $this->phpCode[(int) $valueElements[1]] ?? '';
+ $phpCode = $this->phpCode[(int)$valueElements[1]] ?? '';
/*
if (VTPL_PHP_MINIFY === true) {
$phpCode = $this->minifyPhp($phpCode);
}
*/
- if ($modifier && ! in_array($modifier, $this->modifiers)) {
+ if ($modifier && !in_array($modifier, $this->modifiers)) {
$val = '<_script language="php"><![CDATA[' . $this->minifyPhp($phpCode) . ']]></_script>';
} else {
- if ($modifier == 'if_exists' || $modifier == 'hide') {
- $val = "($phpCode)";
+ if ($modifier === 'if_exists' || $modifier === 'hide') {
+ //these modifiers take a boolean expression — strip a
+ //statement wrapper (echo/print + trailing ;) so ifExists()
+ //never wraps statements in isset()
+ $expr = trim($phpCode);
+ $expr = preg_replace('/^\s*(?:echo|print)\s+/s', '', $expr) ?? $expr;
+ $expr = preg_replace('/\s*;\s*$/s', '', $expr) ?? $expr;
+ $val = str_contains($expr, ';') ? "({$phpCode})" : "({$expr})";
} else {
- if ($isConstant || $modifier == 'addClass') {
- $val = '<_script language="php"><![CDATA[' . $this->minifyPhp($phpCode) . ']]></_script>';
- } else {
- $val = '<_script language="php"><![CDATA[' . $this->minifyPhp($phpCode) . ']]></_script>';
- }
+ $val = VTPL_PHP_CDATA_OPEN . $this->minifyPhp($phpCode) . VTPL_PHP_CDATA_CLOSE;
}
}
$this->debug->log('SELECTOR_PHP', $phpCode);
@@ -832,19 +1042,14 @@ class Vtpl {
case 'replace_variable':
$variable = $this->variables[(int) $valueElements[1]] ?? '';
if ($modifier) {
- if ($modifier == 'if_exists' || $modifier == 'hide') {
+ if ($modifier === 'if_exists' || $modifier === 'hide') {
$val = $variable;
- } else {
- if (! in_array($modifier, $this->modifiers) || $modifier == 'addClass') {
- $val = '<_script language="php"><![CDATA[if (isset(' . $variable . ')) echo htmlspecialchars(' . $variable . ');]]></_script>';
- }
+ } elseif (! in_array($modifier, $this->modifiers) || $modifier === 'addClass') {
+ $val = VTPL_PHP_CDATA_OPEN . 'if (isset(' . $variable . ')) echo htmlspecialchars(' . $variable . ');' . VTPL_PHP_CDATA_CLOSE;
}
} else {
- if ($isConstant) {
- $val = '<_script language="php"><![CDATA[if (isset(' . $variable . ')) echo ' . $variable . ';]]></_script>';
- } else {
- $val = '<_script language="php"><![CDATA[if (isset(' . $variable . ')) echo htmlspecialchars(' . $variable . ');]]></_script>';
- }
+ $echo = $isConstant ? 'echo ' . $variable : 'echo htmlspecialchars(' . $variable . ')';
+ $val = VTPL_PHP_CDATA_OPEN . 'if (isset(' . $variable . ')) ' . $echo . ';' . VTPL_PHP_CDATA_CLOSE;
}
$this->debug->log('SELECTOR_VARIABLE', $variable);
@@ -852,21 +1057,9 @@ class Vtpl {
break;
case 'replace_from':
- $from = $this->froms[0][(int) $valueElements[1]] ?? ''; //external html file
- /*
- $fromSelector = substr($this->froms[2][(int) $valueElements[1]],1);
- //load specified selector if available otherwise load html with the same selector
- if (empty($fromSelector))
- {
- //override default selector with the provided one
- $fromSelector = $selector;
-
- }*/
- //get html
- //if ($from != '@_SELF_@')
- $this->external_elements = true;
+ $this->externalElements = true;
$val = $valueElements;
- //$val = $this->loadFromExternalHtml($from, $fromSelector);
+
break;
}
@@ -876,14 +1069,12 @@ class Vtpl {
continue;
}
- //echo $selector . ' --- ' . $this->cssToXpath($selector) . "<br/>\n";
- $xpathSelector = $this->cssToXpath($selector);
- $elements = $this->xpath->query($xpathSelector);
+ $elements = $this->query($selector);
- if (! $elements) {
+ if (!$elements) {
$this->debug->log(0, ' [empty]');
} else {
- if ($elements && $elements->length == 0) {
+ if ($elements->length === 0) {
$this->debug->log(0, ' [0 elements]');
} else {
$this->debug->log(0, " [{$elements->length} elements]");
@@ -898,6 +1089,31 @@ class Vtpl {
}
}
+ /**
+ * Replace $$N placeholders in a filter command string with option values.
+ * Non-zero indices are quoted as string literals.
+ *
+ * @param string $command
+ * @param array<array-key, mixed> $options
+ *
+ * @return string
+ */
+ private function replaceFilterVars(string $command, array &$options): string {
+ return preg_replace_callback(
+ '@\$\$(\d+)@',
+ function($matches) use (&$options) {
+ $index = (int)$matches[1];
+
+ if ($index > 0) {
+ $options[$index] = '\'' . trim($options[$index], '\'') . '\'';
+ }
+
+ return $options[$index];
+ },
+ $command
+ );
+ }
+
/*
Process data-filter-* attributes defined in filters array.
Process attributes with json and transforms them to php arrays ex: data-my-data='{var:"value"}'
@@ -905,18 +1121,26 @@ class Vtpl {
Process json path, for a node with data-v-myjson='{var:{subvar1:val1, subvar2:val2}}' @@myjson.var.subvar1@@ will return val1
*/
- private function processAttributeFilters($value, &$node) {
- //filters
- //search for filters and their options
- //@filter_([^ :$]+):?(\'[^\']+\'|[^ $]+)?@ old
+ /**
+ * @param string $value
+ * @param Dom\HTMLElement|DOMNode &$node
+ *
+ * @return string
+ */
+ private function processAttributeFilters(string $value, Dom\HTMLElement|DOMNode &$node): string {
+ /*
+ filters
+ search for filters and their options
+ @filter_([^ :$]+):?(\'[^\']+\'|[^ $]+)?@ old
+ */
$filters = [];
$length = $node->attributes->length;
- for ($i = 0; $i < $length; ++$i) {
+ for ($i = 0; $i < $length; $i++) {
if ($item = $node->attributes->item($i)) {
$name = $item->name;
- if (strpos($name, 'data-filter') !== false) {
+ if (str_contains($name, 'data-filter')) {
$name = str_replace('data-filter-', '', $name);
$filters[$name] = $item->value;
//$node->removeAttribute($item->name);
@@ -931,7 +1155,7 @@ class Vtpl {
foreach ($filters as $name => $options) {
if ($options) {
//string is json
- if ($options[0] == '{'/* || $options[0] == '['*/) {
+ if ($options[0] === '{'/* || $options[0] == '['*/) {
$options = json_decode($options, false);
} else {
$options = [$options];
@@ -952,8 +1176,12 @@ class Vtpl {
$commands = [1 => $commands];
}
+ if (!$commands) {
+ continue;
+ }
+
foreach ($commands as &$command) {
- $commandVariableCount = preg_match_all('@\$\$[1-9]+@' , $command);
+ $commandVariableCount = preg_match_all('@\$\$[1-9]+@', $command);
//if different parameter number then don't add filter to filter chain
if ($commandVariableCount != count($options)) {
@@ -963,53 +1191,21 @@ class Vtpl {
}
//run php functions if any
- $command = preg_replace_callback('/@@__VTPL_([^_]+)__@@/',
- function ($matches) {
- return eval('return ' . $matches[1] . ';');
- }, $command);
+ $command = preg_replace_callback(
+ '/@@__VTPL_([^_]+)__@@/',
+ fn ($matches) => eval('return ' . $matches[1] . ';'),
+ $command
+ );
}
- if ($type == 'class') {
- //replace variables with their values
- $command = preg_replace_callback('@\$\$(\d+)@',
- function ($matches) use ($options) {
- if ($matches[1] > 0) {
- $options[$matches[1]] = '\'' . trim($options[$matches[1]], '\'') . '\'';
- }
-
- return $options[$matches[1]];
- }, $command);
-
+ if ($type === 'class') {
+ $command = $this->replaceFilterVars($command, $options);
$this->addNodeClass($node, trim($commands[1], '\''), false);
} else {
- if ($type == 'tag') {
- //replace variables with their values
- $command = preg_replace_callback('@\$\$(\d+)@',
- function ($matches) use ($options) {
- if ($matches[1] > 0) {
- $options[$matches[1]] = '\'' . trim($options[$matches[1]], '\'') . '\'';
- }
-
- return $options[$matches[1]];
- }, $command);
-
- $openTag = preg_replace_callback('@\$\$(\d+)@',
- function ($matches) use ($options) {
- if ($matches[1] > 0) {
- $options[$matches[1]] = '\'' . trim($options[$matches[1]], '\'') . '\'';
- }
-
- return $options[$matches[1]];
- }, $commands[1]);
-
- $closeTag = preg_replace_callback('@\$\$(\d+)@',
- function ($matches) use ($options) {
- if ($matches[1] > 0) {
- $options[$matches[1]] = '\'' . trim($options[$matches[1]], '\'') . '\'';
- }
-
- return $options[$matches[1]];
- }, $commands[2]);
+ if ($type === 'tag') {
+ $command = $this->replaceFilterVars($command, $options);
+ $openTag = $this->replaceFilterVars($commands[1], $options);
+ $closeTag = $this->replaceFilterVars($commands[2], $options);
$nodeList = [$node]; //only one node and the methods accepts multiple nodes
$this->tagWrap($nodeList, $openTag, $closeTag);
@@ -1020,18 +1216,11 @@ class Vtpl {
$options[] = $chain;
}
- $chain = preg_replace_callback('@\$\$(\d+)@',
- function ($matches) use ($options) {
- if ($matches[1] > 0) {
- $options[$matches[1]] = '\'' . trim($options[$matches[1]], '\'') . '\'';
- }
-
- return $options[$matches[1]];
- }, $commands[1]);
+ $chain = $this->replaceFilterVars($commands[1], $options);
}
}
} else {
- $this->debug->log('warning','Unknown filter <b>' . $name . '</b> for "' . $name . '"');
+ $this->debug->log('warning', 'Unknown filter <b>' . $name . '</b> for "' . $name . '"');
}
}
@@ -1054,67 +1243,91 @@ class Vtpl {
}
/*
- Replace placeholders in values
- Ex;
+ Replace placeholders in values
+ Ex;
// @@__innerText__@@ will be replaced with the text already present in the tag that has data-v-product-name attribute
- [data-v-product-name] = <?php echo 'Product: @@__innerText__@@';?>
-
- Available placeholders:
+ [data-v-product-name] = <?php echo 'Product: @@__innerText__@@';?>
+
+ Available placeholders:
@@__innerText__@@ - inner html of the node
@@__innerText__@@ - inner text of the node
@@__my-attribute__@@ - value of my-attribute of current node
@@__data-v-plugin-(.+)__@@ - run regex and return first match \1 for example for data-v-plugin-name it will return `name`
@@__my-*:my-(*)__@@ - get attribute name that starts with 'my-' and run the regex after ':' used to extract attribute name from current node
-
+
Process data-filter-* attributes defined in filters array.
Process attributes with json and transforms them to php arrays ex: data-my-data='{var:"value"}'
Process macro definitions like @@macro Mymacro('var1', 'var2') Mymacro must be a function defined with name vtplMymacro and must accept two variables like in definition
Process json path, for a node with data-v-myjson='{var:{subvar1:val1, subvar2:val2}}' @@myjson.var.subvar1@@ will return val1
*/
- private function processAttributeConstants($value, $node) {
- if (! $node) {
- return $value;
+
+ /**
+ * Expand a JSON-looking value ({...}) to PHP array syntax via var_export.
+ *
+ * Shared by the @@__innerText__@@, @@__innerHTML__@@ and attribute
+ * placeholder expansions in processAttributeConstants().
+ *
+ * @param string|null $value
+ *
+ * @return string|null
+ */
+ private function expandJsonValue(?string $value): ?string {
+ if (isset($value[0]) && $value[0] === '{') {
+ $value = var_export(json_decode($value, true), true);
}
- $value = preg_replace_callback('/@@__innerText__@@/',
- function ($matches) use ($node) {
+ return $value;
+ }
+
+ /**
+ * @param string $value
+ * @param Dom\HTMLElement|DOMNode $node
+ *
+ * @return string
+ */
+ private function processAttributeConstants(string $value, Dom\HTMLElement|DOMNode $node): string {
+ $value = preg_replace_callback(
+ '/@@__innerText__@@/',
+ function($matches) use ($node) {
$value = $this->innerText([$node]);
- if (isset($value[0]) && ($value[0] == '{' /*|| $value[0] == '['*/)) {
- $value = json_decode($value, 1);
- $value = var_export($value, 1);
- }
+ $value = $this->expandJsonValue($value);
$this->debug->log('VTPL_ATTRIBUTE', '<b>VALUE </b>' . $value);
return trim($value);
- }, $value);
+ },
+ $value
+ );
- $value = preg_replace_callback('/@@__innerHtml__@@/',
- function ($matches) use ($node) {
- $value = $this->innerHtml([$node]);
+ $value = preg_replace_callback(
+ '/@@__innerHTML__@@/',
+ function($matches) use ($node) {
+ $value = $this->innerHTML([$node]);
- if (isset($value[0]) && ($value[0] == '{'/* || $value[0] == '['*/)) {
- $value = json_decode($value, 1);
- $value = var_export($value, 1);
- }
+ $value = $this->expandJsonValue($value);
$this->debug->log('VTPL_ATTRIBUTE', '<b>VALUE </b>' . $value);
return $value;
- }, $value);
+ },
+ $value
+ );
//attribute value
- $value = preg_replace_callback('/@@__([\.a-zA-Z*_-]+)__@@/',
- function ($matches) use ($node) {
+ $value = preg_replace_callback(
+ '/@@__([\.a-zA-Z*_-]+)__@@/',
+ function($matches) use ($node) {
$attributeName = $matches[1];
- if (strpos($attributeName, '*') !== false) {
+ if (str_contains($attributeName, '*')) {
//wildcard attribute
$attributeName = str_replace('*', '', $attributeName);
+ $value = '';
+
foreach ($node->attributes as $attribute) {
- if (strpos($attribute->name, $attributeName) !== false) {
+ if (str_contains($attribute->name, $attributeName)) {
$value = $attribute->value;
}
}
@@ -1122,24 +1335,21 @@ class Vtpl {
$value = $node->getAttribute($matches[1]);
}
- if (isset($value[0]) && ($value[0] == '{'/* || $value[0] == '['*/)) {
- $value = json_decode($value, 1);
- $value = var_export($value, 1);
- }
+ $value = $this->expandJsonValue($value);
$this->debug->log('VTPL_ATTRIBUTE', '<b>VALUE </b>' . $value);
return $value;
-
- return \Vvveb\System\filter('@[#\@&=?\0-9a-zA-Z_: ;-]+@',$value, 500);
- }, $value);
+ },
+ $value
+ );
//run regex on attribute name @@__data-v-product-*:data-v-product-(*)__@@
- //$value = preg_replace_callback('/@@__\[([\*a-zA-Z_-]+)\]:([a-zA-Z-_\]\[\\\+\(\)\,\+\^:*]+)__@@/',
- $value = preg_replace_callback('/@@__([*a-zA-Z_-]+):([a-zA-Z-_\]\[\\\+\(\)\,\.\+\^:*]+)__@@/',
- function ($matches) use ($node) {
+ $value = preg_replace_callback(
+ '/@@__([*a-zA-Z_-]+):([a-zA-Z-_\]\[\\\+\(\)\,\.\+\^:*]+)__@@/',
+ function($matches) use ($node) {
$attrib = $matches[1];
- $regex = $matches[2];
+ $regex = $matches[2];
$this->debug->log('VTPL_ATTRIBUTE', '<b>ATTRIB NAME</b> ' . $attrib);
$this->debug->log('VTPL_ATTRIBUTE', '<b>REGEX </b> ' . $regex);
$value = $node->getAttribute($attrib);
@@ -1156,11 +1366,14 @@ class Vtpl {
}
return $value;
- }, $value);
+ },
+ $value
+ );
//attribute name ex @@__data-v-plugin-(.+)__@@
- $value = preg_replace_callback('/@@__(.+?)__@@/',
- function ($matches) use ($node) {
+ $value = preg_replace_callback(
+ '/@@__(.+?)__@@/',
+ function($matches) use ($node) {
$value = $node->getAttribute($matches[1]);
$this->debug->log('VTPL_ATTRIBUTE', '<b>ATTRIB NAME</b> ' . $matches[1]);
//expand shorthand expression (*) to regex ([a-zA-Z_0-9-]+)
@@ -1170,16 +1383,16 @@ class Vtpl {
if (preg_match("@$regex@", $name, $_match)) {
//$value = \Vvveb\System\filter('@[0-9a-zA-Z_\-\.\#\/]+@', $_match[1], 500);
$value = $_match[1] ?? null;
- $this->debug->log('VTPL_ATTRIBUTE', '<b>MATCH </b>' . $value);
+ $this->debug->log('VTPL_ATTRIBUTE', '<b>MATCH </b> ' . $value);
} else {
$this->debug->log('VTPL_ATTRIBUTE', '<b>NO MATCH </b>');
}
}
return $value;
-
- return \Vvveb\System\filter('@[#\@&=?\0-9a-zA-Z_: ;-]+@',$value, 500);
- }, $value);
+ },
+ $value
+ );
$json = [];
@@ -1189,26 +1402,29 @@ class Vtpl {
$name = str_replace('data-v-', '', $attr->nodeName);
$val = $attr->nodeValue;
- if ($val && ($val[0] == '{'/* || $val[0] == '['*/)) {
+ if ($val && ($val[0] === '{'/* || $val[0] == '['*/)) {
$json[$name] = json_decode($val, true);
}
}
}
- $value = preg_replace_callback('/@@([\.a-zA-Z_-]+)@@/m',
- function ($matches) use ($node, $json) {
- return $attrib = var_export(\Vvveb\arrayPath($json, $matches[1]), true);
+ $value = preg_replace_callback(
+ '/@@([\.a-zA-Z_-]+)@@/m',
+ function($matches) use ($node, $json) {
+ $attrib = var_export(\Vvveb\arrayPath($json, $matches[1]), true);
$this->debug->log('VTPL_ATTRIBUTE', '<b>JSON NAME</b> ' . $attrib);
- $this->debug->log('VTPL_ATTRIBUTE', '<b>REGEX </b> ' . $regex);
$value = $node->getAttribute($attrib);
- $this->debug->log('VTPL_ATTRIBUTE', '<b>ATTRIB VALUE </b> ' . $value);
+ $this->debug->log('VTPL_ATTRIBUTE', '<b>ATTRIB VALUE</b> ' . $value);
- return $value;
- }, $value);
+ return $attrib;
+ },
+ $value
+ );
//macros, compile time function calls
- $value = preg_replace_callback('/@@macro ([a-z_A-Z]+)\((.+?)\)@@/',
- function ($matches) use (&$node) {
+ $value = preg_replace_callback(
+ '/@@macro ([a-z_A-Z]+)\((.+?)\)@@/',
+ function($matches) use (&$node) {
$function = 'vtpl' . $matches[1];
//$parameters = preg_split('@\'?\s*,\s*\'?@', $matches[2]);
@@ -1221,28 +1437,101 @@ class Vtpl {
foreach ($parameters as $param) {
$params[] = trim($param[1]);
}
- /*$params_exp = var_export($params, true);*/
- return call_user_func_array($function, $params);
+
+ // $params_exp = var_export($params, true);
+ return $function(...$params);
}
return $matches[0];
- }, $value);
+ },
+ $value
+ );
- $value = $this->processAttributeFilters($value, $node);
+ return $this->processAttributeFilters($value, $node);
+ }
- return $value;
+ /**
+ * @param Dom\HTMLElement|DOMNode &$node
+ *
+ * @return void
+ */
+ /**
+ * Detach a node from the document after emptying it.
+ *
+ * Shared by the delete* modifiers; the parent check makes it safe to
+ * call on already-detached nodes.
+ *
+ * @param Dom\HTMLElement|DOMNode &$node
+ *
+ * @return void
+ */
+ private function removeNode(Dom\HTMLElement|DOMNode &$node): void {
+ $this->removeChildren($node);
+
+ if ($node->parentNode) {
+ $node->parentNode->removeChild($node);
+ }
}
- private function removeChildren(&$node) {
+ /**
+ * @param Dom\HTMLElement|DOMNode &$node
+ *
+ * @return void
+ */
+ private function removeChildren(Dom\HTMLElement|DOMNode &$node): void {
while ($node->firstChild) {
- while ($node->firstChild->firstChild) {
- $this->removeChildren($node->firstChild);
- }
$node->removeChild($node->firstChild);
}
}
- private function innerHTML($nodeList, $html = false) {
+ /**
+ * Set a node's value based on its tag type.
+ * - input → value attribute
+ * - iframe/video/audio/source → src attribute
+ * - form → action attribute
+ * - default → innerHTML via document fragment
+ *
+ * @param DOMNode $node
+ * @param string $html
+ *
+ * @return void
+ */
+ private function setNodeValueByType(Dom\HTMLElement|DOMNode $node, string $html): void {
+ switch ($node->nodeName) {
+ case 'input':
+ $this->setAttribute($node, 'value', $html);
+
+ break;
+
+ case 'iframe':
+ case 'video':
+ case 'audio':
+ case 'source':
+ $this->setAttribute($node, 'src', $html);
+
+ break;
+
+ case 'form':
+ $this->setAttribute($node, 'action', $html);
+
+ break;
+
+ default:
+ $this->removeChildren($node);
+ $f = $this->createXmlFragment($this->processAttributeConstants($html, $node));
+ if ($f) {
+ $node->appendChild($f);
+ }
+ }
+ }
+
+ /**
+ * @param array<array-key, mixed>|Dom\NodeList<\Dom\Node>|DOMNodeList<\DOMNode> $nodeList
+ * @param false|string $html
+ *
+ * @return string|null
+ */
+ private function innerHTML(array|Dom\NodeList|DOMNodeList $nodeList, false|string $html = false): ?string {
if ($nodeList) {
foreach ($nodeList as $node) {
if ($html === false) {
@@ -1252,18 +1541,13 @@ class Vtpl {
$doc->appendChild($doc->importNode($child, true));
}
- if ($this->documentType == 'html') {
- return $doc->saveHTML();
- } else {
- return Vvveb\xmlStripVersionDeclr($doc->saveXML());
- }
+ return $this->saveDocument($doc);
} else {
- if ($html == '') {
+ if ($html === '') {
continue;
}
- //if ($node->nodeName !== 'title') $html .= '<_script language="php"><![CDATA[/*__VTPL_MAP:' . $node->getLineNo() . '*/]]></_script>';
- if ($this->external_elements) {
+ if ($this->externalElements) {
$result = $this->loadFromExternalHtml($html, $node);
$this->removeChildren($node);
@@ -1272,370 +1556,353 @@ class Vtpl {
$node->appendChild($importedNode);
}
} else {
- switch ($node->nodeName) {
- case 'input':
- /* case 'option':*/
- $this->setAttribute($node, 'value', $html);
-
- break;
- //case 'img':
- case 'iframe':
- //case 'script':
- case 'video':
- case 'audio':
- case 'source':
- $this->setAttribute($node, 'src', $html);
-
- break;
- /*
- //case 'a':
- case 'link':
- //case 'script':
- $this->setAttribute($node, 'href', $html);
- break;
- */
-
- case 'form':
- $this->setAttribute($node, 'action', $html);
-
- break;
-
- default:
- $this->removeChildren($node);
- $f = $this->document->createDocumentFragment();
- $append = $this->processAttributeConstants($html, $node);
- $f->appendXML($append);
- $node->appendChild($f);
- }
+ $this->setNodeValueByType($node, $html);
}
}
}
}
+
+ return null;
}
- private function outerHTML(&$nodeList, $html = false) {
+ /**
+ * @param Dom\NodeList<\Dom\Node>|DOMNodeList<\DOMNode>|null &$nodeList
+ * @param array<array-key, mixed>|string|null $html
+ *
+ * @return void
+ */
+ private function outerHTML(null|Dom\NodeList|DOMNodeList &$nodeList, null|array|string $html = null): void {
foreach ($nodeList as $node) {
- if ($html === false) {
- $doc = new DOMDocument();
-
- foreach ($node->childNodes as $child) {
- $node->parentNode->replaceChild($doc->importNode($child, true), $node);
- }
+ if ($html === '') {
+ continue;
+ }
- if ($this->documentType == 'html') {
- return $doc->saveHTML();
- } else {
- return Vvveb\xmlStripVersionDeclr($doc->saveXML());
- }
- } else {
-// $this->removeChildren($node);
- if ($html == '') {
- continue;
- }
+ if ($this->externalElements) {
+ $result = $this->loadFromExternalHtml($html, $node);
- if ($this->external_elements) {
- $result = $this->loadFromExternalHtml($html, $node);
+ $parent = $node->parentNode;
+ $count = 0;
- $parent = $node->parentNode;
- //$children = $node->childNodes;
- $count = 0;
+ if ($result) {
+ foreach ($result as $externalNode) {
+ $importedNode = $this->document->importNode($externalNode, true);
- if ($result) {
- foreach ($result as $externalNode) {
- $importedNode = $this->document->importNode($externalNode, true);
-
- if ($parent) {
- if ($count) {
- $parent->appendChild($importedNode);
- } else {
- $parent->replaceChild($importedNode, $node);
- /*
- foreach ($children as $child) {
- $importedNode->appendChild($child);
- }
- */
- }
- $node = $importedNode;
- $count++;
+ if ($parent) {
+ if ($count) {
+ $parent->appendChild($importedNode);
+ } else {
+ $parent->replaceChild($importedNode, $node);
}
+ $node = $importedNode;
+ $count++;
}
}
- } else {
- $f = $this->document->createDocumentFragment();
- $f->appendXML($this->processAttributeConstants($html, $node));
+ }
+ } else {
+ $f = $this->createXmlFragment($this->processAttributeConstants($html, $node));
+ if ($f) {
$node->parentNode->replaceChild($f, $node);
}
}
}
}
- private function innerText($nodeList, $text = false) {
+ /**
+ * @param list<Dom\HTMLElement|DOMNode>|Dom\NodeList<\Dom\Node>|DOMNodeList<\DOMNode>|null $nodeList
+ * @param string|null $text
+ *
+ * @return string|null
+ */
+ private function innerText(array|Dom\NodeList|DOMNodeList|null $nodeList, ?string $text = null): ?string {
foreach ($nodeList as $node) {
- if ($text === false) {
+ if ($text === null) {
return $node->nodeValue;
} else {
if ($node->hasChildNodes()) {
foreach ($node->childNodes as $childNode) {
$value = trim($childNode->nodeValue);
- //find first non empty text node
- //error_log(XML_TEXT_NODE . ' - ' . $childNode->nodeType . ' - ' . !empty($value) );
- if ($childNode->nodeType == XML_TEXT_NODE && ! empty($value)) {
- $f = $this->document->createDocumentFragment();
- //error_log("innerText = $text");
- $f->appendXML($this->processAttributeConstants($text, $node));
- $node->replaceChild($f, $childNode);
+ if ($childNode->nodeType === XML_TEXT_NODE && $value !== '') {
+ $f = $this->createXmlFragment($this->processAttributeConstants($text, $node));
+
+ if ($f) {
+ $node->replaceChild($f, $childNode);
+ }
break;
}
}
} else {
- switch ($node->nodeName) {
- case 'input':
- /* case 'option':*/
- $this->setAttribute($node, 'value', $text);
-
- break;
-
- break;
- //case 'img':
- case 'iframe':
- //case 'script':
- case 'video':
- case 'audio':
- case 'source':
- $this->setAttribute($node, 'src', $text);
-
- break;
- /*
- //case 'a':
- case 'link':
- $this->setAttribute($node, 'href', $text);
- break;
- */
-
- case 'form':
- $this->setAttribute($node, 'action', $text);
-
- break;
-
- default:
- //if node has no children append text
- $f = $this->document->createDocumentFragment();
- $f->appendXML($this->processAttributeConstants($text, $node));
- $node->appendChild($f);
- }
+ $this->setNodeValueByType($node, $text);
}
}
}
+
+ return null;
}
- /*
- * Show elements conditionally if $variable is true
- *
- * @param mixed $nodeList
- * @param mixed $variable [false]
+ /**
+ * @param Dom\NodeList<\Dom\Node>|DOMNodeList<\DOMNode>|null &$nodeList
+ * @param false|string $variable
*
- * @return mixed
+ * @return void
*/
- private function ifExists(&$nodeList, $variable = false) {
- if ($variable == '') {
- return false;
+ private function ifExists(null|Dom\NodeList|DOMNodeList &$nodeList, false|string $variable = false): void {
+ if ($variable === '') {
+ return;
}
foreach ($nodeList as $node) {
$condition = $this->processAttributeConstants($variable, $node);
- $isset = str_replace('!', '', $condition);
+ $isset = str_replace('!', '', $condition);
//before
- $html = "<_script language=\"php\"><![CDATA[if (isset($isset) && $condition) {]]></_script>";
- $f = $this->document->createDocumentFragment();
- $f->appendXML($html);
- $node->parentNode->insertBefore($f, $node);
+ $f = $this->createXmlFragment(VTPL_PHP_CDATA_OPEN . "if (isset($isset) && $condition) {" . VTPL_PHP_CDATA_CLOSE);
+ if ($f) {
+ $node->parentNode->insertBefore($f, $node);
+ }
//after
- $html = '<_script language="php">}</_script>';
- $f = $this->document->createDocumentFragment();
- $f->appendXML($html);
- //$node->parentNode->appendChild( $f );
- $node->parentNode->insertBefore($f, $node->nextSibling);
+ $f = $this->createXmlFragment(VTPL_PHP_OPEN . '}' . VTPL_PHP_CLOSE);
+ if ($f) {
+ $node->parentNode->insertBefore($f, $node->nextSibling);
+ }
}
}
/**
- * Opposite of ifExists, hides the elements if $variable is true.
- *
- * @param mixed $nodeList
- * @param mixed $variable [false]
+ * @param Dom\NodeList<\Dom\Node>|DOMNodeList<\DOMNode>|null &$nodeList
+ * @param false|string $variable
*
- * @return mixed
+ * @return void
*/
- private function hide(&$nodeList, $variable = false) {
+ private function hide(null|Dom\NodeList|DOMNodeList &$nodeList, false|string $variable = false): void {
if ($variable) {
$variable = '!' . $variable;
}
- return $this->ifExists($nodeList, $variable);
+ $this->ifExists($nodeList, $variable);
}
- private function tagWrap(&$nodeList, $open = false, $close = false) {
- if ($open == '' || $close == '') {
+ /**
+ * @param list<Dom\HTMLElement|DOMNode>|Dom\NodeList<\Dom\Node>|DOMNodeList<\DOMNode>|null &$nodeList
+ * @param false|string $open
+ * @param false|string $close
+ *
+ * @return bool
+ */
+ private function tagWrap(array|Dom\NodeList|DOMNodeList|null &$nodeList, false|string $open = false, false|string $close = false): bool {
+ if ($open === '' || $close === '') {
return false;
}
- $openStart = "<_script language=\"php\"><![CDATA[$open]]></_script>";
- $openEnd = '<_script language="php">}</_script>';
+ $openStart = VTPL_PHP_CDATA_OPEN . $open . VTPL_PHP_CDATA_CLOSE;
+ $openEnd = VTPL_PHP_OPEN . '}' . VTPL_PHP_CLOSE;
- $closeStart = "<_script language=\"php\"><![CDATA[$close]]></_script>";
- $closeEnd = '<_script language="php">}</_script>';
+ $closeStart = VTPL_PHP_CDATA_OPEN . $close . VTPL_PHP_CDATA_CLOSE;
+ $closeEnd = VTPL_PHP_OPEN . '}' . VTPL_PHP_CLOSE;
foreach ($nodeList as $node) {
//before start
- $f = $this->document->createDocumentFragment();
- $f->appendXML($this->processAttributeConstants($openStart, $node));
- $node->parentNode->insertBefore($f, $node);
+ $f = $this->createXmlFragment($this->processAttributeConstants($openStart, $node));
+ if ($f) {
+ $node->parentNode->insertBefore($f, $node);
+ }
//before end
- $f = $this->document->createDocumentFragment();
- $f->appendXML($this->processAttributeConstants($openEnd, $node));
+ $f = $this->createXmlFragment($this->processAttributeConstants($openEnd, $node));
if ($node->hasChildNodes()) {
- $node->insertBefore($f,$node->firstChild);
+ if ($f) {
+ $node->insertBefore($f, $node->firstChild);
+ }
} else {
- $node->appendChild($f);
+ if ($f) {
+ $node->appendChild($f);
+ }
}
//after start
- $f = $this->document->createDocumentFragment();
- $f->appendXML($this->processAttributeConstants($closeStart, $node));
- $node->appendChild($f);
+ $f = $this->createXmlFragment($this->processAttributeConstants($closeStart, $node));
+ if ($f) {
+ $node->appendChild($f);
+ }
//after end
- $f = $this->document->createDocumentFragment();
- $f->appendXML($this->processAttributeConstants($closeEnd, $node));
- $node->parentNode->insertBefore($f, $node->nextSibling);
+ $f = $this->createXmlFragment($this->processAttributeConstants($closeEnd, $node));
+ if ($f) {
+ $node->parentNode->insertBefore($f, $node->nextSibling);
+ }
}
+
+ return true;
}
- private function insertBefore(&$nodeList, $html = false) {
- if ($html == '') {
+ /**
+ * Resolve external elements for insert/append operations.
+ * If the from() reference is @_SELF_@, queries the current document;
+ * otherwise loads from an external HTML file.
+ *
+ * @param array<array-key, mixed>|string $html
+ * @param DOMNode $node
+ *
+ * @return Dom\NodeList<\Dom\Node>|DOMNodeList<\DOMNode>|false
+ */
+ private function resolveExternalElements(array|string $html, Dom\HTMLElement|DOMNode $node): Dom\NodeList|DOMNodeList|false {
+ if ($this->froms && $this->froms[0][(int)$html[1]] === '@_SELF_@') {
+ $selector = $this->froms[2][(int)$html[1]];
+
+ return $this->query($selector);
+ }
+
+ return $this->loadFromExternalHtml($html, $node);
+ }
+
+ /**
+ * @param Dom\NodeList<\Dom\Node>|DOMNodeList<\DOMNode>|null &$nodeList
+ * @param array<array-key, mixed>|string $html
+ *
+ * @return bool
+ */
+ private function insertBefore(null|Dom\NodeList|DOMNodeList &$nodeList, array|string $html): bool {
+ if ($html === '') {
return false;
}
if ($nodeList) {
foreach ($nodeList as $node) {
- if ($this->external_elements) {
- if ($this->froms[0][(int) $html[1]] == '@_SELF_@') {
- $selector = $this->froms[2][(int) $html[1]];
- $xpath = new DOMXpath($this->document);
- $result = $xpath->query($this->cssToXpath($selector));
- } else {
- $result = $this->loadFromExternalHtml($html, $node);
- }
+ if ($this->externalElements) {
+ $result = $this->resolveExternalElements($html, $node);
- if (! $result) {
+ if (!$result) {
continue;
}
- //$html = array_reverse($html);
foreach ($result as $externalNode) {
$importedNode = $this->document->importNode($externalNode, true);
$node->parentNode->insertBefore($importedNode, $node);
}
} else {
- $f = $this->document->createDocumentFragment();
- $f->appendXML($this->processAttributeConstants($html, $node));
- $node->parentNode->insertBefore($f, $node);
+ $f = $this->createXmlFragment($this->processAttributeConstants($html, $node));
+ if ($f) {
+ $node->parentNode->insertBefore($f, $node);
+ }
}
}
+
+ return true;
}
+
+ return false;
}
- private function insertAfter(&$nodeList, $html = false) {
- if ($html == '') {
+ /**
+ * @param Dom\NodeList<\Dom\Node>|DOMNodeList<\DOMNode>|null &$nodeList
+ * @param array<array-key, mixed>|string $html
+ *
+ * @return bool
+ */
+ private function insertAfter(null|Dom\NodeList|DOMNodeList &$nodeList, array|string $html): bool {
+ if ($html === '') {
return false;
}
if ($nodeList) {
foreach ($nodeList as $node) {
- if ($this->external_elements) {
- if ($this->froms[0][(int) $html[1]] == '@_SELF_@') {
- $selector = $this->froms[2][(int) $html[1]];
- $xpath = new DOMXpath($this->document);
- $result = $xpath->query($this->cssToXpath($selector));
- } else {
- $result = $this->loadFromExternalHtml($html, $node);
- }
+ if ($this->externalElements) {
+ $result = $this->resolveExternalElements($html, $node);
- if (! $result) {
+ if (!$result) {
continue;
}
- //$html = array_reverse($html);
foreach ($result as $externalNode) {
$importedNode = $this->document->importNode($externalNode, true);
+
+ //importNode returns the same node for nodes already in this document;
+ //when the external element is $node's own nextSibling, inserting it
+ //before itself throws "Cannot add newnode as the previous sibling of refnode".
+ //In that case it is already in the correct position, so skip the move.
+ if ($importedNode === $node->nextSibling) {
+ continue;
+ }
$node->parentNode->insertBefore($importedNode, $node->nextSibling);
}
} else {
- $f = $this->document->createDocumentFragment();
- $f->appendXML($this->processAttributeConstants($html, $node));
- //$node->parentNode->appendChild( $f );
- $node->parentNode->insertBefore($f, $node->nextSibling);
+ $f = $this->createXmlFragment($this->processAttributeConstants($html, $node));
+ if ($f) {
+ $node->parentNode->insertBefore($f, $node->nextSibling);
+ }
}
}
+
+ return true;
}
+
+ return false;
}
- private function append(&$nodeList, $html = false) {
- if ($html == '') {
+ /**
+ * @param Dom\NodeList<\Dom\Node>|DOMNodeList<\DOMNode>|null &$nodeList
+ * @param array<array-key, mixed>|string $html
+ *
+ * @return bool
+ */
+ private function append(null|Dom\NodeList|DOMNodeList &$nodeList, array|string $html): bool {
+ if ($html === '') {
return false;
}
if ($nodeList) {
foreach ($nodeList as $node) {
- if ($this->external_elements) {
- if ($this->froms[0][(int) $html[1]] == '@_SELF_@') {
- $selector = $this->froms[2][(int) $html[1]];
- $xpath = new DOMXpath($this->document);
- $result = $xpath->query($this->cssToXpath($selector));
- } else {
- $result = $this->loadFromExternalHtml($html, $node);
- }
+ if ($this->externalElements) {
+ $result = $this->resolveExternalElements($html, $node);
- if (! $result) {
+ if (!$result) {
continue;
}
- //$html = array_reverse($html);
foreach ($result as $externalNode) {
$importedNode = $this->document->importNode($externalNode, true);
$node->appendChild($importedNode);
}
} else {
- $f = $this->document->createDocumentFragment();
- $f->appendXML($this->processAttributeConstants($html, $node));
- $node->appendChild($f);
+ $f = $this->createXmlFragment($this->processAttributeConstants($html, $node));
+ if ($f) {
+ $node->appendChild($f);
+ }
}
}
+
+ return true;
}
+
+ return false;
}
- private function prepend(&$nodeList, $html = false) {
- if ($html == '') {
+ /**
+ * @param Dom\NodeList<\Dom\Node>|DOMNodeList<\DOMNode>|null &$nodeList
+ * @param array<array-key, mixed>|string $html
+ *
+ * @return bool
+ */
+ private function prepend(null|Dom\NodeList|DOMNodeList &$nodeList, array|string $html): bool {
+ if (!$html) {
return false;
}
if ($nodeList) {
foreach ($nodeList as $node) {
- if ($this->external_elements) {
- $result = $this->loadFromExternalHtml($html, $node);
+ if ($this->externalElements) {
+ $result = $this->resolveExternalElements($html, $node);
- if (! $result) {
+ if (!$result) {
continue;
}
- if (is_array($result)) {
- $result = array_reverse($result);
- }
-
foreach ($result as $externalNode) {
$importedNode = $this->document->importNode($externalNode, true);
+ if ($importedNode === $node->firstChild) {
+ //self-reference already in position, avoid inserting before itself
+ continue;
+ }
+
if ($node->firstChild) {
// $ref has an immediate sibling : insert newnode before this one
$node->insertBefore($importedNode, $node->firstChild);
@@ -1645,46 +1912,58 @@ class Vtpl {
}
}
} else {
- $f = $this->document->createDocumentFragment();
- $f->appendXML($this->processAttributeConstants($html, $node));
+ $f = $this->createXmlFragment($this->processAttributeConstants($html, $node));
if ($node->firstChild) {
// $ref has an immediate sibling : insert newnode before this one
- $node->insertBefore($f, $node->firstChild);
+ if ($f) {
+ $node->insertBefore($f, $node->firstChild);
+ }
} else {
// $ref has no sibling next to him : insert newnode as last child of his parent
- $node->appendChild($f);
+ if ($f) {
+ $node->appendChild($f);
+ }
}
}
}
+
+ return true;
}
+
+ return false;
}
- private function deleteAllButFirst(&$nodeList, $parent = false) {
+ /**
+ * @param Dom\NodeList<\Dom\Node>|DOMNodeList<\DOMNode>|null &$nodeList
+ *
+ * @return void
+ */
+ private function deleteAllButFirst(null|Dom\NodeList|DOMNodeList &$nodeList): void {
$first = true;
if ($nodeList) {
foreach ($nodeList as $node) {
- if (! $first) {
- $this->removeChildren($node);
-
- if ($node->parentNode) {
- $node->parentNode->removeChild($node);
- }
+ if (!$first) {
+ $this->removeNode($node);
}
$first = false;
}
}
}
- private function deleteAllButFirstChild(&$nodeList, $parent = false) {
+ /**
+ * @param Dom\NodeList<\Dom\Node>|DOMNodeList<\DOMNode>|null &$nodeList
+ *
+ * @return void
+ */
+ private function deleteAllButFirstChild(null|Dom\NodeList|DOMNodeList &$nodeList): void {
$parents = [];
if ($nodeList) {
foreach ($nodeList as $node) {
if (in_array($node->parentNode, $parents, true)) {
- $this->removeChildren($node);
- $node->parentNode->removeChild($node);
+ $this->removeNode($node);
}
if ($node->parentNode) {
@@ -1694,26 +1973,34 @@ class Vtpl {
}
}
- private function delete(&$nodeList) {
+ /**
+ * @param Dom\NodeList<\Dom\Node>|DOMNodeList<\DOMNode>|null &$nodeList
+ *
+ * @return void
+ */
+ private function delete(null|Dom\NodeList|DOMNodeList &$nodeList): void {
if ($nodeList) {
foreach ($nodeList as $node) {
- $this->removeChildren($node);
-
- if ($node->parentNode) {
- $node->parentNode->removeChild($node);
- }
+ $this->removeNode($node);
}
}
}
- private function setNodeAttribute($node, $attribute, $val) {
- if (! $node || ! $val) {
+ /**
+ * @param Dom\HTMLElement|DOMNode $node
+ * @param string $attribute
+ * @param string $val
+ *
+ * @return void
+ */
+ private function setNodeAttribute(Dom\HTMLElement|DOMNode $node, string $attribute, string $val): void {
+ if (!$val) {
return;
}
$value = $this->processAttributeConstants($val, $node);
//if the attribute value has no php in it add it directly
if ($value) {
- if (strpos($value, '<_script') === false) {
+ if (!str_contains($value, VTPL_PHP_OPEN)) {
$node->setAttribute($attribute, $value);
} else {
$this->attributes[++$this->attributesIndex] = $value;
@@ -1722,8 +2009,15 @@ class Vtpl {
}
}
- private function setAttribute(&$nodeList, $attribute, $val) {
- if (is_a($nodeList,'DOMNodeList')) {
+ /**
+ * @param Dom\HTMLElement|DOMNode|Dom\NodeList<\Dom\Node>|DOMNodeList<\DOMNode> &$nodeList
+ * @param string $attribute
+ * @param string $val
+ *
+ * @return void
+ */
+ private function setAttribute(Dom\HTMLElement|Dom\NodeList|DOMNode|DOMNodeList &$nodeList, string $attribute, string $val): void {
+ if (is_a($nodeList, 'DOMNodeList') || is_a($nodeList, 'Dom\NodeList')) {
if ($nodeList->length > 0) {
foreach ($nodeList as $node) {
/* $attr = new DOMAttr($attribute);
@@ -1738,7 +2032,14 @@ class Vtpl {
}
}
- private function addNodeClass(&$node, $val, $processConstants = true) {
+ /**
+ * @param Dom\HTMLElement|DOMNode &$node
+ * @param string $val
+ * @param bool $processConstants
+ *
+ * @return void
+ */
+ private function addNodeClass(Dom\HTMLElement|DOMNode &$node, string $val, bool $processConstants = true): void {
if ($processConstants) {
$val = $this->processAttributeConstants($val, $node);
}
@@ -1747,8 +2048,14 @@ class Vtpl {
$node->setAttribute('class', $node->getAttribute('class') . " @@__VTPL__ATTRIBUTE_PLACEHOLDER__{$this->attributesIndex}@@");
}
- private function addClass(&$nodeList, $val) {
- if (is_a($nodeList,'DOMNodeList')) {
+ /**
+ * @param Dom\NodeList<\Dom\Node>|DOMNodeList<\DOMNode> $nodeList
+ * @param string $val
+ *
+ * @return void
+ */
+ private function addClass(Dom\NodeList|DOMNodeList $nodeList, string $val): void {
+ if (is_a($nodeList, 'DOMNodeList')) {
if ($nodeList->length > 0) {
foreach ($nodeList as $node) {
$this->addNodeClass($node, $val);
@@ -1757,60 +2064,84 @@ class Vtpl {
}
}
- public function addNodeNewAttribute(&$node, $val) {
+ /**
+ * @param Dom\HTMLElement|DOMNode &$node
+ * @param string $val
+ *
+ * @return void
+ */
+ public function addNodeNewAttribute(Dom\HTMLElement|DOMNode &$node, string $val): void {
$this->newAttributes[++$this->newAttributesIndex] = $this->processAttributeConstants($val, $node);
- $node->setAttribute("__VTPL__NEW_ATTRIBUTE_PLACEHOLDER__{$this->newAttributesIndex}",'');
+ $node->setAttribute("__VTPL__NEW_ATTRIBUTE_PLACEHOLDER__{$this->newAttributesIndex}", '');
}
- public function addNewAttribute(&$nodeList, $val) {
- if ($nodeList && $nodeList->length > 0) {
+ /**
+ * @param array<array-key, mixed>|Dom\NodeList<\Dom\Node>|DOMNodeList<\DOMNode> &$nodeList
+ * @param string $val
+ *
+ * @return void
+ */
+ public function addNewAttribute(array|Dom\NodeList|DOMNodeList &$nodeList, string $val): void {
+ if ($nodeList->length > 0) {
foreach ($nodeList as $node) {
$this->addNodeNewAttribute($node, $val);
}
}
}
- private function removeAttribute(&$nodeList, $val) {
- if ($nodeList && $nodeList->length > 0) {
+ /**
+ * @param Dom\NodeList<\Dom\Node>|DOMNodeList<\DOMNode> $nodeList
+ * @param string $val
+ *
+ * @return void
+ */
+ private function removeAttribute(Dom\NodeList|DOMNodeList $nodeList, string $val): void {
+ if ($nodeList->length > 0) {
foreach ($nodeList as $node) {
$node->removeAttribute($val);
}
}
}
- private function removeClass(&$nodeList, $val) {
+ /**
+ * @param Dom\NodeList<\Dom\Node>|DOMNodeList<\DOMNode> $nodeList
+ * @param string $val
+ *
+ * @return void
+ */
+ private function removeClass(Dom\NodeList|DOMNodeList $nodeList, string $val): void {
if ($nodeList->length > 0) {
foreach ($nodeList as $node) {
- $class = $node->setAttribute('class');
+ $class = $node->getAttribute('class');
$class = str_replace($val, '', $class);
$node->setAttribute('class', $class);
}
}
}
- private function loadFromExternalHtml($val, $node) {
- $filename = $this->froms[0][(int) $val[1]]; //external html file
- $selector = $this->froms[2][(int) $val[1]];
+ /**
+ * @param array<array-key, mixed>|string $val
+ * @param DOMNode $node
+ *
+ * @return Dom\NodeList<\Dom\Node>|DOMNodeList<\DOMNode>|false
+ */
+ private function loadFromExternalHtml(array|string $val, Dom\HTMLElement|DOMNode $node): Dom\NodeList|DOMNodeList|false {
+ $filename = $this->froms[0][(int)$val[1]]; //external html file
+ $selector = $this->froms[2][(int)$val[1]];
//load specified selector if available otherwise load html with the same selector
$filename = $this->processAttributeConstants($filename, $node);
$selector = $this->processAttributeConstants($selector, $node);
- if (strncmp($filename,'/plugins/', 9) === 0) {
+ if (str_starts_with($filename, '/plugins/') || str_starts_with($filename, PUBLIC_PATH)) {
$filename = DIR_ROOT . $filename;
- } else {
- if (strncmp($filename,PUBLIC_PATH, strlen(PUBLIC_PATH)) === 0) {
- $filename = DIR_ROOT . $filename;
- } else {
- if ($filename[0] !== '/') {
- $filename = $this->htmlPath . $filename;
- }
- }
+ } elseif ($filename[0] !== '/') {
+ $filename = $this->htmlPath . $filename;
}
$this->debug->log('SELECTOR_FROM', $filename);
- if (! ($html = @file_get_contents($filename))) {
+ if (!($html = @file_get_contents($filename))) {
Vvveb\logError("can't load html $filename");
$this->debug->log('LOAD', '<b>EXTERNAL ERROR</b> ' . $filename . ' ' . $selector);
@@ -1827,266 +2158,173 @@ class Vtpl {
$html = $this->minifyHtml($html);
}
- $document = new DomDocument();
-
- if ($this->documentType == 'html') {
- @$document->loadHTML($html);
- } else {
- @$document->loadXML($html);
- }
+ $document = $this->loadDomFromString($html);
if ($selector) {
- $xpath = new DOMXpath($document);
- $xpathSelector = $this->cssToXpath($selector);
- $elements = $xpath->query($xpathSelector);
+ if ($this->legacy) {
+ $xpath = new DOMXPath($document);
+ $xpathSelector = $this->cssToXpath($selector);
+ $elements = $xpath->query($xpathSelector);
+ } else {
+ $elements = $document->querySelectorAll($selector);
+ }
} else {
$elements = $document->childNodes;
}
+ //$elements = $this->query($selector);
return $elements;
}
- function loadHtml($html) {
- if (VTPL_DONT_ALLOW_PHP) {
- $html = $this->removePhp($html);
+ /**
+ * Processes a node's attributes during the multi-language pass: rewrites
+ * relative media urls against the theme path, removes data-v-* attributes
+ * when configured, converts {$variable} attribute values to php echoes and
+ * wraps translatable placeholder/title values with the translation function.
+ *
+ * @param Dom\HTMLElement|DOMNode $node
+ *
+ * @return void
+ */
+ private function processNodeAttributes(Dom\Element|Dom\HTMLElement|DOMNode $node): void {
+ if (!$node->hasAttributes()) {
+ return;
}
- //replace script tags with placeholders to preserve formatting.
- //preg_match_all("@<script[^>]*>.*?script>@s", $html, $this->scripts);
- preg_match_all("/<script(.*?)>(.*?)<\/script>/smix", $html, $this->scripts);
- $count = count($this->scripts[0] ?? []);
+ $publicLen = strlen(PUBLIC_PATH);
- if ($count) {
- $patternsScripts = [];
- $placeholdersScripts = [];
+ foreach ($node->attributes as $name => $attrNode) {
+ $value = $attrNode->nodeValue;
+ $name = $attrNode->nodeName;
+
+ //set relative media to theme folder
+ if ($this->relativePath) {
+ if (($name === 'src' || $name === 'href' || $name === 'srcset') && $node->nodeName !== 'A') {
+ if ($value && $value[0] !== '#'
+ && $value[0] !== '@'
+ && !str_starts_with($value, '//')
+ && !str_starts_with($value, '/feed/')
+ && (!str_contains($value, ':'))) {
+ if ($value[0] === '/') {
+ if (str_starts_with($value, PUBLIC_PATH)) {
+ $value = substr($value, $publicLen);
+ } else {
+ $value = substr($value, 1);
+ }
- for ($i=0; $i < $count; $i++) {
- $patternsScripts[] = $this->scripts[0][$i];
- $placeholdersScripts[] = '<script ' . $this->scripts[1][$i] . ' holder="@@__VTPL__SCRIPT_PLACEHOLDER__' . $i . '@@"></script>';
- }
+ $this->setNodeAttribute($node, $name, PUBLIC_PATH . $value);
+ } else {
+ $this->setNodeAttribute($node, $name, $this->relativePath . $value);
+ }
+ }
+ }
- $html = str_replace($patternsScripts, $placeholdersScripts, $html);
- $this->scripts = $this->scripts[2];
- }
+ if ($name === 'style' && str_contains($value, 'url(')) {
+ $value = preg_replace_callback(
+ '/url\(([^\)]+)\)/',
+ function($matches) use ($publicLen) {
+ $url = trim($matches[1], ' \'"');
- if ($this->minifyHtml === true) {
- $html = $this->minifyHtml($html);
- }
- //replace constants
- if ($this->replaceConstants) {
- $html = str_replace(array_keys($this->replaceConstants),array_values($this->replaceConstants),$html);
- }
-
- if ($this->documentType == 'html') {
- @$this->document->loadHTML($html, LIBXML_NOERROR);
- } else {
- //convert json
- if ($this->documentType == 'json') {
- //remove json comments from line start
- $html = Vvveb\removeJsonComments($html);
- $json = json_decode($html, true);
- $json = Vvveb\prepareJson($json);
- $xml = Vvveb\array2xml($json);
- $html = $xml;
- }
- @$this->document->loadXML($html, LIBXML_NOERROR | LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
- }
+ if (str_starts_with($url, 'http')) {
+ return 'url(' . $url . ')';
+ }
- $errors = libxml_get_errors();
+ if ($url[0] === '/') {
+ if (str_starts_with($url, PUBLIC_PATH)) {
+ $url = substr($url, $publicLen);
+ } else {
+ $url = substr($url, 1);
+ }
- //original document used to extract selectors
- //$this->originalDocument = clone($this->document);
- $this->xpath = new DOMXpath($this->document);
- if ($rootNamespace = $this->document->lookupNamespaceUri($this->document->namespaceURI)) {
- $this->xpath->registerNamespace('x', $rootNamespace);
- }
+ $url = PUBLIC_PATH . $url;
+ } else {
+ $url = $this->relativePath . $url;
+ }
- if ($this->componentContent) {
- //replace component content from page with the one provided
- $elements = $this->xpath->query($this->cssToXpath($this->selector));
+ return 'url(' . $url . ')';
+ },
+ $value
+ );
- if ($elements) {
- $node = $elements->item($this->componentId);
+ $this->setNodeAttribute($node, $name, $value);
+ }
+ }
- if ($node && $node->parentNode) {
- //$html = '<div>asdasdasdasd<div>';
- //$html = $this->processAttributeConstants($this->componentContent, $node);
+ if ($this->removeVattrs && str_starts_with($name, 'data-v-')) {
+ $node->removeAttribute($name);
- $tmpDom = new DomDocument();
+ continue;
+ } else {
+ if (str_contains($value, '$')) {
+ $value = preg_replace_callback(
+ '/{(\$[a-z][\w\.>\-]+)}/i',
+ function($matches) {
+ $value = $matches[1];
+
+ if (str_starts_with($value, '$this')) {
+ $value = str_replace('$this.', '$this->', $value);
+ }
+ $value = Vvveb\dotToArrayKey($value);
- if ($this->documentType == 'html') {
- @$tmpDom->loadHTML($this->componentContent);
- } else {
- @$tmpDom->loadXML($this->componentContent);
- }
- $body = $tmpDom->getElementsByTagName('body');
- $nodeToImport = $body->item(0)->firstChild;
+ return VTPL_PHP_CDATA_OPEN . 'if (isset(' . $value . ')) echo htmlspecialchars(' . $value . ');' . VTPL_PHP_CDATA_CLOSE;
+ },
+ $value
+ );
- $importNode = $this->document->importNode($nodeToImport, true);
- //$this->document->appendChild($importNode);
- $node->parentNode->replaceChild($importNode, $node);
- //$node->parentNode->removeChild($node);
- ///$node->appendChild($f);
+ $this->setNodeAttribute($node, $name, $value);
}
}
- }
- //add base tag if missing
- $base = $this->document->getElementsByTagName('base');
+ if (($name === 'placeholder' || $name === 'title'/* || $name == 'alt'*/) && ($value && $value[0] !== '@' && $value[0] !== '<')) {
+ $trimmed = trim($value);
- if ($base->length == 0) {
- $head = $this->document->getElementsByTagName('head');
-
- if ($head->length > 0) {
- $base = $this->document->createElement('base');
- $base->setAttribute('href','');
- $head->item(0)->insertBefore($base, $head->item(0)->firstChild);
+ if ($trimmed) {
+ $php = VTPL_PHP_CDATA_OPEN . 'echo ' . $this->translationFunction . '(\'' . addcslashes($trimmed, "'") . '\');' . VTPL_PHP_CDATA_CLOSE;
+ $this->setNodeAttribute($node, $name, $php);
+ }
}
- } else {
- $base[0]->setAttribute('href', '');
- }
-
- return $errors;
- }
-
- function loadHtmlTemplate($filename) {
- $extension = strtolower(trim(substr($filename, -4), '.'));
- $this->documentType = $extension;
-
- if (strpos($filename, DS) === false) {
- $filename = $this->htmlPath . $filename;
+ /*
+ if (strpos($name, 'data-v-') === 0) {
+ $node->removeAttribute($name);
+ }*/
}
-
- if (! ($html = @file_get_contents($filename))) {
- Vvveb\logError("can't load template $filename");
- $this->debug->log('LOAD', '<b>ERROR</b> ' . $filename);
-
- return false;
- }
-
- $this->htmlSourceFile = $filename;
- $this->debug->log('LOAD', $filename);
-
- $this->loadHtml($html);
}
- private function setMultiLanguageText($currentNode) {
- if (! $currentNode || ! $currentNode->childNodes || $currentNode->childNodes->length == 0) {
+ /**
+ * @param Dom\HTMLElement|DOMNode $currentNode
+ *
+ * @return void
+ */
+ private function setMultiLanguageText(Dom\Node|DOMNode $currentNode): void {
+ if ($currentNode->childNodes->length === 0) {
return;
}
- $length = $currentNode->childNodes->length;
-
+ $length = $currentNode->childNodes->length;
$publicLen = strlen(PUBLIC_PATH);
-
for ($i = 0; $i < $length; $i++) {
$node = $currentNode->childNodes[$i];
-
- if (! $node) {
+ if (!$node) {
continue;
}
//strip comments
- if ($this->removeComments && $node->nodeType == XML_COMMENT_NODE) {
+ if ($node->nodeType === XML_COMMENT_NODE && $this->removeComments) {
$node->parentNode->removeChild($node);
$i--;
continue;
}
- //check if attribute is a php variable
- if ($node && $node->hasAttributes()) {
- foreach ($node->attributes as $name => $attrNode) {
- $value = $attrNode->nodeValue;
- $name = $attrNode->nodeName;
-
- //set relative media to theme folder
- if ($this->relativePath) {
- if (($name == 'src' || $name == 'href' || $name == 'srcset') && $node->nodeName != 'A') {
- if ($value && $value[0] != '#' &&
- $value[0] != '@' &&
- strncmp($value, '//', 2) != 0 &&
- strncmp($value, '/feed/', 6) != 0 &&
- (strpos($value, ':') === false)) {
- if ($value[0] == '/') {
- if (strncmp($value, PUBLIC_PATH, $publicLen) == 0) {
- $value = substr($value, $publicLen);
- } else {
- $value = substr($value, 1);
- }
-
- $this->setNodeAttribute($node, $name, PUBLIC_PATH . $value);
- } else {
- $this->setNodeAttribute($node, $name, $this->relativePath . $value);
- }
- }
- }
-
- if ($name == 'style' && strpos($value, 'url(') !== false) {
- $value = preg_replace_callback('/url\(([^\)]+)\)/',
- function ($matches) {
- $url = trim($matches[1], ' \'"');
-
- if ($url[0] == '/') {
- if (strncmp($url, PUBLIC_PATH, $publicLen) == 0) {
- $url = substr($url, $publicLen);
- } else {
- $url = substr($url, 1);
- }
-
- $url = PUBLIC_PATH . $url;
- } else {
- $url = $this->relativePath . $url;
- }
-
- return 'url(' . $url . ')';
- }, $value);
-
- $this->setNodeAttribute($node, $name, $value);
- }
- }
-
- if ($this->removeVattrs && substr($name, 0, 7) === 'data-v-') {
- $node->removeAttribute($name);
-
- continue;
- } else {
- if (strpos($value,'$') !== false) {
- $value = preg_replace_callback('/{(\$[a-z][\w\.>\-]+)}/i',
- function ($matches) {
- $value = $matches[1];
-
- if (strpos($value, '$this') === 0) {
- $value = str_replace('$this.', '$this->', $value);
- }
- $value = Vvveb\dotToArrayKey($value);
- $php = '<_script language="php"><![CDATA[if (isset(' . $value . ')) echo htmlspecialchars(' . $value . ');]]></_script>';
-
- return $php;
- }, $value);
-
- $this->setNodeAttribute($node, $name, $value);
- }
- }
-
- if (($name == 'placeholder' || $name == 'title'/* || $name == 'alt'*/) && ($value && $value[0] != '@' && $value[0] != '<')) {
- $trimmed = trim($value);
- if ($trimmed) {
- $php = '<_script language="php"><![CDATA[echo ' . $this->translationFunction . '(\'' . addcslashes($trimmed, "'") . '\');]]></_script>';
- $this->setNodeAttribute($node, $name, $php);
- }
- }
- /*
- if (strpos($name, 'data-v-') === 0) {
- $node->removeAttribute($name);
- }*/
- }
+ //process media urls, data-v-* attrs, {$variables} and translatable placeholders
+ if (property_exists($node, 'attributes') || (method_exists($node, 'hasAttributes') && $node->hasAttributes())) {
+ $this->processNodeAttributes($node);
}
$tagName = isset($node->parentNode->tagName) ? strtolower($node->parentNode->tagName) : false;
- if ($node && $node->nodeType == XML_TEXT_NODE &&
- (! $tagName || ($tagName != 'textarea' && $tagName != '_script'
- && $tagName != 'code' && $tagName != 'iframe'
- && $tagName != 'noscript'))) {
+ if ($node && $node->nodeType === XML_TEXT_NODE
+ && (!$tagName || ($tagName !== 'textarea' && $tagName !== '_script' && $tagName !== 'script'
+ && $tagName !== 'code' && $tagName !== 'iframe' && $tagName !== 'html'
+ && $tagName !== 'noscript'))) {
if (isset($node->wholeText)) {
$text = $node->wholeText;
} else {
@@ -2097,102 +2335,113 @@ class Vtpl {
$trimmed = trim($text);
//skip untranslatable text
- if (strlen($trimmed) < 2 || //too small
- (strncmp($trimmed, '{$', 2) == 0) || //starts with variable
- (strncmp($trimmed, 'http', 4) == 0) || //is url
- (strpos($trimmed, '{$') !== false) || //string has variable
- (strpos($trimmed, '<?php') !== false) || //string has php code
- (is_numeric($trimmed[0]))
+ if (strlen($trimmed) < 2 //too small
+ || str_starts_with($trimmed, '{$') //starts with variable
+ || str_starts_with($trimmed, 'http') //is url
+ || str_contains($trimmed, '{$') //string has variable
+ || str_contains($trimmed, '<?php') //string has php code
+ || (is_numeric($trimmed[0]))
) {
continue;
}
$before = $currentNode->childNodes->length;
- if ($trimmed != '') {
- //don't translate long texts
- if (strlen($trimmed) < 1024) {
- /*
- $php = '<_script language="php"><![CDATA[echo ' . $this->translationFunction . '(\'' . $trimmed . '\');]]></_script>';
- //keep space around text for html spacing
- $php = str_replace($trimmed, $php, $text);
- $f = $this->document->createDocumentFragment();
- $f->appendXML($php);
- */
+ //don't translate long texts
+ if (strlen($trimmed) < 1024) {
+ if ($this->legacy) {
$c = $this->document->createCDATASection('echo ' . $this->translationFunction . '(\'' . addcslashes($trimmed, "'") . '\');');
- $f = $this->document->createElement('_script');
- $f->setAttribute('language', 'php');
- $f->appendChild($c);
- $node->parentNode->replaceChild($f, $node);
-
- //add previously trimmed space around text
- $space = str_replace($trimmed, '|', $text);
- $explode = explode('|', $space);
- //space before text
- if ($explode[0]) {
- $s = $this->document->createTextNode($explode[0]);
- $f->parentNode->insertBefore($s, $f);
- }
- //space after text
- if (isset($explode[1]) && $explode[1]) {
- $e = $this->document->createTextNode($explode[1]);
- //php 8
- if (isset($f->nextElementSibling) && $f->nextElementSibling) {
+ } else {
+ $c = $this->document->createTextNode('echo ' . $this->translationFunction . '(\'' . addcslashes($trimmed, "'") . '\');');
+ }
+ $f = $this->document->createElement('_script');
+ $f->setAttribute('language', 'php');
+ $f->appendChild($c);
+ $node->parentNode->replaceChild($f, $node);
+
+ //add previously trimmed space around text
+ $space = str_replace($trimmed, '|', $text);
+ $explode = explode('|', $space);
+ //space before text
+ if ($explode[0]) {
+ $s = $this->document->createTextNode($explode[0]);
+ $f->parentNode->insertBefore($s, $f);
+ }
+ //space after text
+ if (isset($explode[1]) && $explode[1]) {
+ $e = $this->document->createTextNode($explode[1]);
+ //php 8
+ if (isset($f->nextElementSibling)) {
+ //add before next element
+ $f->parentNode->insertBefore($e, $f->nextSibling);
+ } else {
+ if ($f->nextSibling) {
//add before next element
$f->parentNode->insertBefore($e, $f->nextSibling);
} else {
- if ($f->nextSibling) {
- //add before next element
- $f->parentNode->insertBefore($e, $f->nextSibling);
- } else {
- //add as last element
- $f->parentNode->appendChild($e);
- }
+ //add as last element
+ $f->parentNode->appendChild($e);
}
}
}
- //$node->parentNode->replaceChild($f, $node);
- } else {
- if ($this->removeWhitespace) {
- //remove empty space
- $node->parentNode->removeChild($node);
- $i--;
- }
}
$diff = $currentNode->childNodes->length - $before;
$length += $diff;
- //$i += $diff;
} else {
$this->setMultiLanguageText($node);
}
}
}
- private function minifyPhp($php) {
- //php comments outside strings /* */
- $php = preg_replace('/(?<!["\'])\/\*.*?\*\//s', '', $php);
+ /**
+ * @param string $php
+ *
+ * @return string
+ */
+ private function minifyPhp(string $php): string {
+ if (function_exists('token_get_all')) {
+ //tokenize so // and /* inside strings (e.g. "https://host") are not stripped as comments
+ $tokens = token_get_all('<?php ' . $php);
+ $clean = '';
+ foreach ($tokens as $token) {
+ if (is_array($token) && ($token[0] === T_DOC_COMMENT || ($token[0] === T_COMMENT && !str_starts_with($token[1], '#')))) {
+ continue;
+ }
+ $clean .= is_array($token) ? $token[1] : $token;
+ }
+ $php = preg_replace('/^<\?php\s*/', '', $clean, 1);
+ } else {
+ //php comments outside strings /* */
+ $php = preg_replace('/(?<!["\'])\/\*.*?\*\//s', '', $php);
- //php comments outside strings //
- $php = preg_replace('@(\/\/)(?=(?:[^"\']|["\'][^"\']*["\'])*$)[^\n]*@s', '', $php);
+ //php comments outside strings //
+ $php = preg_replace('@(\/\/)(?=(?:[^"\']|["\'][^"\']*["\'])*$)[^\n]*@s', '', $php);
+ }
//repeating spaces
$php = preg_replace('/\s+/', ' ', $php);
//repeating end lines
- $php = preg_replace('/\n+/', '', $php);
-
- return $php;
+ return preg_replace('/\n+/', '', $php);
}
- private function removePhp($html) {
+ /**
+ * @param string $html
+ *
+ * @return string
+ */
+ private function removePhp(string $html): string {
//hack, php allows different opening and closing tags
- $html = preg_replace('@(<\?php|<\? |<\?=|<\s*script\s*language\s*=\s*"\s*php\s*"\s*>|<%[^%]*%>).*?(\?>|<\s*/\s*script\s*>|%>)@sm', '', $html);
-
- return $html;
+ return preg_replace('@(<\?php|<\? |<\?=|<\s*script\s*language\s*=\s*"\s*php\s*"\s*>|<%[^%]*%>).*?(\?>|<\s*/\s*script\s*>|%>)@sm', '', $html);
}
- private function minifyHtml($html) {
+ /**
+ * @param string $html
+ *
+ * @return string
+ */
+ private function minifyHtml(string $html): string {
//html comments but keep ie conditionals
$html = preg_replace('/<!--(?!\s*\[if\s)(?!@@_KEEP_COMMENT_@@)(.*?)-->/sm', '', $html);
$html = str_replace('<!--@@_KEEP_COMMENT_@@', '<!--', $html);
@@ -2203,71 +2452,76 @@ class Vtpl {
//repeating end lines
$html = preg_replace('/\n+/', "\n", $html);
$html = preg_replace('@> </@', '></', $html);
- /*
- // space between tags
- $html = preg_replace('/> </', '><', $html);
- $html = preg_replace('/> </', '><', $html);*/
- /*
- $html = preg_replace('/ </', '<', $html);
- $html = preg_replace('/> /', '>', $html);
- */
$html = preg_replace('/ "/', '"', $html);
$html = preg_replace('/" /', '"', $html);
//repeating spaces
- $html = preg_replace('/\s+/', ' ', $html);
-
- return $html;
+ return preg_replace('/\s+/', ' ', $html);
}
- private function cleanHtml(&$html) {
- $self = $this;
+ /**
+ * @param string|null &$html
+ *
+ * @return void
+ */
+ private function cleanHtml(?string &$html): void {
+ if ($html === null) {
+ return;
+ }
- $html = preg_replace_callback('/@@__VTPL__ATTRIBUTE_PLACEHOLDER__(\d+)@@/',
- function ($matches) use ($self) {
- return $self->attributes[$matches[1]];
- }, $html); //sad hack :(
+ $html = preg_replace_callback(
+ '/@@__VTPL__ATTRIBUTE_PLACEHOLDER__(\d+)@@/',
+ fn ($matches) => $this->attributes[$matches[1]],
+ $html
+ ); //sad hack :(
- $html = preg_replace_callback('/__VTPL__NEW_ATTRIBUTE_PLACEHOLDER__(\d+)=""/',
- function ($matches) use ($self) {
- return $self->newAttributes[$matches[1]];
- }, $html); //sad hack :(
+ $html = preg_replace_callback(
+ '/__VTPL__NEW_ATTRIBUTE_PLACEHOLDER__(\d+)=""/',
+ fn ($matches) => $this->newAttributes[$matches[1]],
+ $html
+ ); //sad hack :(
- $html = preg_replace_callback('/<script(.*?)holder="@@__VTPL__SCRIPT_PLACEHOLDER__(\d+)@@"(.*?)><\/script>/',
- function ($matches) use ($self) {
+ $html = preg_replace_callback(
+ '/<script(.*?)holder="@@__VTPL__SCRIPT_PLACEHOLDER__(\d+)@@"(.*?)><\/script>/',
+ function($matches) {
if (VTPL_JS_MINIFY) {
- $script = $self->minifyJs($self->scripts[$matches[2]]);
+ $script = $this->minifyJs($this->scripts[$matches[2]]);
} else {
- $script = $self->scripts[$matches[2]];
+ $script = $this->scripts[$matches[2]];
}
return '<script' . $matches[1] . ' ' . $matches[3] . '>' . $script . '</script>';
- }, $html);
+ },
+ $html
+ );
//cleanup modified scripts
- $html = preg_replace('/<script.*?holder="@@__VTPL__SCRIPT_PLACEHOLDER__(\d+)@@"[^>]*>/','', $html);
+ $html = preg_replace('/<script.*?holder="@@__VTPL__SCRIPT_PLACEHOLDER__(\d+)@@"[^>]*>/', '', $html);
+
+ // Constants, replace @@_CONSTANT_NAME_@@ with the value defined for CONSTANT_NAME = 'value'
+ $html = preg_replace_callback(
+ '/@@_CONSTANT_([A-Z_]*)_@@/',
+ function($matches) {
+ //constant may be referenced but never defined - emit nothing instead of warning/null
+ return $this->constants[$matches[0]] ?? '';
+ },
+ $html
+ );
/*
- Constants, replace @@_CONSTANT_NAME_@@ with the value defined for CONSTANT_NAME = 'value'
- */
- $html = preg_replace_callback('/@@_CONSTANT_([A-Z_]*)_@@/',
- function ($matches) use ($self) {
- return $self->constants[$matches[0]];
- }, $html);
-
- /*
- Moustache variables used in javascript code in html template, it replaces {$variable} with $variable, if $variable is array then the output is json
- Modifier support with {$variable|function_name} ex: {$var|htmlspecialchars} multiple modifiers {$var|htmlspecialchars|trim}
+ Moustache variables used in javascript code in html template, it replaces $variable with $variable, if $variable is array then the output is json
+ Modifier support with $variable|function_name ex: $var|htmlspecialchars multiple modifiers $var|htmlspecialchars|trim
*/
- $html = preg_replace_callback('/{\s*(\$[\w\-\>\.]+)\|?([\w\.\|]+)?\s*}/',
- function ($matches) use ($self) {
+ $html = preg_replace_callback(
+ '/{\s*(\$[\w\-\>\.]+)\|?([\w\.\|]+)?\s*}/',
+ function($matches) {
$modifier = false;
$variable = str_replace('$this.', '$this->', $matches[1]);
$variable = Vvveb\dotToArrayKey($variable);
if (isset($matches[2]) && $matches[2]) {
- $modifier = $variable;
+ $modifier = $variable;
$modifiers = explode('|', $matches[2]);
foreach ($modifiers as $mod) {
@@ -2276,21 +2530,33 @@ class Vtpl {
}
if ($modifier) {
- $template =
- "<?php if (isset($variable)) {
+ if ($this->escapeInline) {
+ $escaped = 'htmlspecialchars($modified)';
+ } else {
+ $escaped = '$modified';
+ }
+
+ $template
+ = "<?php if (isset($variable)) {
\$modified = $modifier;
if (is_array($variable)) {
- echo json_encode(\$modified);
+ echo json_encode(\$modified, JSON_HEX_TAG);
} else {
- echo \$modified;
+ echo $escaped;
}
}
?>";
} else {
- $template =
- "<?php if (isset($variable)) {
+ if ($this->escapeInline) {
+ $escaped = "htmlspecialchars($variable)";
+ } else {
+ $escaped = $variable;
+ }
+
+ $template
+ = "<?php if (isset($variable)) {
if (is_array($variable)) {
- echo json_encode($variable);
+ echo json_encode($variable, JSON_HEX_TAG);
} else {
echo $variable;
}
@@ -2299,49 +2565,116 @@ class Vtpl {
}
return $template;
- }, $html);
+ },
+ $html
+ );
- $html = str_replace(['<_script language="php"><![CDATA[', ']]></_script>', '<_script language="php">', '</_script>'], ['<?php ', ' ?>', '<?php ', ' ?>'], $html);
+ $html = str_replace([VTPL_PHP_CDATA_OPEN, VTPL_PHP_CDATA_CLOSE, VTPL_PHP_OPEN, VTPL_PHP_CLOSE], ['<?php ', ' ?>', '<?php ', ' ?>'], $html);
//decode html entities to match translation strings
$translationFunction = preg_quote($this->translationFunction);
- $html = preg_replace_callback("/<\?php echo $translationFunction\('(.+?)'\); \?>/",
- function ($matches) {
+ $html = preg_replace_callback(
+ "/<\\?php echo {$translationFunction}\\('(.+?)'\\); \\?>/",
+ function($matches) {
$translation = html_entity_decode($matches[1], ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML5);
//keep <> encoded to avoid xss
$translation = str_replace(['<', '>'], ['&lt;', '&gt;'], $translation);
- return "<?php echo {$this->translationFunction}('$translation'); ?>";
- }, $html);
+ return "<?php echo {$this->translationFunction}('{$translation}'); ?>";
+ },
+ $html
+ );
//remove empty value for data attributes
- //$html = preg_replace('/(data-[\w\-]+)="\s*"/','$1', $html);
//remove data-v- attributes
if ($this->removeVattrs) {
- //$html = preg_replace('/data-v-[\-\w]+\s*=\s*"[^"]*"|data-v-[\-\w]+/','', $html);
}
}
- function saveCompiledTemplate($compiledFile) {
+ /**
+ * Creates a document fragment from an xml string, or null when the fragment
+ * would be empty (appendXML on empty/invalid xml yields no children).
+ *
+ * @param string $xml
+ *
+ * @return ?DOMDocumentFragment
+ */
+ private function createXmlFragment(string $xml): null|Dom\DocumentFragment|DOMDocumentFragment {
+ $f = $this->document->createDocumentFragment();
+ $f->appendXML($xml);
+
+ return $f->firstChild ? $f : null;
+ }
+
+ /**
+ * Creates a DOMDocument|Dom\Document and loads a string as html or xml based on documentType.
+ *
+ * @param string $html
+ * @param int $options libxml option flags for the xml branch
+ *
+ * @return Dom\Document|DOMDocument
+ */
+ private function loadDomFromString(string $html, int $options = LIBXML_NOERROR): Dom\Document|DOMDocument {
+ if ($this->documentType === 'html') {
+ if ($this->legacy) {
+ $document = new DOMDocument();
+ @$document->loadHTML($html, $options);
+ } else {
+ $document = \Dom\HTMLDocument::createFromString($html);
+ }
+ } else {
+ $document = new DOMDocument();
+ @$document->loadXML($html, $options);
+ }
+
+ return $document;
+ }
+
+ /**
+ * Create a DOMDocument with the same options used by the engine.
+ *
+ * @return DOMDocument
+ */
+ private function createDomDocument(): DOMDocument {
+ $dom = new DOMDocument();
+ $this->configureDomDocument($dom);
+ $dom->preserveWhiteSpace = false; //override for extraction
+
+ return $dom;
+ }
+
+ /**
+ * Serialize a DOMDocument to HTML or XML string based on documentType.
+ *
+ * @param DOMDocument $dom
+ *
+ * @return string
+ */
+ private function saveDocument(Dom\Document|DOMDocument $dom): string {
+ if ($this->documentType === 'html') {
+ return $dom->saveHTML();
+ }
+
+ return Vvveb\xmlStripVersionDeclr($dom->saveXML());
+ }
+
+ /**
+ * @param string $compiledFile
+ *
+ * @return bool
+ */
+ public function saveCompiledTemplate(string $compiledFile): bool {
$this->processTemplateFile();
$this->processTemplate();
$this->setMultiLanguageText($this->document);
if ($this->selector) {
//extract only the specified part
- $elements = $this->xpath->query($this->cssToXpath($this->selector));
- $componentNode = $elements->item($this->componentId);
+ $elements = $this->query($this->selector);
+ $componentNode = $elements ? $elements->item($this->componentId) : null;
if ($componentNode) {
- $tmpDom = new DOMDocument();
- $tmpDom->preserveWhiteSpace = false;
- $tmpDom->recover = true;
- $tmpDom->strictErrorChecking = false;
- $tmpDom->substituteEntities = false;
- $tmpDom->formatOutput = false;
- $tmpDom->resolveExternals = false;
- $tmpDom->validateOnParse = false;
- $tmpDom->xmlStandalone = true;
+ $tmpDom = $this->createDomDocument();
//add before php code if available
$currentNode = $componentNode;
@@ -2359,26 +2692,12 @@ class Vtpl {
$tmpDom->appendChild($tmpDom->importNode($currentNode, true));
}
- if ($this->documentType == 'html') {
- $html = $tmpDom->saveHTML();
- } else {
- $html = Vvveb\xmlStripVersionDeclr($tmpDom->saveXML());
- }
-
- $html = trim($html);
+ $html = trim($this->saveDocument($tmpDom));
} else {
- if ($this->documentType == 'html') {
- $html = $this->document->saveHTML();
- } else {
- $html = Vvveb\xmlStripVersionDeclr($this->document->saveXML());
- }
+ $html = $this->saveDocument($this->document);
}
} else {
- if ($this->documentType == 'html') {
- $html = $this->document->saveHTML();
- } else {
- $html = Vvveb\xmlStripVersionDeclr($this->document->saveXML());
- }
+ $html = $this->saveDocument($this->document);
}
$this->cleanHtml($html);
@@ -2397,20 +2716,159 @@ class Vtpl {
}
if ($this->checkSyntax && function_exists('token_get_all')) {
- file_put_contents($compiledFile, $html);
-
try {
- token_get_all($html, TOKEN_PARSE);
- } catch (\ParseError | \Error $e) {
- //return \Vvveb\System\Core\exceptionHandler($e);
+ //validate before writing so a broken template never poisons the compiled cache
+ $tokens = token_get_all($html, TOKEN_PARSE);
+ unset($tokens);
+ } catch (\Error|\ParseError $e) {
$data = \Vvveb\System\Core\exceptionToArray($e, $compiledFile);
+ file_put_contents($compiledFile, $html);
- return \Vvveb\System\Core\FrontController :: notFound(false, $data, 500);
+ \Vvveb\System\Core\FrontController::notFound(false, $data, 500);
}
- } else {
- file_put_contents($compiledFile, $html);
}
+ file_put_contents($compiledFile, $html);
+
return true;
}
+
+ /**
+ * @param string $html
+ *
+ * @return array<array-key, mixed>
+ */
+ public function loadHtml(string $html): array {
+ if (VTPL_DONT_ALLOW_PHP) {
+ $html = $this->removePhp($html);
+ }
+ //replace script tags with placeholders to preserve formatting.
+
+ preg_match_all('/<script(.*?)>(.*?)<\/script>/smix', $html, $this->scripts);
+ $count = count($this->scripts[0]);
+
+ if ($count) {
+ $patternsScripts = [];
+ $placeholdersScripts = [];
+
+ for ($i = 0; $i < $count; $i++) {
+ $patternsScripts[] = $this->scripts[0][$i];
+ $placeholdersScripts[] = '<script ' . $this->scripts[1][$i] . ' holder="@@__VTPL__SCRIPT_PLACEHOLDER__' . $i . '@@"></script>';
+ }
+
+ $html = str_replace($patternsScripts, $placeholdersScripts, $html);
+ $this->scripts = $this->scripts[2];
+ }
+
+ if ($this->minifyHtml === true) {
+ $html = $this->minifyHtml($html);
+ }
+ //replace constants
+ if ($this->replaceConstants) {
+ $html = str_replace(array_keys($this->replaceConstants), array_values($this->replaceConstants), $html);
+ }
+
+ if ($this->documentType === 'html') {
+ libxml_clear_errors();
+
+ if ($this->legacy) {
+ @$this->document->loadHTML($html, LIBXML_NOERROR);
+ } else {
+ $this->document = \Dom\HTMLDocument::createFromString($html);
+ }
+
+ //@\Dom\HTMLDocument::createFromString($html, LIBXML_NOERROR);
+ } else {
+ //convert json
+ if ($this->documentType === 'json') {
+ //remove json comments from line start
+ $html = Vvveb\removeJsonComments($html);
+ $json = json_decode($html, true);
+ $json = Vvveb\prepareJson($json);
+ $xml = Vvveb\array2xml($json);
+ $html = $xml;
+ }
+ libxml_clear_errors();
+ @$this->document->loadXML($html, LIBXML_NOERROR | LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
+ }
+
+ $errors = libxml_get_errors();
+ //original document used to extract selectors
+ if ($this->legacy) {
+ $this->xpath = new DOMXPath($this->document);
+
+ if ($rootNamespace = $this->document->lookupNamespaceUri($this->document->namespaceURI)) {
+ $this->xpath->registerNamespace('x', $rootNamespace);
+ }
+ }
+ if ($this->componentContent) {
+ //replace component content from page with the one provided
+ //$elements = $this->xpath->query($this->cssToXpath($this->selector));
+ $elements = $this->query($this->selector);
+
+ if ($elements) {
+ $node = $elements->item($this->componentId);
+
+ if ($node && $node->parentNode) {
+ //$html = '<div>asdasdasdasd<div>';
+ //$html = $this->processAttributeConstants($this->componentContent, $node);
+
+ $tmpDom = $this->loadDomFromString($this->componentContent);
+ $body = $tmpDom->getElementsByTagName('body');
+ $nodeToImport = $body->item(0)->firstChild ?? null;
+
+ if (!$nodeToImport) {
+ Vvveb\logError("component content for selector {$this->selector} is empty");
+
+ return $errors;
+ }
+
+ $importNode = $this->document->importNode($nodeToImport, true);
+ $node->parentNode->replaceChild($importNode, $node);
+ }
+ }
+ }
+
+ //add base tag if missing
+ $base = $this->document->getElementsByTagName('base');
+
+ if ($base->length === 0) {
+ $head = $this->document->getElementsByTagName('head');
+
+ if ($head->length > 0) {
+ $base = $this->document->createElement('base');
+ $base->setAttribute('href', '');
+ $head->item(0)->insertBefore($base, $head->item(0)->firstChild);
+ }
+ } else {
+ $base[0]->setAttribute('href', '');
+ }
+
+ return $errors;
+ }
+
+ /**
+ * @param string $filename
+ *
+ * @return array<array-key, mixed> Array with xml error messages, empty if no errors
+ */
+ public function loadHtmlTemplate(string $filename): array {
+ $extension = strtolower(trim(substr($filename, -4), '.'));
+ $this->documentType = $extension;
+
+ if (!str_contains($filename, DS)) {
+ $filename = $this->htmlPath . $filename;
+ }
+
+ if (!($html = @file_get_contents($filename))) {
+ Vvveb\logError("can't load template $filename");
+ $this->debug->log('LOAD', '<b>ERROR</b> ' . $filename);
+
+ return [];
+ }
+
+ $this->debug->log('LOAD', $filename);
+
+ return $this->loadHtml($html);
+ }
}