Powerful and easy to use cms to build websites, blogs or ecommerce stores.
HTML backendblogblog-engineblog-platformbloggingcmscontent-managementcontent-management-systemecommerceecommerce-platformno-codepage-builderphpphp-cmsphp7php8self-hostedshopping-cartweb-applicationwebsite-builder
Refactored functions.php, improved sanitizeHTML entity decode and work with unclosed tags GHSA-prqj-4768-vcmq
Givan2ef74f82a7ff
diff --git a/system/functions.php b/system/functions.phpindex 9225338..3df6429 100755--- a/system/functions.php+++ b/system/functions.php@@ -20,2314 +20,25 @@**/-namespace Vvveb;--function url($parameters, $mergeParameters = false, $useCurrentUrl = true) {- if (is_string($parameters) && $parameters) {- $result = '';-- if (isset($mergeParameters['scheme'])) {- $result .= $mergeParameters['scheme'] . ':';- unset($mergeParameters['scheme']);- }-- if (isset($mergeParameters['host'])) {- $result .= '//' . \Vvveb\System\Sites::url($mergeParameters['host']);- unset($mergeParameters['host']);-- if (isset($mergeParameters['scheme'])) {- $result = $mergeParameters['scheme'] . ":$result";- unset($mergeParameters['scheme']);- }- }-- $path = $mergeParameters['path'] ?? SITE_PATH;-- $url = System\Routes::url($parameters, $mergeParameters);- $result .= (V_SUBDIR_INSTALL ? V_SUBDIR_INSTALL : '') . $path . ($url ?? '');- } else {- static $url = '';- static $urlParams = [];-- if ($useCurrentUrl) {- $url = parse_url($_SERVER['REQUEST_URI'] ?? '');-- if (isset($url['query'])) {- parse_str($url['query'], $urlParams);- }- }-- if (! is_array($parameters)) {- $parameters = [];- }-- if ($mergeParameters) {- if (is_array($mergeParameters)) {- $mergeParameters = array_merge($urlParams, $mergeParameters);- } else {- $mergeParameters = $urlParams;- }-- if (is_array($mergeParameters)) {- $parameters = array_merge($mergeParameters, $parameters);- }- }-- $result = '';- $path = $parameters['path'] ?? SITE_PATH;-- if (isset($parameters['host'])) {- $result .= '//' . \Vvveb\System\Sites::url($parameters['host']);- unset($parameters['host']);-- if (isset($parameters['scheme'])) {- $result = $parameters['scheme'] . ":$result";- unset($parameters['scheme']);- }- } else {- if (! $useCurrentUrl) {- $result .= (V_SUBDIR_INSTALL ? V_SUBDIR_INSTALL : '') . $path;- }- }-- $result .= ($useCurrentUrl ? $url['path'] ?? '' : '') . ($parameters ? '?' . urldecode(http_build_query($parameters)) : '');- }-- return $result;-}--function config($key = null, $default = null) {- if (is_null($key)) {- return System\Config::getInstance();- }-- return System\Config::getInstance()->get($key, $default);-}--function getConfig($key = null, $default = null) {- return System\Config::getInstance()->get($key, $default);-}--function setConfig($key, $value = null) {- return System\Config::getInstance()->set($key, $value);-}--function unsetConfig($key) {- return System\Config::getInstance()->unset($key);-}--//setting-function getSetting($namespace, $key = null, $default = null, $site_id = SITE_ID) {- return System\Setting::getInstance()->get($namespace, $key, $default, $site_id);-}--function setSetting($namespace, $key = null, $value = null, $site_id = SITE_ID) {- return System\Setting::getInstance()->set($namespace, $key, $value, $site_id);-}--function deleteSetting($namespace, $key = null, $site_id = SITE_ID) {- return System\Setting::getInstance()->delete($namespace, $key, $site_id);-}--function setMultiSetting($namespace, $settings, $site_id = SITE_ID) {- return System\Setting::getInstance()->setMulti($namespace, $settings, $site_id);-}--//setting content-function getMultiSettingContent($site_id, $namespace, $key = null, $default = null, $language_id = false) {- return System\Meta\SettingContent::getInstance()->getMulti($site_id, $namespace, $key, $default, $language_id);-}--function setMultiSettingContent($site_id, $meta) {- return System\Meta\SettingContent::getInstance()->setMulti($site_id, $meta);-}--// post meta-function getPostMeta($post_id, $namespace, $key = null, $default = null) {- return System\Meta\PostMeta::getInstance()->get($post_id, $namespace, $key, $default);-}--function setPostMeta($post_id, $namespace, $key = null, $value = null) {- return System\Meta\PostMeta::getInstance()->set($post_id, $namespace, $key, $value);-}--function deletePostMeta($post_id, $namespace, $key = null) {- return System\Meta\PostMeta::getInstance()->delete($post_id, $namespace, $key);-}--function setMultiPostMeta($post_id, $namespace, $meta) {- return System\Meta\PostMeta::getInstance()->setMulti($post_id, $namespace, $meta);-}--// post meta content-function getPostContentMeta($post_id, $namespace, $key = null, $default = null, $language_id = false) {- return System\Meta\PostContentMeta::getInstance()->get($post_id, $namespace, $key, $default, $language_id);-}--function getMultiPostContentMeta($post_id, $namespace, $key = null, $default = null, $language_id = false) {- return System\Meta\PostContentMeta::getInstance()->getMulti($post_id, $namespace, $key, $default, $language_id);-}--function getMultiProductContentMeta($product_id, $namespace, $key = null, $default = null, $language_id = false) {- return System\Meta\ProductContentMeta::getInstance()->getMulti($product_id, $namespace, $key, $default, $language_id);-}--function setPostContentMeta($post_id, $namespace, $key = null, $value = null, $language_id = false) {- return System\Meta\PostContentMeta::getInstance()->set($post_id, $namespace, $key, $value, $language_id);-}-function setProductContentMeta($product_id, $namespace, $key = null, $value = null, $language_id = false) {- return System\Meta\ProductContentMeta::getInstance()->set($product_id, $namespace, $key, $value, $language_id);-}--function deletePostContentMeta($post_id, $namespace, $key = null, $language_id = false) {- return System\Meta\PostContentMeta::getInstance()->delete($post_id, $namespace, $key, $language_id);-}--function deleteProductContentMeta($product_id, $namespace, $key = null, $language_id = false) {- return System\Meta\ProductContentMeta::getInstance()->delete($product_id, $namespace, $key, $language_id);-}--function setMultiPostContentMeta($post_id, $meta) {- return System\Meta\PostContentMeta::getInstance()->setMulti($post_id, $meta);-}--function setMultiProductContentMeta($product_id, $meta) {- return System\Meta\ProductContentMeta::getInstance()->setMulti($product_id, $meta);-}--function getCurrentTemplate() {- return System\Core\View :: getInstance()->template();-}--function getUrlRoute($url) {- $urlData = \Vvveb\System\Routes::getUrlData($url);-- return $urlData;-}--function getCurrentUrl() {- return $_SERVER['REQUEST_URI'] ?? '';-}--function adminPath() {- return (V_SUBDIR_INSTALL ? V_SUBDIR_INSTALL : '') . '/' . \Vvveb\config('admin.path', 'admin') . '/';-}--function publicUrlPath() {- $public_path = PUBLIC_PATH;-- if (V_SUBDIR_INSTALL) {- $public_path = str_replace(V_SUBDIR_INSTALL, '', $public_path);- }-- if ($public_path == '/public/' || $public_path == '/public/admin/') {- return PUBLIC_PATH;- } else {- return '/';- }-}--function themeUrlPath() {- $theme = \Vvveb\System\Core\View::getInstance()->getTheme();- //$theme = 'landing';- if (APP == 'app') {- $path = PUBLIC_THEME_PATH . 'themes/' . $theme . '/';- } else {- $path = PUBLIC_THEME_PATH . $theme . '/';- }-- return $path;-}--function escUrl($url) {- return htmlspecialchars($url, ENT_QUOTES, 'UTF-8');-}--function escAttr($attr) {- return htmlspecialchars($attr);-}--function escHtml($url) {- return htmlspecialchars($url);-}--function env($key, $default = null) {- if ($env = getenv($key)) {- return $env;- } else {- return $default;- }-}--function friendlyDate($date) {- $fileformats = [- 1 => function ($i) { return __('%d second', '%d seconds', $i); },- 60 => function ($i) { return __('%d minute', '%d minutes', $i); },- 3600 => function ($i) { return __('%d hour', '%d hours', $i); },- 86400 => function ($i) { return __('%d day', '%d days', $i); },- 604800 => function ($i) { return __('%d week', '%d weeks', $i); },- 2592000 => function ($i) { return __('%d month', '%d months', $i); },- 31536000 => function ($i) { return __('%d year', '%d years', $i); },- 315360000 => function ($i) { return __('%d decade', '%d decades', $i); },- 3153600000 => function ($i) { return __('%d century', '%d centuries', $i); },- ];-- $time_direction = __(' ago');-- if (is_string($date)) {- $date = strtotime($date);- }-- $diff = time() - $date + 10;-- if ($diff < 0) {- $time_direction = __(' from now');- $diff = abs($diff);- }-- $lastTime = 1;- $lastText = $fileformats[1]($diff);-- foreach ($fileformats as $time => $text) {- if ($diff < $time) {- $units = floor($diff / $lastTime);-- return sprintf($lastText($units), $units) . $time_direction;- }- $lastText = $text;- $lastTime = $time;- }-- return $date;-}--/*-Convert var.key1.key2 > var['key1']['key2']-*/-function dotToArrayKey($key) {- //var.key1.key2 > var['key1']['key2']- //var.key1 > var['key1']-- return preg_replace_callback('/\.([-_\w]+)/', function ($matches) {- return "['" . str_replace("'", "\'", $matches[1]) . "']";- }, $key);-}--/*-Convert name[key] > ['name']['key']-*/-function postNameToArrayKey($key) {- $key = str_replace(['][', '[', ']'] , ['.', '.', ''], $key);-- return '[\'' . str_replace('.', '\'][\'', $key) . '\']';-}--/*-Prefix array keys-*/-function prefixArrayKeys($prefix, &$array) {- if (is_array($array)) {- foreach ($array as $k => $v) {- $array["$prefix$k"] = $v;- unset($array[$k]);- }- }-- return $array;-}--function filterText($data) {- return urldecode(filter_var($data, FILTER_SANITIZE_FULL_SPECIAL_CHARS, FILTER_FLAG_ENCODE_HIGH | FILTER_FLAG_ENCODE_LOW));-}--function session($data, $default = null) {- $session = System\Session :: getInstance();-- if (! $session) {- return $default;- }-- if (is_array($data)) {- foreach ($data as $key => $value) {- $session->set($key, $value);- }- } else {- $value = $session->get($data);-- if ($default && $value === null) {- return $default;- }-- return $value;- }-}--/*- * Regex filter to allow only matched content- *- * @param string $regex- * @param string $input- * @param integer $maxInputSize [100]- */-function filter($regex, $input, $maxInputSize = 100) {- $matches = [];-- if (preg_match($regex, substr($input, 0, $maxInputSize), $matches)) {- return $matches[0];- } else {- return false;- }-}--/**- * Shortcut for preg_match to return the matched parameter directly.- *- * @param string $regex- * @param string $input- * @param integer $level [false]- *- * @return mixed- */-function pregMatch($regex, $input, $level = false) {- $matches = [];-- //if (preg_match($regex, $input, $matches, PREG_UNMATCHED_AS_NULL | PREG_PATTERN_ORDER)) {- if (preg_match($regex, $input, $matches, PREG_UNMATCHED_AS_NULL)) {- if ($level !== false) {- return $matches[$level];- }-- return $matches;- } else {- return false;- }-}--/**- * Shortcut for preg_match_all to return the matched parameters directly.- *- * @param string $regex- * @param string $input- * @param integer $level [false]- *- * @return mixed- */-function pregMatchAll($regex, $input, $level = false) {- $matches = [];-- if (preg_match_all($regex, $input, $matches, PREG_UNMATCHED_AS_NULL | PREG_PATTERN_ORDER)) {- if ($level !== false) {- return $matches[$level];- }-- return $matches;- } else {- return false;- }-}--function arrayAllowValues($input, $allowedValues) {- if (! in_array($input, $allowedValues)) {- return null;- } else {- return $input;- }-}--/*- * Get values from multidimensional arrays based on path- * For example for array ['item' => ['desc' => ['name' => 'test']]] the path "item.description.name" will return "test".- *- * */--function arrayPath(array $a, $path, $default = null, $token = '.') {- $p = strtok($path, $token);-- while ($p !== false) {- if (! isset($a[$p])) {- return $default;- }-- $a = $a[$p];- $p = strtok($token);- }-- return $a;-}--function humanReadable($text) {- if (is_string($text)) {- return ucfirst(str_replace(['_', '-', '/', '[', ']', '.'], [' ', ' ', ' - ', ' ', ' ', ' '], trim($text, ' /\-_')));- }-- return $text;-}--function cleanUrl($text, $divider = '-') {- // replace non letter or digits by divider- $text = preg_replace('/[^\pL\d]+/u', $divider, $text);-- // remove unwanted characters- $text = preg_replace('/[^\\-\w]+/', '', $text);-- $text = trim($text, $divider);-- return $text;-}--function slugify($text, $divider = '-') {- if (! $text) {- return $text;- }- // replace non letter or digits by divider- $text = preg_replace('/[^\pL\d]+/u', $divider, $text);-- // transliterate- if (function_exists('iconv')) {- $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);- }-- // remove unwanted characters- $text = preg_replace('/[^-\w]+/', '', $text);-- // trim- $text = trim($text, $divider);-- // remove duplicate divider- $text = preg_replace('/-+/', $divider, $text);-- // lowercase- $text = strtolower($text);-- return $text;-}--if ((!defined('GETTEXT') || GETTEXT == true) && function_exists('_')) {- function __($text, $plural = false, $count = false, $nocache = false) {-- if ($plural) {- $translation = ngettext($text, $plural, $count);- } else {- $translation = gettext($text);- }-- return $translation;- }-} else {- function __($text, $plural = false, $count = false, $nocache = false) {- static $translations;-- if (($translations === null || $nocache) && !isEditor()) {- $translations = [];- $lang = System\Locale::getLanguage();-- $cacheFile = DIR_CACHE . $lang . '-translations.php';-- if (file_exists($cacheFile)) {- $translations = require $cacheFile;- } else {- $folder = DIR_ROOT . 'locale' . DS . $lang . DS . 'LC_MESSAGES' . DS;- if (is_dir($folder)) {- require_once DIR_SYSTEM . 'functions' . DS . 'php-mo.php';-- foreach (['vvveb', 'user'] as $domain) {- $poFile = $folder . $domain . '.po';- if (file_exists($poFile) && ($t = phpmo_parse_po_file($poFile) ?: []) && is_array($t)) {- $translations = array_merge($translations, $t);- }- }-- foreach ($translations as $id => &$msg) {- $msg = $msg['msgstr'];- }-- file_put_contents($cacheFile, '<?php return ' . var_export($translations, true) . ';');- }- }- }-- if (isset($translations[$text])) {- if ($count && $plural) {- $translation = $translations[$text][1] ?? $translations[$text][0] ?? $text;- } else {- $translation = $translations[$text][0] ?? $text;- }- } else {- $translation = $text;- }-- //list($text, $plural, $count, $translation) = System\Event::trigger(__NAMESPACE__, '__', $text, $plural, $count, $translation);-- return $translation;- }-}--function isAdmin() {- return System\User\Admin::current() ? true : false;-}--function cssToXpath($selector) {- //if already xpath don't transform- //if (substr_compare($selector,'vtpl_xpath', 0, 11) == 0) return substr($selector, 12, -1);-- $selector = (string) $selector;-- //convert , to | union operator to allow multiple queries- $selector = str_replace(',', '|', $selector);-- $cssSelector = [- // E > F: Matches any F element that is a child of an element E- '/\s*>\s*/',-- // E + F: Matches any F element immediately preceded by an element- '/\s*\+\s*/',-- // E F: Matches any F element that is a descendant of an E element- '/([a-zA-Z\*="\[\]#._-])\s+([a-zA-Z\*="\[\]#._-])/', //'/([a-zA-Z\*="\[\]#._-])\s+([a-zA-Z\*#._-])/',-- // E:first-child: Matches element E when E is the first child of its parent- '/([a-z#\.]\w*):first-child/',-- // E:nth-child() Matches the nth child element- '/([a-z#\.]\w*):nth-child\((\d+)\)/',-- // E:first: Matches the first element from the set- '/([a-z#\.]\w*):first/',-- // E:nth(2): Matches the nth element from the set- '/([a-z#\.]\w*):nth\((\d+)\)/',-- // E[foo="warning"]: Matches any E element whose "foo" attribute value is exactly equal to "warning"- '/([a-z]\w*)\[([a-z][\w\-_]*)\="([^"]*)"]/',-- // E[foo]: Matches any E element with the "foo" attribute set (whatever the value)- '/([a-z]\w*)\[([a-z][\w_\-]*)\]/',-- // E[!foo]: Matches any E element without the "foo" attribute set- '/([a-z]\w*)\[!([a-z][\w\-_]*)\]/',-- // [foo="warning"]: Matches any element whose "foo" attribute value is exactly equal to "warning"- '/\[([a-z][\w\-_]*)\=\"(.*)\"\]/',-- // [foo*="warning"]: Matches any element whose "foo" attribute value contains the string "warning" and has other attributes- '/(?<=\])\[([a-z][\w\-_]*)\*\=\"([^"]+)\"\]/',-- // [foo*="warning"]: Matches any element whose "foo" attribute value contains the string "warning"- '/\[([a-z][\w\-_]*)\*\=\"([^"]+)\"\]/',-- // [foo^="warning"]: Matches any element whose "foo" attribute value begins with the string "warning"- '/\[([a-z][\w_\-]*)\^\=\"([^"]+)\"\]/',-- // [foo$="warning"]: Matches any element whose "foo" attribute value ends with the string "warning"- '/\[([a-z][\w_\-]*)\$\=\"([^"]+)\"\]/',-- // [foo][baz]: Matches any element with the "foo" attribute set (whatever the value)- '/(?<=\])(?<! )\[([a-z][\w_\-]*)\]/',-- // [foo]: Matches any element with the "foo" attribute set (whatever the value)- '/\[([a-z][\w_\-]*)\]/',-- // element[foo*]: Matches any element that starts with "foo" attribute (whatever the value)- '/(\w+)\[([a-z][\w\-]*)\*\]/',-- // [foo*]: Matches any element that starts with "foo" attribute (whatever the value) and has other attributes- '/(?<=\])\[([a-z][\w\-]*)\*\]/',-- // [foo*]: Matches any element that starts with "foo" attribute (whatever the value) and is a single attribute- '/(?<!\])\[([a-z][\w\-]*)\*\]/',-- // div.warn*: HTML only. The same as DIV[class*="warning"]- '/([a-z]\w*|\*)\.([a-z][\w\-_]*)\*/',-- // div.warning: HTML only. The same as DIV[class~="warning"]- '/([a-z]\w*|\*)\.([a-z][\w\-_]*)+/',-- // .warn*: HTML only. The same as [class*="warning"]- '/\.([a-z][\w\-\_]*)\*/',-- // .warning: HTML only. The same as [class~="warning"]- '/\.([a-z][\w\-\_]*)+/',-- // E#myid: Matches any E element with id-attribute equal to "myid"- '/([a-z]\w*)\#([a-z][\w\-_]*)/',-- // #myid: Matches any E element with id-attribute equal to "myid"- '/\#([a-z][\w\-_]*)/',- ];-- $xpathQuery = [- '/', //element > child- '/following-sibling::*[1]/self::', // element + precedent- '\1//\2', //element descendent- '*[1]/self::\1', //element:first-child- '*[\2]/self::\1', //element:nth-child(2)- '\1[1]', //element:first- '\1[\2]', //element:nth(2)- '\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"]- '*[ contains( concat( " ", @\1, " " ), concat( " ", "\2", " " ) ) ]', //[foo="warning"]- '*[ contains( concat( " ", @\1, " " ), "\2" ) ]', //[foo*="warning"]- '*[ contains( concat( " ", @\1, " " ), concat( " ", "\2", " " ) ) ]', //[foo^="warning"] not implemented- '*[ contains( concat( " ", @\1, " " ), concat( " ", "\2", " " ) ) ]', //[foo$="warning"] not implemented- '[ @\1 ]', //[attribute][attribute]- '*[ @\1 ]', //[attribute]- '\1 [ @*[starts-with(name(), "\2")] ]', //element[attr*]- '[ @*[starts-with(name(), "\1")] ]', //[attr*] - attribute with other attributes- '*[ @*[starts-with(name(), "\1")] ]', //[attr*] - single attribute- '\1[ contains( concat( " ", @class, " " ), concat( " ", "\2") ) ]', //element[class*="string"]- '\1[ contains( concat( " ", @class, " " ), concat( " ", "\2", " " ) ) ]', //element[class~="string"]- '*[ contains( concat( " ", @class, " " ), concat( " ", "\1") ) ]', //[class*="string"]- '*[ contains( concat( " ", @class, " " ), concat( " ", "\1", " " ) ) ]', //element[class~="string"]- '\1[ @id = "\2" ]', //element#id- '*[ @id = "\1" ]', //#id- ];-- $result = (string) '//' . preg_replace($cssSelector, $xpathQuery, $selector);-- return $result;-}--function dashesToCamelCase($string, $dash = '-') {- return str_replace($dash, '', ucwords($string, $dash));-}--function arrayKeysToCamelCase(&$array) {- foreach ($array as $key => &$value) {- if (is_array($value)) {- $value = arrayKeysToCamelCase($value);- }-- $newKey = lcfirst(dashesToCamelCase($key, '_'));-- if ($newKey != $key) {- $array[$newKey] = $value;- unset($array[$key]);- }- }-- return $array;-}--/**- * Remove extra spaces.- * @param mixed $string- *- * @return string- */-function stripExtraSpaces($string) {- foreach (['\t', '\n', '\r', ' '] as $space) {- $string = preg_replace('/(' . $space . ')' . $space . '+/', '\1', $string);- }-- return $string;-}--function tail($filename, $lines = 1000) {- $file = @fopen($filename, 'rb');-- if ($file === false) {- return false;- }-- $buffer = 4096;- $output = '';- $chunk = '';-- @fseek($file, -1, SEEK_END);-- if (fread($file, 1) != "\n") {- $lines -= 1;- }-- while (ftell($file) > 0 && $lines >= 0) {- $seek = min(ftell($file), $buffer);- fseek($file, -$seek, SEEK_CUR);- $output = ($chunk = fread($file, $seek)) . $output;- //fseek($file, -mb_strlen($chunk, '8bit'), SEEK_CUR);- fseek($file, strlen($chunk), SEEK_CUR);- $lines -= substr_count($chunk, "\n");- }-- while ($lines++ < 0) {- $output = substr($output, strpos($output, "\n") + 1);- }-- fclose($file);-- return trim($output);-}--/**- * Return current module name.- *- * @return string- */-function getModuleName() {- return strtolower(\Vvveb\System\Core\FrontController::getModuleName());-}--/**- * Return current action name.- *- * @return string- */-function getActionName() {- return strtolower(\Vvveb\System\Core\FrontController::getActionName());-}--/*- * Inserts a new key/value before the key in the array.- *- * @param $key- * The key to insert before.- * @param $array- * An array to insert in to.- * @param $new_key- * The key to insert.- * @param $new_value- * An value to insert.- *- * @return- * The new array if the key exists, otherwise the unchanged array.- *- * @see arrayInsertAfter()- */-function arrayInsertBefore($key, array &$array, $new_key, $new_value) {- if (array_key_exists($key, $array)) {- $new = [];-- foreach ($array as $k => $value) {- if ($k === $key) {- $new[$new_key] = $new_value;- }- $new[$k] = $value;- }-- return $new;- }-- return $array;-}--/*- * Inserts a new array before the key in the array.- *- * @param $key- * The key to insert before.- * @param $array- * An array to insert in to.- * @param $new_key- * The key to insert.- * @param $new_value- * An value to insert.- *- * @return- * The new array if the key exists, otherwise the unchanged array.- *- * @see arrayInsertAfter()- */-function arrayInsertArrayBefore($key, array &$array, $new_array) {- if (array_key_exists($key, $array)) {- $new = [];-- foreach ($array as $k => $value) {- if ($k === $key) {- $new += $new_array;- }- $new[$k] = $value;- }-- return $new;- }-- return $array;-}--/*- * Inserts a new key/value after the key in the array.- *- * @param $key- * The key to insert after.- * @param $array- * An array to insert in to.- * @param $new_key- * The key to insert.- * @param $new_value- * An value to insert.- *- * @return- * The new array if the key exists, otherwise the unchanged array.- *- * @see arrayInsertBefore()- */-function arrayInsertAfter($key, array &$array, $new_key, $new_value) {- if (array_key_exists($key, $array)) {- $new = [];-- foreach ($array as $k => $value) {- $new[$k] = $value;-- if ($k === $key) {- $new[$new_key] = $new_value;- }- }-- return $new;- }-- return $array;-}--/*- * Inserts a new array after the key in the array.- *- * @param $key- * The key to insert after.- * @param $array- * An array to insert in to.- * @param $new_key- * The key to insert.- * @param $new_value- * An value to insert.- *- * @return- * The new array if the key exists, otherwise the unchanged array.- *- * @see arrayInsertBefore()- */-function arrayInsertArrayAfter($key, array &$array, $new_array) {- if (array_key_exists($key, $array)) {- $new = [];-- foreach ($array as $k => $value) {- $new[$k] = $value;-- if ($k === $key) {- $new += $new_array;- }- }-- return $new;- }-- return $array;-}--//request-function get($key) {- return System\Core\Request::getInstance()->get[$key] ?? false;-}--/**- * Check if the page is loaded in the editor.- *- * @return boolean- */-function isEditor() {- return isset($_GET['r']);-}--function logError($message) {- error_log($message);-}--function getThemeFolderList($theme = false) {- $skipFolders = ['src', 'source', 'backup', 'sections', 'blocks', 'inputs', 'css', 'scss', 'fonts', 'img', 'import', 'node_modules', 'screenshots', 'video', 'js'];-- if (! $theme) {- $theme = \Vvveb\System\Sites::getTheme(SITE_ID) ?? 'default';- }-- $themeFolder = DIR_THEMES . $theme;- $files = glob("$themeFolder/*", GLOB_ONLYDIR);- $pages['/'] = ['name' => '/', 'title' => '/', 'filename' => '/', 'file' => '/', 'path' => '/', 'folder' => $theme];-- foreach ($files as $file) {- $folder = preg_replace('@^.*/themes/[^/]+/@', '', $file);- $filename = basename($file);-- if (in_array($folder, $skipFolders)) {- continue;- }-- //$path = PUBLIC_PATH . "themes/$theme/$folder";-- $pages[$file] = ['name' => $filename, 'title' => "/$filename", 'filename' => $filename, 'file' => $filename, 'folder' => $theme];- }-- return $pages;-}--function getFieldTypes() {- return- [- 'basic' => [- 'text' => [- 'name' => __('Text'),- 'icon' => 'icon-text-outline',- ],- 'textarea' => [- 'name' => __('Textarea'),- 'icon' => 'icon-document-text-outline',- ],- 'number' => [- 'name' => __('Number'),- 'icon' => 'icon-document-text-outline',- ],- 'range' => [- 'name' => __('Range'),- 'icon' => 'icon-git-commit-outline',- ],- 'email' => [- 'name' => __('Email'),- 'icon' => 'icon-mail-outline',- ],- 'url' => [- 'name' => __('Url'),- 'icon' => 'icon-link-outline',- ],- 'tel' => [- 'name' => __('Telephone'),- 'icon' => 'icon-call-outline',- ],- 'password' => [- 'name' => __('Password'),- 'icon' => 'icon-lock-open-outline',- ],- 'select' => [- 'name' => __('Select'),- 'icon' => 'icon-chevron-down-circle-outline',- ],- ],- 'content' => [- 'image' => [- 'name' => __('Image'),- 'icon' => 'icon-image-outline',- ],- 'file' => [- 'name' => __('File'),- 'icon' => 'icon-document-outline',- ],- 'wysiwyg' => [- 'name' => __('Wysiwyg Editor'),- 'icon' => 'icon-create-outline',- ],- 'oembed' => [- 'name' => __('oEmbed'),- 'icon' => 'icon-videocam-outline',- ],- 'gallery' => [- 'name' => __('Gallery'),- 'icon' => 'icon-images-outline',- ],- ],- 'choice' => [- 'select' => [- 'name' => __('Select'),- 'icon' => 'icon-chevron-down-circle-outline',- ],- 'checkbox' => [- 'name' => __('Checkbox'),- 'icon' => 'icon-checkbox-outline',- ],- 'radio' => [- 'name' => __('Radio Button'),- 'icon' => 'icon-checkmark-circle-outline',- ],- 'toggle' => [- 'name' => __('Toggle'),- 'icon' => 'icon-toggle-outline',- ],- ],- 'relational' => [- 'link' => [- 'name' => __('Link'),- 'icon' => 'icon-link-outline',- ],- 'post' => [- 'name' => __('Post'),- 'icon' => 'icon-document-text-outline',- ],- 'product' => [- 'name' => __('Product'),- 'icon' => 'icon-cube-outline',- ],- 'relationship' => [- 'name' => __('Relationship'),- 'icon' => 'icon-link-outline',- ],- 'taxonomy' => [- 'name' => __('Taxonomy'),- 'icon' => 'icon-apps-outline',- ],- 'user' => [- 'name' => __('User'),- 'icon' => 'icon-person-outline',- ],- ],- 'widgets' => [- 'google_map' => [- 'name' => __('Google Map'),- 'icon' => 'icon-map-outline',- ],- 'color' => [- 'name' => __('Color'),- 'icon' => 'icon-color-palette-outline',- ],- 'time' => [- 'name' => __('Time'),- 'icon' => 'icon-time-outline',- ],- 'date' => [- 'name' => __('Date'),- 'icon' => 'icon-today-outline',- ],- 'date_time' => [- 'name' => __('Date time'),- 'icon' => 'icon-calendar-clear-outline',- ],- 'month' => [- 'name' => __('Month'),- 'icon' => 'icon-calendar-outline',- ],- 'week' => [- 'name' => __('week'),- 'icon' => 'icon-calendar-number-outline',- ],- ],- 'advanced' => [- 'message' => [- 'name' => __('Message'),- 'icon' => 'icon-chevron-down-circle-outline',- ],- 'accordion' => [- 'name' => __('Accordion'),- 'icon' => 'icon-chevron-down-circle-outline',- ],- 'tab' => [- 'name' => __('Tab'),- 'icon' => 'icon-chevron-down-circle-outline',- ],- ],- ];-}--function getDefaultTemplateList() {- return [- 'index.html',- 'index.coming-soon.html',- 'index.maintenance.html',- 'blank.html',- 'error404.html',- 'error500.html',- 'contact.html',- 'search/index.html',- 'content/post.html',- 'content/page.html',- 'content/index.html',- 'content/category.html',- 'content/tag.html',- 'product/index.html',- 'product/product.html',- 'product/category.html',- ];-}--function getTemplateList($theme = null, $skip = []) {- $friendlyNames = [- 'index' => ['name' => __('Home page'), 'description' => __('Website homepage'), 'global' => true],- 'index.coming-soon' => ['name' => __('Coming soon'), 'description' => __('Coming soon message page'), 'global' => true],- 'index.maintenance' => ['name' => __('Under maintenance'), 'description' => __('Website under maintenance message page'), 'global' => true],- 'contact' => ['name' => __('Contact us page'), 'description' => __('Contact us page')],- 'blank' => ['name' => __('Blank page'), 'description' => __('Template page used for new pages')],- 'product' => ['name' => __('Product page'), 'description' => __('Used to display a product'), 'editor' => ['template' => 'product'], 'global' => true],- 'error404' => ['name' => __('Page not found'), 'description' => __('Shows when a page is not available'), 'global' => true],- 'error500' => ['name' => __('Server error'), 'description' => __('Site error display page'), 'global' => true],- 'content-index' => ['name' => __('Blog homepage'), 'description' => __('Blog page with latest posts'), 'global' => true],- 'content-post' => ['name' => __('Blog post'), 'description' => __('Blog post'), 'editor' => ['template' => 'post'], 'global' => true],- 'content-page' => ['name' => __('Page'), 'description' => __('Page'), 'editor' => ['template' => 'page'], 'global' => true],- 'product-index' => ['name' => __('Shop page'), 'description' => __('Shop homepage'), 'global' => true],- 'search-index' => ['name' => __('Search page'), 'description' => __('Search page'), 'global' => true],- 'user-index' => ['name' => __('Dashboard'), 'description' => __('User dashboard'), 'global' => true],- ];-- $skipFolders = array_merge(['src', 'source', 'backup', 'sections', 'blocks', 'inputs', 'css', 'scss', 'screenshots', 'locale', 'node_modules'], $skip);-- if (! $theme) {- $theme = \Vvveb\System\Sites::getTheme(SITE_ID) ?? 'default';- }- $pages = [];- $themeFolder = DIR_THEMES . $theme;- //$files = glob("$themeFolder/{,*/*/,*/}*.html", GLOB_BRACE);- $glob = ['', '*/*/', '*/'];- $files = globBrace($themeFolder . DS, $glob, '*.html');-- foreach ($files as $file) {- $file = preg_replace('@^.*[\\\/]themes[\\\/][^\\\/]+[\\\/]@', '', $file);- $filename = basename($file);-- $folder = \Vvveb\System\Functions\Str::match('@(\w+)/.*?$@', $file) ?? DS;- $path = \Vvveb\System\Functions\Str::match('@(\w+)/.*?$@', $file);-- if (in_array($folder, $skipFolders)) {- continue;- }- $name = $title = str_replace('.html', '', $filename);- $description = '';- $name = (! empty($folder) && $folder != DS) ? "$folder-$name" : $name;-- if (isset($friendlyNames[$name])) {- if (isset($friendlyNames[$name]['description'])) {- $description = $friendlyNames[$name]['description'];- }-- $title = $friendlyNames[$name]['name'];- }-- $url = PUBLIC_PATH . "themes/$theme/$file";- $title = str_replace('index', 'home', $title);-- $pages[$name] = ['name' => $name, 'filename' => $filename, 'file' => $file, 'url' => $url, 'title' => humanReadable($title), 'folder' => $path, 'description' => $description, 'global' => $friendlyNames[$name]['global'] ?? false];-- if (isset($friendlyNames[$name]['editor'])) {- $pages[$name]['editor'] = $friendlyNames[$name]['editor'];- }- }-- //ksort($pages);-- return $pages;-}--function sanitizeFileName($file, $normalizePath = true) {- if (! $file) {- return $file;- }-- //remove null bytes- $file = str_replace(chr(0), '', $file);- //sanitize, remove double dot .. and remove get parameters if any- $prev = '';- while ($prev != $file) {- $prev = $file;- $file = preg_replace('@\?.*$|\.{2,}|[^\w\-\./\\\]@' , '', $file);- }- //replace directory separators with OS specific separator- if ($normalizePath) {- $file = str_replace(['\\', '/'], DS, $file);- }-- return $file;-}--function formatBytes($bytes) {- $i = 0;- $units = ['', 'K', 'M', 'G', 'T', 'P', 'E'];-- while (($remainder = ($bytes / 1024)) > 1) {- $bytes = $remainder;- $i++;- }-- return round($bytes, 2) . ' ' . $units[$i] . 'B';-}--function parseQuantity($string) {- if (function_exists('\ini_parse_quantity')) {- return \ini_parse_quantity($string);- }-- $string = trim($string);- $multiplier = lcfirst($string[strlen($string) - 1]);- $number = intval($string);-- switch ($multiplier) {- case 'k':- return $number * 1024;-- case 'm':- return $number * 1048576;-- case 'g':- return $number * 1073741824;- }-- return $number;-}--function isController($name, $app = APP) {- $file = DIR_ROOT . $app . DS . 'controller' . DS . strtolower($name) . '.php';- $exists = file_exists($file);-- return $exists;-}--function isModel($name, $app = APP) {- $file = DIR_ROOT . $app . DS . 'sql' . DS . DB_ENGINE . DS . $name . '.sql';- $exists = file_exists($file);-- return $exists;-}--function model($model) {- $modelClass = 'Vvveb\Sql\\' . ucwords($model) . 'SQL';-- return new $modelClass();-}--function controller($name) {- $controllerClass = 'Vvveb\Controller\\' . ucwords($name);-- return new $controllerClass();-}--function fieldTypeClass($fieldType) {- $field = ucfirst($fieldType);- $fieldClass = "Vvveb\System\Fields\\$fieldType";-- if (! class_exists($fieldClass)) {- return;- }-- return $fieldClass;-}--function postTypes($type) {- $defaultTypes = [- 'post' => [- 'post' => [- 'name' => 'Post',- 'source' => 'default',- 'site_id' => '0',- 'type' => 'post',- 'plural' => 'posts',- 'icon' => 'icon-document-text-outline',- 'comments'=> true,- ],- 'page' => [- 'name' => 'Page',- 'source' => 'default',- 'site_id' => '0',- 'type' => 'page',- 'plural' => 'pages',- 'icon' => 'icon-document-outline',- 'comments'=> false,- ],- ],- 'product' => [- 'product' => [- 'name' => 'Product',- 'type' => 'product',- 'site_id' => '0',- 'source' => 'default',- 'plural' => 'products',- 'icon' => 'icon-cube-outline',- ],- ],- ];-- $default = $defaultTypes[$type] ?? [];- $typeName = ucfirst($type);- list($pluginTypes) = System\Event::trigger('Vvveb\postTypes', "custom$typeName", []);- array_walk($pluginTypes, function (&$type,$key) {- $type['source'] = 'plugin';- $type['name'] = ucfirst($key);- });-- $userTypes = getSetting($type, 'types', []);-- $params = ['module' => "settings/{$type}-type"];- $paramsList = ['module' => "settings/{$type}-types"];-- array_walk($userTypes, function (&$type,$key) use ($params, $paramsList) {- $type['source'] = 'user';- $type['name'] = ucfirst($key);- $type['url'] = \Vvveb\url($params + ['type' => $type['type']]);- $type['delete-url'] = \Vvveb\url($paramsList + ['action' => 'delete', 'type[]' => $type['type']]);- });-- $types = $default + $pluginTypes + $userTypes;-- return $types;-}--function d(...$variables) {- foreach ($variables as $variable) {- echo highlight_string("<?php\n" . var_export($variable, true), true);- }-}--function dd(...$variables) {- foreach ($variables as $variable) {- echo highlight_string("<?php\n" . var_export($variable, true), true);- }-- die();-}--function encrypt($key, $value, $cipher = 'aes256', $digest = 'sha256', $tag = null, $aad = '', $tag_length = 16) {- $key = openssl_digest($key, $digest, true);- $iv_length = openssl_cipher_iv_length($cipher);- $iv = openssl_random_pseudo_bytes($iv_length);-- return base64_encode($iv . openssl_encrypt($value, $cipher, $key, OPENSSL_RAW_DATA, $iv, $tag, $aad, $tag_length));-}--function decrypt($key, $value, $cipher = 'aes256', $digest = 'sha256', $tag = null, $aad = '') {- $result = false;-- $key = openssl_digest($key, $digest, true);- $iv_length = openssl_cipher_iv_length($cipher);- $value = base64_decode($value);- $iv = substr($value, 0, $iv_length);- $value = substr($value, $iv_length);-- if (strlen($iv) == $iv_length) {- $result = openssl_decrypt($value, $cipher, $key, OPENSSL_RAW_DATA, $iv, $tag, $aad);- }-- return $result;-}--function camelToUnderscore($string, $us = '-') {- return strtolower(preg_replace(- '/(?<=\d)(?=[A-Za-z])|(?<=[A-Za-z])(?=\d)|(?<=[a-z])(?=[A-Z])/', $us, $string));-}--function arrayKeysToUnderscore(&$array, $us = '-') {- foreach ($array as $key => &$value) {- if (is_array($value)) {- $value = arrayKeysToUnderscore($value, $us);- }-- $newKey = camelToUnderscore($key, $us);-- if ($newKey != $key) {- $array[$newKey] = $value;- unset($array[$key]);- }- }-- return $array;-}--function stripTags($string, $tags = ['script', 'iframe', 'applet']) {- if ($string && $tags) {- foreach ($tags as $tag) {- $string = preg_replace("@<\s*$tag.*?>.*?</$tag\s*>@im", '', $string);- }- }-- return $string;-}--function stripTagsArray($array, $tags) {- if (is_array($array) && $tags) {- array_map($array, function ($key, $value) {- return stripTags($value);- });- }-- return $array;-}--function stripChars($string, $chars = ['(', ')', '{', '}', ':', '<', '>']) {- return str_replace($chars, '', $string);-}--function sanitizeHTML($string) {- if (! is_string($string)) {- return $string;- }-- // Fix &entity\n;- //add <> before tag entities to allow regex matching- $string = str_replace(['<', '>'], ['<<', '>>'], $string);- $string = str_replace(['&', '<', '>'], ['&amp;', '&lt;', '&gt;'], $string);- $string = preg_replace('/(&#*\w+)[\x00-\x20]+;/u', '$1;', $string);- $string = preg_replace('/(&#x*[0-9A-F]+);*/iu', '$1;', $string);- $string = html_entity_decode($string, ENT_COMPAT, 'UTF-8');-- // Remove any attribute starting with "on" or xmlns- $string = preg_replace('#(<[^>]+?[\x00-\x20"\'/])(?:on|xmlns)[^>]*+>#iu', '$1>', $string);- $string = preg_replace('#[\x00-\x20"\'/](on|xmlns)[:\w]+[\x00-\x20"\'/]*=[\x00-\x20"\'/]*([\'"]+).+?\2#iu', '', $string);-- // Remove javascript: and vbscript: protocols- $string = preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([`\'"]*)[\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2nojavascript...', $string);- $string = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*v[\x00-\x20]*b[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2novbscript...', $string);- $string = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#u', '$1=$2nomozbinding...', $string);-- // Only works in IE: <span style="width: expression(alert('Ping!'));"></span>- $string = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?expression[\x00-\x20]*\([^>]*+>#i', '$1>', $string);- $string = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?behaviour[\x00-\x20]*\([^>]*+>#i', '$1>', $string);- $string = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:*[^>]*+>#iu', '$1>', $string);-- // Remove namespaced elements (we do not need them)- $string = preg_replace('#</*\w+:\w[^>]*+>#i', '', $string);-- do {- // Remove really unwanted tags- $old_data = $string;- //$string = preg_replace('#</*(?:applet|b(?:ase|gsound|link)|embed|frame(?:set)?|i(?:frame|layer)|l(?:ayer|ink)|meta|object|s(?:cript|tyle)|title|xml)[^>]*+>#i', '', $string);- $string = preg_replace('#</*(?:applet|b(?:ase|gsound|link)|embed|frame(?:set)?|i(?:layer)|l(?:ayer|ink)|meta|object|s(?:cript|tyle)|title|xml)[^>]*+>#i', '', $string);- } while ($old_data !== $string);-- //restore entities- $string = str_replace(['<<', '>>'], ['<', '>'], $string);- return $string;-}---function siteSettings($site_id = SITE_ID, $language_id = false) {- $cache = System\Cache::getInstance();- $site = $cache->cache(APP,'site.' . $site_id, function () use ($site_id) {- $siteSql = new Sql\SiteSQL();- $site = $siteSql->get(['site_id' => $site_id]);-- if ($site && isset($site['settings'])) {- $settings = json_decode($site['settings'], true);- $siteData = $siteSql->getSiteData(['site' => $settings]);-- foreach (['favicon', 'logo', 'logo-sticky', 'logo-dark', 'logo-dark-sticky', 'webbanner'] as $img) {- if (isset($settings[$img])) {- $settings["$img-src"] = $settings[$img];- $settings[$img] = System\Images::image($settings[$img], '');- }- }-- return $settings + $siteData;- }-- return [];- }, 259200);-- if ($language_id && $site) {- $site['description'] = $site['description'][$language_id] ?? $site['description'][1] ?? '';- }-- return $site;-}--/**- * Check php code for syntax errors, return false on errors.- *- * @param string $source- * @return bool- */-function checkPhpSyntax($source) {- $tokens = false;-- if (function_exists('token_get_all')) {- try {- $tokens = token_get_all($source, TOKEN_PARSE);- } catch (\ParseError $e) {- }- }-- return $tokens ? true : false;-}--function truncateWords($text, $limit) {- $parts = preg_split('/(\s+)/ms', substr($text, 0, $limit * 2), 0, PREG_SPLIT_DELIM_CAPTURE);- $partsCount = count($parts);-- $length = 0;- $lastPart = 0;- for (; $lastPart < $partsCount; ++$lastPart) {- $partlen = strlen($parts[$lastPart]);- $length += $partlen;- if ($length >= $limit) {- //don't include less than two letter last word or spaces- $partlen = strlen($parts[$lastPart - 1]);- while (($partlen < 3) && $lastPart > 3) {- $lastPart--;- $partlen = strlen($parts[$lastPart - 1]);- }- break;- }- }-- return implode(array_slice($parts, 0, $lastPart));-- //return preg_replace('/((\w+\W*){' . ($limit - 1) . '}(\w+))(.*)/m', '${1}', $text);-}-/**- * Send email using template.- *- * @param string|array $to- * @param mixed $template- * @param string $subject- * @param array $data- * @param mixed $config- * @param null|mixed $app- * @param mixed $site_id- * @return bool- */-function email($to, $subject, $template, $data = [], $config = [], $app = null, $site_id = SITE_ID) {- $email = System\Email::getInstance();-- if (is_array($template)) {- $html = $template['html'] ?? '';- $txt = $template['txt'] ?? '';- } else {- $htmlView = new System\Core\View($app);- $htmlView->setTheme();- $htmlView->set($data);- //get email html template- $htmlView->template("email/$template.html");- $html = $htmlView->render(true, false, true);-- //get email text template- $txtView = new System\Core\View($app);- $txtView->setTheme();- $txtView->set($data);- $txtView->template("email/$template.txt.html");- $txt = $txtView->render(true, false, true);- $txt = htmlToText($txt);- }-- //get site contact email for sender and reply to- $site = siteSettings($site_id, session('language_id') ?? 1);- $sender = $config['sender'] ?? $site['description']['title'];- $from = $config['from'] ?? $site['contact-email'];- $reply = $config['reply'] ?? $site['contact-email'];-- $email->setHtml($html);- $email->setText($txt);- $email->setTo($to);- $email->setSender($sender);- $email->setFrom($from);- $email->setReplyTo($reply);- $email->setSubject($subject);-- return $email->send();-}--/* Recursive rmdir */-function rrmdir($src, $skip = []) {- if (! is_dir($src)) {- return false;- }-- $dir = @opendir($src);-- $result = false;-- if ($dir) {- while (false !== ($file = readdir($dir))) {- $full = $src . DS . $file;-- if (($file != '.') &&- ($file != '..')/* &&- (! in_array($full, $skip))*/) {- if (is_dir($full)) {- $result = rrmdir($full);- } else {- $result = @unlink($full);- }-- if (! $result) {- break;- }- }- }-- closedir($dir);-- return rmdir($src);- }-- return result;-}--/* Recursive copy */-function rcopy($src, $dst, $skip = [], $overwrite = true) {- if ($overwrite && file_exists($dst)) {- //rrmdir($dst);- }-- $result = true;-- if (is_dir($src)) {- if (! file_exists($dst)) {- $result = @mkdir($dst);-- if (! $result) {- return false;- }- }-- @chmod($dst, 0755);-- $files = scandir($src);-- foreach ($files as $file) {- $full = $src . DS . $file;-- if ($file != '.' &&- $file != '..' &&- ! in_array($file, $skip)) {- if (is_dir($full)) {- $result = rcopy($full, $dst . DS . $file);- } else {- $result = @copy($full, $dst . DS . $file);-- if (! $result) {- if (@chmod($dst . DS . $file, 0644)) {- $result = @copy($full, $dst . DS . $file);- }- }- }-- if (! $result) {- return false;- }- }- }- } else {- if (file_exists($src)) {- $result = @copy($src, $dst);-- if (! $result) {- if (@chmod($dst, 0644)) {- $result = copy($src, $dst);- }- }-- if (! $result) {- return false;- }- }- }-- return $result;-}--/* Recursive copy */-function rrename($src, $dst, $skip = []) {- if (file_exists($dst)) {- rrmdir($dst);- }-- if (is_dir($src)) {- mkdir($dst);- $files = scandir($src);-- foreach ($files as $file) {- if ($file != '.' &&- $file != '..' &&- ! in_array($file, $skip)) {- //rrename("$src/$file", "$dst/$file");- rename("$src/$file", "$dst/$file");- }- }- } else {- if (file_exists($src)) {- rename($src, $dst);- }- }-}--function download($url) {- $result = false;-- $url = html_entity_decode($url);- $ips = validateUrl($url);-- if (! $ips) {- return;- }-- if (function_exists('curl_init')) {- $ch = curl_init($url);-- if ($ch) {- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);- curl_setopt($ch, CURLOPT_RESOLVE, $ips);- curl_setopt($ch, CURLOPT_FAILONERROR, true);- curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);- curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT'] ?? 'Vvveb ' . V_VERSION);- $result = curl_exec($ch);- $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);-- if (PHP_MAJOR_VERSION < 8) {- curl_close($ch);- }-- if ($httpcode != 200) {- return;- }- }- } else {- if (ini_get('allow_url_fopen') == '1') {- $context_options = [- 'http' => [- 'timeout' => 5,- 'ignore_errors' => 1,- ],- ];- $context = stream_context_create($context_options);- $result = file_get_contents($url, 'r', $context);- }- }-- return $result;-}--function validateUrl($url) {- $p = parse_url($url);- $scheme = $p['scheme'] ?? 'https';- $port = $p['port'] ?? ($scheme === 'http' ? '80' : '443');-- if (! $p || ! in_array($scheme, ['http', 'https'], true) || ! in_array($port, ['80', '443'], true) || empty($p['host'])) {- return [];- }-- if (($scheme === 'http' && $port !== '80') || ($scheme === 'https' && $port !== '443')) {- return [];- }-- $ips = gethostbynamel($p['host']) ?: [];-- $results = [];- foreach ($ips as $ip) {- $results[] = $p['host'] . ':' . $port . ':[' . $ip . ']';-- if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {- return []; // private / reserved / loopback / link-local- }- }-- return $results;-}--function getUrl($url, $cache = true, $expire = 604800, $timeout = 5, $exception = true) {- $cacheDriver = System\Cache :: getInstance();- $cacheKey = md5($url);- $result = false;-- $ips = validateUrl($url);-- if (! $ips) {- return;- }-- if ($cache && ($result = $cacheDriver->get('url', $cacheKey))) {- return $result;- } else {- $result = false;- $url = html_entity_decode($url);- //try with curl- if (function_exists('curl_init')) {- $ch = curl_init($url);-- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);- curl_setopt($ch, CURLOPT_RESOLVE, $ips);- curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);- curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);- curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT'] ?? 'Vvveb ' . V_VERSION);-- if (DEBUG) {- curl_setopt($ch, CURLOPT_VERBOSE, true);- $streamVerboseHandle = fopen('php://temp', 'w+');- curl_setopt($ch, CURLOPT_STDERR, $streamVerboseHandle);- }-- $result = curl_exec($ch);-- if ($result) {- $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);- if ($httpcode != 200) {- return;- }-- if ($cache) {- $cacheDriver->set('url', $cacheKey, $result);- }-- return $result;- } else {- if ($exception) {- $message = 'Curl error: ' . curl_errno($ch) . ' - ' . curl_error($ch);-- if (DEBUG) {- $message .= "\n" . print_r(curl_getinfo($ch), 1);- rewind($streamVerboseHandle);- $message .= "\n" . stream_get_contents($streamVerboseHandle);- }-- throw new \Exception($message);- }- }-- if (PHP_MAJOR_VERSION < 8) {- curl_close($ch);- }- } else {- //try with file get contents- if (ini_get('allow_url_fopen') == '1') {- $context_options = [- 'http' => [- 'timeout' => $timeout,- 'ignore_errors' => 1,- ],- ];-- $context = stream_context_create($context_options);-- if ($exception) {- $result = file_get_contents($url, false, $context);- } else {- $result = @file_get_contents($url, false, $context);- }- }-- if ($result) {- if ($cache) {- $cacheDriver->set('url', $cacheKey, $result);- }-- return $result;- }- }- }-- return $result;-}--function unzip($file) {- // get the absolute path to $file- $path = pathinfo(realpath($file), PATHINFO_DIRNAME);-- $zip = new \ZipArchive();- $res = $zip->open($file);-- if ($res === true) {- $zip->extractTo($path);- $zip->close();-- return true;- }-- return false;-}--function htmlToText($html) {- $html = preg_replace('/\s+/', ' ', $html);- $html = str_replace('<br>', "\n", $html);- //add new line for block elements- $html = preg_replace('/<(div|p|li|hr|pre|blockquote|section|h\d+)/', "\n<$1", $html);-- return trim(strip_tags($html));-}--function nl2p($string) {- $paragraphs = '';-- foreach (explode("\n\n", $string) as $line) {- if (trim($line)) {- $paragraphs .= "<p>$line</p>";- }- }-- return $paragraphs;-}--function orderStatusBadgeClass($order_status_id = 1) {- $classes = [- 1 => 'bg-primary-subtle text-body', //pending- 2 => 'bg-info-subtle text-body', //processing- 3 => 'bg-primary', //processed- 4 => 'bg-success', //complete- 5 => 'bg-danger', //canceled- 6 => 'bg-secondary', //archived- 7 => 'bg-warning', //requires_action- ];-- return $classes[$order_status_id] ?? 'bg-warning text-dark';-}--function paymentStatusBadgeClass($payment_status_id = 1) {- $classes = [- 1 => 'bg-warning-subtle text-body', //not_paid- 2 => 'bg-success-subtle text-body', //awaiting- 3 => 'bg-danger-subtle text-body', //captured- 4 => 'bg-success', //paid- 5 => 'bg-danger', //canceled- 6 => 'bg-danger', //refunded- 7 => 'bg-danger', //partially_refunded- 8 => 'bg-danger', //chargeback- 9 => 'bg-danger', //requires_action- 10 => 'bg-danger', //fraud- ];-- return $classes[$payment_status_id] ?? 'bg-warning text-dark';-}--function shippingStatusBadgeClass($shipping_status_id = 1) {- $classes = [- 1 => 'bg-warning-subtle text-body', //not_fulfilled- 2 => 'bg-success-subtle text-body', //fulfilled- 3 => 'bg-success-subtle text-body', //partially_fulfilled- 4 => 'bg-success', //shipped- 5 => 'bg-success-subtle text-body', //partially_shipped- 6 => 'bg-danger-subtle text-body', //returned- 7 => 'bg-danger-subtle text-body', //partially_returned- 8 => 'bg-success', //delivered- 9 => 'bg-danger', //canceled- 10 => 'bg-warning', //requires_action- ];-- return $classes[$shipping_status_id] ?? 'bg-warning text-dark';-}--function commentStatusBadgeClass($status = 0) {- $classes = [- 0 => 'bg-primary-subtle text-body', //pending- 1 => 'bg-success-subtle text-body', //approved- 2 => 'bg-warning-subtle text-body', //spam- 3 => 'bg-danger-subtle text-body', //trash- ];-- return $classes[$status] ?? 'bg-secondary-subtle text-dark';-}--function globBrace($path, $glob, $filename = '') {- //$glob = ['*','*/*','*/*/*'];- $files = [];-- if (defined('GLOB_BRACE')) {- $path .= '{' . implode(',', $glob) . '}' . $filename;- $files = glob($path, GLOB_BRACE);- } else {- foreach ($glob as $pattern) {- $files = array_merge($files, glob($path . DS . $pattern . $filename));- }- }-- return $files;-}--function isSecure() {- return- (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')- || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')- || ($_SERVER['SERVER_PORT'] ?? 80) == 443;-}--function randomDigits($length) {- $result = '';-- for ($i = 0; $i < $length; $i++) {- $result .= random_int(0, 9);- }-- return $result;-}--function invoiceFormat($format, $data) {- if (! $format) {- return '';- }- $data += ['date_added' => time(), 'year' => date('Y'), 'year2' => date('y'), 'month_name' => date('M'), 'month' => date('m'), 'day' => date('d')];-- return preg_replace_callback('/{(.+?)}/', function ($matches) use ($data) {- $key = $matches[1];-- if (isset($data[$key])) {- return $data[$key];- }-- if (strpos($key, 'rand-no-') !== false) {- $length = (int) str_replace('rand-no-', '', $key);-- return randomDigits($length);- }-- if (strpos($key, 'rand-str-') !== false) {- $length = (int) str_replace('rand-str-', '', $key);-- return strtoupper(System\Functions\Str::random($length));- }-- return $matches[0];- }, $format);-}--/*-remove <?xml declaration to avoid issues with php short start tag-*/-function xmlStripVersionDeclr($xmlString) {- $xmlString = preg_replace('/<\?xml\s+version[^\?]+\?>\s*/', '', $xmlString ?? '');- //xml stylesheet- $xmlString = str_replace('<?xml-', '<?php echo \'<?xml-\';?>', $xmlString);-- return $xmlString;-}--function array2xml($array, $xml = false) {- if ($xml === false) {- $xml = new \SimpleXMLElement('<root/>');- }-- foreach ($array as $key => $value) {- $attributes = [];- $processAttr = function (&$key) use (&$attributes) {- $i = 0;- $start = 0;-- if ($key) {- while (($start = strpos($key, '@@', $start))) {- $i++;- $start += 2;- $end = (int)strpos($key,' ', $start);- $name = substr($key, $start, $end ? $end - $start : null);-- if ($end == 0) {- $start += strlen($name);- } else {- $start = (int)$end;- }-- if ($name) {- $name = explode('=', $name);- $attributes[$name[0]] = trim($name[1] ?? '', '\'"');- }- }-- $key = strstr($key, ' @@', true) ?: $key;- }- };-- $processAttr($key);-- if (is_array($value) || is_object($value)) {- $node = $xml->addChild($key);-- if ($attributes) {- foreach ($attributes as $key => $val) {- $node->addAttribute($key, htmlspecialchars($val));- }- }- array2xml($value, $node);- } else {- if (substr_compare($key, '--xmlattr', -9, 9) === 0) {- $key = substr($key, 0, -9);- $xml->addAttribute($key, htmlspecialchars($value));- } else {- $processAttr($value);-- if ($value && is_string($value)) {- $value = htmlspecialchars($value);- }- $node = $xml->addChild($key, $value);-- if ($attributes) {- foreach ($attributes as $key => $val) {- $node->addAttribute($key, $val);- }- }- }- }- }-- $xmlString = $xml->asXML();-- return xmlStripVersionDeclr($xmlString);-}--function removeJsonComments($json) {- $json = preg_replace('@^\s*//.*([\r\n]|\s)*|^\s*/\*([\r\n]|.)*?\*/([\r\n]|\s)*@m', '', $json);-- return $json;-}--function encodeXmlName($name) {- $len = strlen($name);- $newName = '';-- for ($i = 0; $i < $len; $i++) {- $char = $name[$i];- $code = ord($char);-- // = @ _ - . A-Z a-z 0-9- if (! ($code == 32 || $code == 34 || $code == 61 || $code == 64 || $code == 95 || $code == 45 || $code == 46 || ($code <= 90 && $code >= 65) || ($code <= 122 && $code >= 97) || ($code <= 57 && $code >= 48))) {- $char = '_x' . sprintf('%03d', $code) . '_';- }-- $newName .= $char;- }-- return $newName;-}--function decodeXmlName($name) {- return preg_replace_callback('/_x(\d+)_/',function ($matches) {- return chr(ltrim($matches[1], '0'));- }, $name);-}--function prepareJson($array) {- if (! is_array($array)) {- //return;- }- $helper = [];-- foreach ($array as $key => $value) {- if (is_numeric($key)) {- $key = 'n--' . $key;- }-- if ($key[0] == '@') {- if ($key[1] == '@') {- $key = substr($key, 2) . '--xmlattr';- } else {- $key = substr($key, 1) . '--attr';- }- }-- if (strpos($key, '@')) {- }-- //keep empty arrays as array type- if (is_object($value) && ! $value) {- $key .= '--object';- } else {- if (is_array($value) && ! $value) {- $key .= '--array';- }- }-- //keep boolean type- if (is_bool($value)) {- $key .= '--boolean';- }-- //keep int type- if (is_int($value)) {- $key .= '--int';- }-- //keep null type- if ($value === null) {- $key .= '--null';- }-- $key = encodeXmlName(trim($key));-- $helper[$key] = is_array($value) ? prepareJson($value) : $value;- }-- return $helper;-}--function reconstructJson(&$array, $removeAttrs = false) {- if (! is_iterable($array)) {- return;- }- $helper = [];- $array = (array)$array;-- foreach ($array as $key => $value) {- if ($removeAttrs && $key == '@attributes') {- continue;- }-- $key = decodeXmlName($key);-- if (substr_compare($key, '--array', -7, 7) === 0) {- $key = substr($key, 0, -7);- $value = (array)$value;- } else {- if ($value === null) {- $value = '';- }- }-- if (substr_compare($key, '--boolean', -9, 9) === 0) {- $key = substr($key, 0, -9);- $value = (bool)$value;- }-- if (substr_compare($key, '--null', -6, 6) === 0) {- $key = substr($key, 0, -6);- $value = null;- }-- if (substr_compare($key, '--int', -5, 5) === 0) {- $key = substr($key, 0, -5);- $value = (int)$value;- }-- if (substr_compare($key, '--object', -8, 8) === 0) {- $key = substr($key, 0, -8);- $value = (object)$value;- }-- if (substr_compare($key, 'n--', 0, 3) === 0) {- $newkey = substr($key, 3);-- if (is_numeric($newkey)) {- $key = intval($newkey);- }- }-- if (substr_compare($key, '--xmlattr', -9, 9) === 0) {- $key = '@@' . substr($key, 0, -9);- }-- if (substr_compare($key, '--attr', -6, 6) === 0) {- $key = '@' . substr($key, 0, -6);- }-- $helper[$key] = (is_iterable($value)) ? reconstructJson($value, $removeAttrs) : $value;- }-- return $helper;-}--function fileUploadErrMessage($errorCode) {- switch ($errorCode) {- case UPLOAD_ERR_OK:- return __('No file sent');-- break;-- case UPLOAD_ERR_NO_FILE:- return __('No file sent');-- break;-- case UPLOAD_ERR_PARTIAL:- return __('The uploaded file was only partially uploaded');-- break;-- case UPLOAD_ERR_NO_TMP_DIR:- return __('Missing a temporary folder');-- break;-- case UPLOAD_ERR_CANT_WRITE:- return __('Failed to write file to disk');-- break;-- case UPLOAD_ERR_EXTENSION:- return __('A PHP extension stopped the file upload');-- break;-- case UPLOAD_ERR_INI_SIZE:- case UPLOAD_ERR_FORM_SIZE:- return __('Exceeded filesize limit');-- break;-- default:- return __('Unknown errors');- }-}+ * Global helper functions.+ *+ * Split into thematic modules under system/functions/; this file is the load+ * manifest so every helper stays available exactly as before the split.+ */++require_once __DIR__ . '/functions/url.php';+require_once __DIR__ . '/functions/settings.php';+require_once __DIR__ . '/functions/meta.php';+require_once __DIR__ . '/functions/text.php';+require_once __DIR__ . '/functions/security.php';+require_once __DIR__ . '/functions/arrays.php';+require_once __DIR__ . '/functions/translation.php';+require_once __DIR__ . '/functions/html.php';+require_once __DIR__ . '/functions/fs.php';+require_once __DIR__ . '/functions/xml.php';+require_once __DIR__ . '/functions/ui.php';+require_once __DIR__ . '/functions/themes.php';+require_once __DIR__ . '/functions/site.php';+require_once __DIR__ . '/functions/debug.php';+require_once __DIR__ . '/functions/loader.php';diff --git a/system/functions/arrays.php b/system/functions/arrays.phpnew file mode 100755index 0000000..8b1eea2--- /dev/null+++ b/system/functions/arrays.php@@ -0,0 +1,181 @@+<?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;++/**+ * Validates that input is in the allowed values list.+ *+ * @param mixed $input The input value to validate.+ * @param array<array-key, mixed> $allowedValues The list of allowed values.+ *+ * @return mixed The input value if valid, null otherwise.+ */+function arrayAllowValues(mixed $input, array $allowedValues): mixed {+ if (!in_array($input, $allowedValues)) {+ return null;+ } else {+ return $input;+ }+}++/**+ * Get values from multidimensional arrays based on path.+ * For example for array ['item' => ['desc' => ['name' => 'test']]] the path "item.desc.name" will return "test".+ *+ * @param array<array-key, mixed> $a The array to search.+ * @param string $path The dot-separated path to the value.+ * @param mixed $default The default value if path is not found.+ * @param string $token The token used to separate path segments.+ *+ * @return mixed The value at the given path or the default value.+ */+function arrayPath(array $a, string $path, mixed $default = null, string $token = '.'): mixed {+ $p = strtok($path, $token);++ while ($p !== false) {+ if (!isset($a[$p])) {+ return $default;+ }++ $a = $a[$p];+ $p = strtok($token);+ }++ return $a;+}++/**+ * Inserts a new key/value before the key in the array.+ *+ * @param string $key The key to insert before.+ * @param array<array-key, mixed> $array An array to insert in to.+ * @param string $new_key The key to insert.+ * @param mixed $new_value An value to insert.+ *+ * @return array<array-key, mixed> The new array if the key exists, otherwise the unchanged array.+ *+ * @see arrayInsertAfter()+ */+function arrayInsertBefore(string $key, array $array, string $new_key, mixed $new_value): array {+ if (array_key_exists($key, $array)) {+ $new = [];++ foreach ($array as $k => $value) {+ if ($k === $key) {+ $new[$new_key] = $new_value;+ }+ $new[$k] = $value;+ }++ return $new;+ }++ return $array;+}++/**+ * Inserts a new array before the key in the array.+ *+ * @param string $key The key to insert before.+ * @param array<array-key, mixed> $array An array to insert in to.+ * @param array<array-key, mixed> $new_array An array to insert.+ *+ * @return array<array-key, mixed> The new array if the key exists, otherwise the unchanged array.+ *+ * @see arrayInsertAfter()+ */+function arrayInsertArrayBefore(string $key, array $array, array $new_array): array {+ if (array_key_exists($key, $array)) {+ $new = [];++ foreach ($array as $k => $value) {+ if ($k === $key) {+ $new += $new_array;+ }+ $new[$k] = $value;+ }++ return $new;+ }++ return $array;+}++/**+ * Inserts a new key/value after the key in the array.+ *+ * @param string $key The key to insert after.+ * @param array<array-key, mixed> $array An array to insert in to.+ * @param string $new_key The key to insert.+ * @param mixed $new_value An value to insert.+ *+ * @return array<array-key, mixed> The new array if the key exists, otherwise the unchanged array.+ *+ * @see arrayInsertBefore()+ */+function arrayInsertAfter(string $key, array $array, string $new_key, mixed $new_value): array {+ if (array_key_exists($key, $array)) {+ $new = [];++ foreach ($array as $k => $value) {+ $new[$k] = $value;++ if ($k === $key) {+ $new[$new_key] = $new_value;+ }+ }++ return $new;+ }++ return $array;+}++/**+ * Inserts a new array after the key in the array.+ *+ * @param string $key The key to insert after.+ * @param array<array-key, mixed> $array An array to insert in to.+ * @param array<array-key, mixed> $new_array An array to insert.+ *+ * @return array<array-key, mixed> The new array if the key exists, otherwise the unchanged array.+ *+ * @see arrayInsertBefore()+ */+function arrayInsertArrayAfter(string $key, array $array, array $new_array): array {+ if (array_key_exists($key, $array)) {+ $new = [];++ foreach ($array as $k => $value) {+ $new[$k] = $value;++ if ($k === $key) {+ $new += $new_array;+ }+ }++ return $new;+ }++ return $array;+}diff --git a/system/functions/debug.php b/system/functions/debug.phpnew file mode 100755index 0000000..84ae71f--- /dev/null+++ b/system/functions/debug.php@@ -0,0 +1,60 @@+<?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;++/**+ * Debug output function - dumps variables with syntax highlighting.+ *+ * @param mixed ...$variables The variables to dump.+ *+ * @return void+ */+function d(mixed ...$variables): void {+ foreach ($variables as $variable) {+ echo highlight_string("<?php\n" . var_export($variable, true), true);+ }+}++/**+ * Debug and die - dumps variables with syntax highlighting and stops execution.+ *+ * @param mixed ...$variables The variables to dump.+ *+ * @return never+ */+function dd(mixed ...$variables): never {+ d(...$variables);++ exit();+}++/**+ * Log an error message.+ *+ * @param string $message The error message to log.+ *+ * @return void+ */+function logError(string $message): void {+ error_log($message);+}diff --git a/system/functions/fs.php b/system/functions/fs.phpnew file mode 100755index 0000000..5fb85c5--- /dev/null+++ b/system/functions/fs.php@@ -0,0 +1,344 @@+<?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;++/**+ * Reads the last N lines from a file.+ *+ * @param string $filename The path to the file.+ * @param int $lines The number of lines to read from the end.+ *+ * @return string|false The last lines of the file, or false on failure.+ */+function tail(string $filename, int $lines = 1000): string|false {+ $file = @fopen($filename, 'r');++ if ($file === false) {+ return false;+ }++ $buffer = 4096;+ $output = '';+ $chunk = '';++ @fseek($file, -1, SEEK_END);++ if (fread($file, 1) != "\n") {+ $lines--;+ }++ while (ftell($file) > 0 && $lines >= 0) {+ $seek = min(ftell($file), $buffer);+ fseek($file, -$seek, SEEK_CUR);+ $output = ($chunk = fread($file, $seek)) . $output;+ //fseek($file, -mb_strlen($chunk, '8bit'), SEEK_CUR);+ fseek($file, strlen($chunk), SEEK_CUR);+ $lines -= substr_count($chunk, "\n");+ }++ while ($lines++ < 0) {+ $output = substr($output, strpos($output, "\n") + 1);+ }++ fclose($file);++ return trim($output);+}++/**+ * Recursively removes a directory.+ *+ * @param string $src The directory path to remove.+ * @param array<array-key, mixed> $skip Files or directories (full paths) to skip.+ * @param mixed $keepParent Don't delete parent folder+ * @param callable $condition Provide callback function to condition file delete+ *+ * @return bool True on success, false on failure.+ */+function rrmdir(string $src, array $skip = [], $keepParent = false, ?callable $condition = null): bool {+ //never follow a symlink, otherwise a link inside the removed tree can+ //point outside it and its target contents would be deleted+ if (is_link($src)) {+ if (in_array($src, $skip)) {+ return true;+ }++ return @unlink($src);+ }++ if (!is_dir($src)) {+ return false;+ }++ $dir = @opendir($src);+ $result = true;++ if ($dir) {+ while (false !== ($file = readdir($dir))) {+ $full = $src . DS . $file;++ if (($file != '.') &&+ ($file != '..') &&+ (!in_array($full, $skip))) {+ if (is_link($full)) {+ if ($condition === null || $condition($full)) {+ $result = @unlink($full);+ }+ } elseif (is_dir($full)) {+ $result = rrmdir($full, $skip, false);+ } else {+ if ($condition === null || $condition($full)) {+ $result = @unlink($full);+ }+ }++ if (!$result) {+ break;+ }+ }+ }++ closedir($dir);++ if ($result && !$keepParent) {+ $result = @rmdir($src);+ }+ }++ return $result;+}++/**+ * Recursively copies a directory.+ *+ * @param string $src The source directory path.+ * @param string $dst The destination directory path.+ * @param array<array-key, mixed> $skip Files or directories to skip.+ * @param bool $overwrite Whether to overwrite existing destination (default true).+ *+ * @return bool True on success, false on failure.+ */+function rcopy(string $src, string $dst, array $skip = [], bool $overwrite = true): bool {+ $result = true;++ //copy symlinks as links instead of following them outside the source tree+ if (is_link($src)) {+ $target = @readlink($src);++ if ($target === false) {+ return false;+ }++ @unlink($dst);++ return @symlink($target, $dst);+ }++ if (is_dir($src)) {+ if (!file_exists($dst)) {+ $result = @mkdir($dst);++ if (!$result) {+ return false;+ }+ }++ @chmod($dst, 0755);++ $files = scandir($src);++ foreach ($files as $file) {+ $full = $src . DS . $file;++ if ($file != '.' &&+ $file != '..' &&+ !in_array($file, $skip)) {+ //is_link() first in rcopy() so links are recreated, not followed+ if (is_dir($full) || is_link($full)) {+ $result = rcopy($full, $dst . DS . $file);+ } else {+ $result = @copy($full, $dst . DS . $file);++ if (!$result) {+ if (@chmod($dst . DS . $file, 0644)) {+ $result = @copy($full, $dst . DS . $file);+ }+ }+ }++ if (!$result) {+ return false;+ }+ }+ }+ } else {+ if (file_exists($src)) {+ $result = @copy($src, $dst);++ if (!$result) {+ if (@chmod($dst, 0644)) {+ $result = copy($src, $dst);+ }+ }++ if (!$result) {+ return false;+ }+ }+ }++ return $result;+}++/**+ * Recursively renames/moves a directory.+ *+ * @param string $src The source directory path.+ * @param string $dst The destination directory path.+ * @param array<array-key, mixed> $skip Files or directories to skip.+ *+ * @return void+ */+function rrename(string $src, string $dst, array $skip = []): void {+ if (file_exists($dst)) {+ rrmdir($dst);+ }++ if (is_dir($src)) {+ if (!is_dir($dst)) {+ mkdir($dst, 0755, true);+ }+ $files = scandir($src);++ foreach ($files as $file) {+ if ($file != '.' &&+ $file != '..' &&+ !in_array($file, $skip)) {+ rename("$src/$file", "$dst/$file");+ }+ }+ } else {+ if (file_exists($src)) {+ rename($src, $dst);+ }+ }+}++/**+ * Extracts a zip archive.+ *+ * @param string $file The path to the zip file to extract.+ *+ * @return bool True on success, false on failure.+ */+function unzip(string $file): bool {+ // get the absolute path to $file+ $realPath = realpath($file);++ if ($realPath === false) {+ return false;+ }++ $path = pathinfo($realPath, PATHINFO_DIRNAME);++ $zip = new \ZipArchive();+ $res = $zip->open($file);++ if ($res === true) {+ $zip->extractTo($path);+ $zip->close();++ return $result;+ }++ return false;+}++/**+ * Format byte count to human-readable string (KB, MB, etc.).+ *+ * @param int $bytes The number of bytes.+ *+ * @return string The formatted string with appropriate unit.+ */+function formatBytes(int $bytes): string {+ $i = 0;+ $units = ['', 'K', 'M', 'G', 'T', 'P', 'E'];+ $bytes = abs($bytes);++ while (($remainder = ($bytes / 1024)) > 1 && $i < count($units) - 1) {+ $bytes = $remainder;+ $i++;+ }++ return round($bytes, 2) . ' ' . $units[$i] . 'B';+}++/**+ * Parse quantity string with K/M/G suffix to integer bytes.+ *+ * @param string $string The quantity string to parse (e.g. "10M", "512K").+ *+ * @return int The parsed integer value in bytes.+ */+function parseQuantity(string $string): int {+ if (function_exists('\ini_parse_quantity')) {+ return \ini_parse_quantity($string);+ }++ $string = trim($string);++ if ($string === '') {+ return 0;+ }++ $multiplier = lcfirst($string[strlen($string) - 1]);+ $number = (int)$string;++ return match ($multiplier) {+ 'k' => $number * 1024,+ 'm' => $number * 1048576,+ 'g' => $number * 1073741824,+ default => $number,+ };+}++/**+ * Returns a human-readable error message for a PHP file upload error code.+ *+ * @param int $errorCode One of the UPLOAD_ERR_* constants+ *+ * @return string The translated error message+ */+function fileUploadErrMessage(int $errorCode): string {+ return match ($errorCode) {+ //UPLOAD_ERR_OK => __('Upload ok'),+ UPLOAD_ERR_NO_FILE => __('No file sent'),+ UPLOAD_ERR_PARTIAL => __('The uploaded file was only partially uploaded'),+ UPLOAD_ERR_NO_TMP_DIR => __('Missing a temporary folder'),+ UPLOAD_ERR_CANT_WRITE => __('Failed to write file to disk'),+ UPLOAD_ERR_EXTENSION => __('A PHP extension stopped the file upload'),+ UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE => __('Exceeded filesize limit'),+ default => __('Unknown errors'),+ };+}diff --git a/system/functions/html.php b/system/functions/html.phpnew file mode 100755index 0000000..e546745--- /dev/null+++ b/system/functions/html.php@@ -0,0 +1,220 @@+<?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;++/**+ * Converts a CSS selector to an XPath query.+ *+ * @param string $selector The CSS selector to convert.+ *+ * @return string The resulting XPath query.+ */+function cssToXpath(string $selector): string {+ //if already xpath don't transform+ //if (substr_compare($selector,'vtpl_xpath', 0, 11) == 0) return substr($selector, 12, -1);++ $selector = (string)$selector;++ //convert , to | union operator to allow multiple queries+ $selector = str_replace(',', '|', $selector);++ $cssSelector = [+ // E > F: Matches any F element that is a child of an element E+ '/\s*>\s*/',++ // E + F: Matches any F element immediately preceded by an element+ '/\s*\+\s*/',++ // E F: Matches any F element that is a descendant of an E element+ '/([a-zA-Z\*="\[\]#._-])\s+([a-zA-Z\*="\[\]#._-])/', //'/([a-zA-Z\*="\[\]#._-])\s+([a-zA-Z\*#._-])/',++ // E:first-child: Matches element E when E is the first child of its parent+ '/([a-z#\.]\w*):first-child/',++ // E:nth-child() Matches the nth child element+ '/([a-z#\.]\w*):nth-child\((\d+)\)/',++ // E:first: Matches the first element from the set+ '/([a-z#\.]\w*):first/',++ // E:nth(2): Matches the nth element from the set+ '/([a-z#\.]\w*):nth\((\d+)\)/',++ // E[foo="warning"]: Matches any E element whose "foo" attribute value is exactly equal to "warning"+ '/([a-z]\w*)\[([a-z][\w\-_]*)\="([^"]*)"]/',++ // E[foo]: Matches any E element with the "foo" attribute set (whatever the value)+ '/([a-z]\w*)\[([a-z][\w_\-]*)\]/',++ // E[!foo]: Matches any E element without the "foo" attribute set+ '/([a-z]\w*)\[!([a-z][\w\-_]*)\]/',++ // [foo="warning"]: Matches any element whose "foo" attribute value is exactly equal to "warning"+ '/\[([a-z][\w\-_]*)\=\"(.*)\"\]/',++ // [foo*="warning"]: Matches any element whose "foo" attribute value contains the string "warning" and has other attributes+ '/(?<=\])\[([a-z][\w\-_]*)\*\=\"([^"]+)\"\]/',++ // [foo*="warning"]: Matches any element whose "foo" attribute value contains the string "warning"+ '/\[([a-z][\w\-_]*)\*\=\"([^"]+)\"\]/',++ // [foo^="warning"]: Matches any element whose "foo" attribute value begins with the string "warning"+ '/\[([a-z][\w_\-]*)\^\=\"([^"]+)\"\]/',++ // [foo$="warning"]: Matches any element whose "foo" attribute value ends with the string "warning"+ '/\[([a-z][\w_\-]*)\$\=\"([^"]+)\"\]/',++ // [foo][baz]: Matches any element with the "foo" attribute set (whatever the value)+ '/(?<=\])(?<! )\[([a-z][\w_\-]*)\]/',++ // [foo]: Matches any element with the "foo" attribute set (whatever the value)+ '/\[([a-z][\w_\-]*)\]/',++ // element[foo*]: Matches any element that starts with "foo" attribute (whatever the value)+ '/(\w+)\[([a-z][\w\-]*)\*\]/',++ // [foo*]: Matches any element that starts with "foo" attribute (whatever the value) and has other attributes+ '/(?<=\])\[([a-z][\w\-]*)\*\]/',++ // [foo*]: Matches any element that starts with "foo" attribute (whatever the value) and is a single attribute+ '/(?<!\])\[([a-z][\w\-]*)\*\]/',++ // div.warn*: HTML only. The same as DIV[class*="warning"]+ '/([a-z]\w*|\*)\.([a-z][\w\-_]*)\*/',++ // div.warning: HTML only. The same as DIV[class~="warning"]+ '/([a-z]\w*|\*)\.([a-z][\w\-_]*)+/',++ // .warn*: HTML only. The same as [class*="warning"]+ '/\.([a-z][\w\-\_]*)\*/',++ // .warning: HTML only. The same as [class~="warning"]+ '/\.([a-z][\w\-\_]*)+/',++ // E#myid: Matches any E element with id-attribute equal to "myid"+ '/([a-z]\w*)\#([a-z][\w\-_]*)/',++ // #myid: Matches any E element with id-attribute equal to "myid"+ '/\#([a-z][\w\-_]*)/',+ ];++ $xpathQuery = [+ '/', //element > child+ '/following-sibling::*[1]/self::', // element + precedent+ '\1//\2', //element descendent+ '*[1]/self::\1', //element:first-child+ '*[\2]/self::\1', //element:nth-child(2)+ '\1[1]', //element:first+ '\1[\2]', //element:nth(2)+ '\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"]+ '*[ contains( concat( " ", @\1, " " ), concat( " ", "\2", " " ) ) ]', //[foo="warning"]+ '*[ contains( concat( " ", @\1, " " ), "\2" ) ]', //[foo*="warning"]+ '*[ contains( concat( " ", @\1, " " ), concat( " ", "\2", " " ) ) ]', //[foo^="warning"] not implemented+ '*[ contains( concat( " ", @\1, " " ), concat( " ", "\2", " " ) ) ]', //[foo$="warning"] not implemented+ '[ @\1 ]', //[attribute][attribute]+ '*[ @\1 ]', //[attribute]+ '\1 [ @*[starts-with(name(), "\2")] ]', //element[attr*]+ '[ @*[starts-with(name(), "\1")] ]', //[attr*] - attribute with other attributes+ '*[ @*[starts-with(name(), "\1")] ]', //[attr*] - single attribute+ '\1[ contains( concat( " ", @class, " " ), concat( " ", "\2") ) ]', //element[class*="string"]+ '\1[ contains( concat( " ", @class, " " ), concat( " ", "\2", " " ) ) ]', //element[class~="string"]+ '*[ contains( concat( " ", @class, " " ), concat( " ", "\1") ) ]', //[class*="string"]+ '*[ contains( concat( " ", @class, " " ), concat( " ", "\1", " " ) ) ]', //element[class~="string"]+ '\1[ @id = "\2" ]', //element#id+ '*[ @id = "\1" ]', //#id+ ];++ return (string)'//' . preg_replace($cssSelector, $xpathQuery, $selector);+}++/**+ * Imports an HTML string into a DOM document and returns the node.+ *+ * @param string $html The HTML string to import.+ * @param string|null $selector An optional CSS selector to find a specific node.+ *+ * @return \DOMNode|null The imported DOM node or null.+ */+function importHtml(string $html, ?string $selector = null): ?\DOMNode {+ $dom = new \DOMDocument();+ $dom->preserveWhiteSpace = true;+ $dom->recover = true;+ $dom->strictErrorChecking = false;+ $dom->substituteEntities = false;+ $dom->formatOutput = false;+ $dom->resolveExternals = false;+ $dom->validateOnParse = false;+ $dom->xmlStandalone = true;+ $dom->loadHTML($html);++ if ($selector) {+ $xpath = new \DOMXPath($dom);+ $xpathQuery = cssToXpath($selector);+ $result = $xpath->query($xpathQuery);++ $nodeToImport = $result ? $result->item(0)?->firstChild : null;+ } else {+ $body = $dom->getElementsByTagName('body');+ $nodeToImport = $body->item(0)?->firstChild;+ }++ return $nodeToImport;+}++/**+ * Converts an HTML string to plain text.+ *+ * @param string $html The HTML string to convert.+ *+ * @return string The plain text result.+ */+function htmlToText(string $html): string {+ $html = preg_replace('/\s+/', ' ', $html) ?? $html;+ $html = str_replace('<br>', "\n", $html);+ //add new line for block elements+ $html = preg_replace('/<(div|p|li|hr|pre|blockquote|section|h\d+)/', "\n<$1", $html) ?? $html;++ return trim(strip_tags($html));+}++/**+ * Wraps double-newline-separated text in paragraph tags.+ *+ * @param string $string The text to wrap.+ *+ * @return string The text wrapped in <p> tags.+ */+function nl2p(string $string): string {+ $paragraphs = '';++ foreach (explode("\n\n", $string) as $line) {+ if (trim($line)) {+ $paragraphs .= "<p>$line</p>";+ }+ }++ return $paragraphs;+}diff --git a/system/functions/loader.php b/system/functions/loader.phpnew file mode 100755index 0000000..759ce03--- /dev/null+++ b/system/functions/loader.php@@ -0,0 +1,77 @@+<?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;++/**+ * Instantiate and return a model object by name.+ *+ * @param string $model The model name.+ *+ * @return object The instantiated model object.+ */+function model(string $model): object {+ $modelClass = 'Vvveb\Sql\\' . ucwords($model) . 'SQL';++ return new $modelClass();+}++/**+ * Instantiate and return a controller object by name.+ *+ * @param string $name The controller name.+ *+ * @return object The instantiated controller object.+ */+function controller(string $name): object {+ $controllerClass = 'Vvveb\Controller\\' . ucwords($name);++ return new $controllerClass();+}++/**+ * Check if a controller file exists.+ *+ * @param string $name The controller name.+ * @param string $app The application directory name.+ *+ * @return bool True if the controller file exists.+ */+function isController(string $name, string $app = APP): bool {+ $file = DIR_ROOT . $app . DS . 'controller' . DS . strtolower($name) . '.php';++ return file_exists($file);+}++/**+ * Check if a model SQL file exists.+ *+ * @param string $name The model name.+ * @param string $app The application directory name.+ *+ * @return bool True if the model SQL file exists.+ */+function isModel(string $name, string $app = APP): bool {+ $file = DIR_ROOT . $app . DS . 'sql' . DS . DB_ENGINE . DS . $name . '.sql';++ return file_exists($file);+}diff --git a/system/functions/meta.php b/system/functions/meta.phpnew file mode 100644index 0000000..7ef07da--- /dev/null+++ b/system/functions/meta.php@@ -0,0 +1,232 @@+<?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;++/**+ * Get multiple setting content values.+ *+ * @param int $site_id Site ID+ * @param string $namespace Setting namespace+ * @param array<array-key, mixed>|string|null $key Setting key or array of keys+ * @param array<array-key, mixed> $default Default value if keys are not found+ * @param int|false $language_id Language ID or false for default+ *+ * @return mixed Setting content values+ */+function getMultiSettingContent(int $site_id, string $namespace, array|string|null $key = null, array $default = [], int|false $language_id = false): mixed {+ return System\Meta\SettingContent::getInstance()->getMulti($site_id, $namespace, $key, $default, $language_id);+}++/**+ * Set multiple setting content values.+ *+ * @param int $site_id Site ID+ * @param mixed $meta Setting content data to set+ *+ * @return mixed Result of the set operation+ */+function setMultiSettingContent(int $site_id, mixed $meta): mixed {+ return System\Meta\SettingContent::getInstance()->setMulti($site_id, $meta);+}++/**+ * Get post metadata.+ *+ * @param int $post_id Post ID+ * @param string $namespace Metadata namespace+ * @param string|null $key Metadata key+ * @param mixed $default Default value if key is not found+ *+ * @return mixed Metadata value+ */+function getPostMeta(int $post_id, string $namespace, ?string $key = null, mixed $default = null): mixed {+ return System\Meta\PostMeta::getInstance()->get($post_id, $namespace, $key, $default);+}++/**+ * Set post metadata.+ *+ * @param int $post_id Post ID+ * @param string $namespace Metadata namespace+ * @param string|null $key Metadata key+ * @param mixed $value Value to set+ *+ * @return mixed Result of the set operation+ */+function setPostMeta(int $post_id, string $namespace, ?string $key = null, mixed $value = null): mixed {+ return System\Meta\PostMeta::getInstance()->set($post_id, $namespace, $key, $value);+}++/**+ * Delete post metadata.+ *+ * @param int $post_id Post ID+ * @param string $namespace Metadata namespace+ * @param string|null $key Metadata key+ *+ * @return mixed Result of the delete operation+ */+function deletePostMeta(int $post_id, string $namespace, ?string $key = null): mixed {+ return System\Meta\PostMeta::getInstance()->delete($post_id, $namespace, $key);+}++/**+ * Set multiple post metadata values at once.+ *+ * @param int $post_id Post ID+ * @param string $namespace Metadata namespace+ * @param mixed $meta List of ['key' => ..., 'value' => ...] rows+ * @param int|false $language_id Language ID or false for the default language+ *+ * @return mixed Result of the set operation+ */+function setMultiPostMeta(int $post_id, string $namespace, mixed $meta, int|false $language_id = false): mixed {+ return System\Meta\PostMeta::getInstance()->setMulti($post_id, $meta, $namespace, $language_id);+}++/**+ * Get post content metadata.+ *+ * @param int $post_id Post ID+ * @param string $namespace Metadata namespace+ * @param string|null $key Metadata key+ * @param mixed $default Default value if key is not found+ * @param int|false $language_id Language ID or false for default+ *+ * @return mixed Metadata value+ */+function getPostContentMeta(int $post_id, string $namespace, ?string $key = null, mixed $default = null, int|false $language_id = false): mixed {+ return System\Meta\PostContentMeta::getInstance()->get($post_id, $namespace, $key, $default, $language_id);+}++/**+ * Get multiple post content metadata values.+ *+ * @param int $post_id Post ID+ * @param string $namespace Metadata namespace+ * @param array<array-key, mixed>|string|null $key Metadata key or array of keys+ * @param array<array-key, mixed> $default Default value if keys are not found+ * @param int|false $language_id Language ID or false for default+ *+ * @return mixed Metadata values+ */+function getMultiPostContentMeta(int $post_id, string $namespace, array|string|null $key = null, array $default = [], int|false $language_id = false): mixed {+ return System\Meta\PostContentMeta::getInstance()->getMulti($post_id, $namespace, $key, $default, $language_id);+}++/**+ * Get multiple product content metadata values.+ *+ * @param int $product_id Product ID+ * @param string $namespace Metadata namespace+ * @param array<array-key, mixed>|string|null $key Metadata key or array of keys+ * @param array<array-key, mixed> $default Default value if keys are not found+ * @param int|false $language_id Language ID or false for default+ *+ * @return mixed Metadata values+ */+function getMultiProductContentMeta(int $product_id, string $namespace, array|string|null $key = null, array $default = [], int|false $language_id = false): mixed {+ return System\Meta\ProductContentMeta::getInstance()->getMulti($product_id, $namespace, $key, $default, $language_id);+}++/**+ * Set post content metadata.+ *+ * @param int $post_id Post ID+ * @param string $namespace Metadata namespace+ * @param string|null $key Metadata key+ * @param mixed $value Value to set+ * @param int|false $language_id Language ID or false for default+ *+ * @return mixed Result of the set operation+ */+function setPostContentMeta(int $post_id, string $namespace, ?string $key = null, mixed $value = null, int|false $language_id = false): mixed {+ return System\Meta\PostContentMeta::getInstance()->set($post_id, $namespace, $key, $value, $language_id);+}++/**+ * Set product content metadata.+ *+ * @param int $product_id Product ID+ * @param string $namespace Metadata namespace+ * @param string|null $key Metadata key+ * @param mixed $value Value to set+ * @param int|false $language_id Language ID or false for default+ *+ * @return mixed Result of the set operation+ */+function setProductContentMeta(int $product_id, string $namespace, ?string $key = null, mixed $value = null, int|false $language_id = false): mixed {+ return System\Meta\ProductContentMeta::getInstance()->set($product_id, $namespace, $key, $value, $language_id);+}++/**+ * Delete post content metadata.+ *+ * @param int $post_id Post ID+ * @param string $namespace Metadata namespace+ * @param string|null $key Metadata key+ * @param int|false $language_id Language ID or false for default+ *+ * @return mixed Result of the delete operation+ */+function deletePostContentMeta(int $post_id, string $namespace, ?string $key = null, int|false $language_id = false): mixed {+ return System\Meta\PostContentMeta::getInstance()->delete($post_id, $namespace, $key, $language_id);+}++/**+ * Delete product content metadata.+ *+ * @param int $product_id Product ID+ * @param string $namespace Metadata namespace+ * @param string|null $key Metadata key+ * @param int|false $language_id Language ID or false for default+ *+ * @return mixed Result of the delete operation+ */+function deleteProductContentMeta(int $product_id, string $namespace, ?string $key = null, int|false $language_id = false): mixed {+ return System\Meta\ProductContentMeta::getInstance()->delete($product_id, $namespace, $key, $language_id);+}++/**+ * Set multiple post content metadata values at once.+ *+ * @param int $post_id Post ID+ * @param mixed $meta Metadata data to set+ *+ * @return mixed Result of the set operation+ */+function setMultiPostContentMeta(int $post_id, mixed $meta): mixed {+ return System\Meta\PostContentMeta::getInstance()->setMulti($post_id, $meta);+}++/**+ * Set multiple product content metadata values at once.+ *+ * @param int $product_id Product ID+ * @param mixed $meta Metadata data to set+ *+ * @return mixed Result of the set operation+ */+function setMultiProductContentMeta(int $product_id, mixed $meta): mixed {+ return System\Meta\ProductContentMeta::getInstance()->setMulti($product_id, $meta);+}diff --git a/system/functions/php-mo.php b/system/functions/php-mo.phpindex df6e256..24ad108 100755--- a/system/functions/php-mo.php+++ b/system/functions/php-mo.php@@ -1,34 +1,37 @@<?php/**- * php.mo 0.1 by Joss Crowcroft (http://www.josscrowcroft.com).- *- * Converts gettext translation '.po' files to binary '.mo' files in PHP.- *- * Usage:- * <?php require('php-mo.php'); phpmo_convert( 'input.po', [ 'output.mo' ] ); ?>- *- * NB:- * - If no $output_file specified, output filename is same as $input_file (but .mo)- * - Returns true/false for success/failure- * - No warranty, but if it breaks, please let me know- *- * More info:- * https://github.com/josscrowcroft/php.mo- *- * Based on php-msgfmt by Matthias Bauer (Copyright © 2007), a command-line PHP tool- * for converting .po files to .mo.- * (http://wordpress-soc-2007.googlecode.com/svn/trunk/moeffju/php-msgfmt/msgfmt.php)- *- * License: GPL v3 http://www.opensource.org/licenses/gpl-3.0.html+ * 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/>.+ *+ * @param string $input+ * @param string|false $output*//*** The main .po to .mo function.+ *+ * @param string $input The input .po file path.+ * @param string|false $output The output .mo file path, or false to derive from input.+ *+ * @return bool*/--function phpmo_convert($input, $output = false) {- if (! $output) {+function phpmo_convert(string $input, string|false $output = false): bool {+ if (!$output) {$output = str_replace('.po', '.mo', $input);}@@ -43,7 +46,12 @@ function phpmo_convert($input, $output = false) {}}-function phpmo_clean_helper($x) {+/**+ * @param mixed $x+ *+ * @return mixed+ */+function phpmo_clean_helper(mixed $x): mixed {if (is_array($x)) {foreach ($x as $k => $v) {$x[$k] = phpmo_clean_helper($v);@@ -61,9 +69,14 @@ function phpmo_clean_helper($x) {return $x;}-/* Parse gettext .po files. */-/* @link http://www.gnu.org/software/gettext/manual/gettext.html#PO-Files */-function phpmo_parse_po_file($in) {+// Parse gettext .po files.+/** @see http://www.gnu.org/software/gettext/manual/gettext.html#PO-Files */+/**+ * @param string $in+ *+ * @return array<array-key, mixed>|false+ */+function phpmo_parse_po_file(string $in): array|false {// read .po file$fh = fopen($in, 'r');@@ -100,13 +113,14 @@ function phpmo_parse_po_file($in) {case '#,': // flag...$fuzzy = in_array('fuzzy', preg_split('/,\s*/', $data));+ // no breakcase '#': // translator-commentscase '#.': // extracted-commentscase '#:': // reference...case '#|': // msgid previous-untranslated-string// start a new entry- if (sizeof($temp) && array_key_exists('msgid', $temp) && array_key_exists('msgstr', $temp)) {- if (! $fuzzy) {+ if (count($temp) && array_key_exists('msgid', $temp) && array_key_exists('msgstr', $temp)) {+ if (!$fuzzy) {$hash[] = $temp;}$temp = [];@@ -120,11 +134,12 @@ function phpmo_parse_po_file($in) {// contextcase 'msgid':// untranslated-string- if (sizeof($temp)) {+ if (count($temp)) {$hash[] = $temp;$temp = [];}+ // no breakcase 'msgid_plural':// untranslated-string-plural$state = $key;@@ -140,7 +155,7 @@ function phpmo_parse_po_file($in) {break;default:- if (strpos($key, 'msgstr[') !== FALSE) {+ if (str_contains($key, 'msgstr[')) {// translated-string-case-n$state = 'msgstr';$temp[$state][] = $data;@@ -155,7 +170,7 @@ function phpmo_parse_po_file($in) {break;case 'msgstr':- $temp[$state][sizeof($temp[$state]) - 1] .= "\n" . $line;+ $temp[$state][count($temp[$state]) - 1] .= "\n" . $line;break;@@ -163,7 +178,7 @@ function phpmo_parse_po_file($in) {// parse errorfclose($fh);- return FALSE;+ return false;}}@@ -185,9 +200,9 @@ function phpmo_parse_po_file($in) {foreach ($entry as &$v) {$v = phpmo_clean_helper($v);- if ($v === FALSE) {+ if ($v === false) {// parse error- return FALSE;+ return false;}}$hash[$entry['msgid']] = $entry;@@ -196,7 +211,12 @@ function phpmo_parse_po_file($in) {return $hash;}-function phpmo_po_text($hash) {+/**+ * @param array<array-key, mixed> $hash+ *+ * @return string+ */+function phpmo_po_text(array $hash): string {$text = '';foreach ($hash as $id => $value) {@@ -208,17 +228,29 @@ function phpmo_po_text($hash) {return $text;}-/* Write a gettext .po file. */-/* @link http://www.gnu.org/software/gettext/manual/gettext.html#MO-Files */-function phpmo_write_po_file($hash, $out) {+// Write a gettext .po file.+/** @see http://www.gnu.org/software/gettext/manual/gettext.html#MO-Files */+/**+ * @param array<array-key, mixed> $hash+ * @param string $out+ *+ * @return int|false+ */+function phpmo_write_po_file(array $hash, string $out): int|false {$text = phpmo_po_text($hash);return file_put_contents($out, $text);}-/* Write a GNU gettext style machine object. */-/* @link http://www.gnu.org/software/gettext/manual/gettext.html#MO-Files */-function phpmo_write_mo_file($hash, $out) {+// Write a GNU gettext style machine object.+/** @see http://www.gnu.org/software/gettext/manual/gettext.html#MO-Files */+/**+ * @param array<array-key, mixed> $hash+ * @param string $out+ *+ * @return int|false+ */+function phpmo_write_mo_file(array $hash, string $out): int|false {// sort by msgidksort($hash, SORT_STRING);// our mo file data@@ -230,7 +262,7 @@ function phpmo_write_mo_file($hash, $out) {foreach ($hash as $index => &$entry) {//don't add empty translations- if (! $entry['msgstr'] || ! $entry['msgstr'][0]) {+ if (!$entry['msgstr'] || !$entry['msgstr'][0]) {unset($hash[$index]);continue;@@ -248,19 +280,20 @@ function phpmo_write_mo_file($hash, $out) {// plural msgstrs are NUL-separated$str = implode("\x00", $entry['msgstr']);- $str = str_replace('\n',"\n", $str); //restore newlines+ $str = str_replace('\n', "\n", $str); //restore newlines// keep track of offsets$offsets[] = [- strlen($ids- ), strlen($id), strlen($strings), strlen($str), ];+ strlen(+ $ids+ ), strlen($id), strlen($strings), strlen($str), ];// plural msgids are not stored (?)$ids .= $id . "\x00";$strings .= $str . "\x00";}// keys start after the header (7 words) + index tables ($#hash * 4 words)- $key_start = 7 * 4 + sizeof($hash) * 4 * 4;+ $key_start = 7 * 4 + count($hash) * 4 * 4;// values start right after the keys$value_start = $key_start + strlen($ids);// first all key offsets, then all value offsets@@ -268,7 +301,7 @@ function phpmo_write_mo_file($hash, $out) {$value_offsets = [];// calculateforeach ($offsets as $v) {- list($o1, $l1, $o2, $l2) = $v;+ [$o1, $l1, $o2, $l2] = $v;$key_offsets[] = $l1;$key_offsets[] = $o1 + $key_start;$value_offsets[] = $l2;@@ -277,13 +310,15 @@ function phpmo_write_mo_file($hash, $out) {$offsets = array_merge($key_offsets, $value_offsets);// write header- $mo .= pack('Iiiiiii', 0x950412de, // magic number- 0, // version- sizeof($hash), // number of entries in the catalog- 7 * 4, // key index offset- 7 * 4 + sizeof($hash) * 8, // value index offset,- 0, // hashtable size (unused, thus 0)- $key_start // hashtable offset+ $mo .= pack(+ 'Iiiiiii',+ 0x950412DE, // magic number+ 0, // version+ count($hash), // number of entries in the catalog+ 7 * 4, // key index offset+ 7 * 4 + count($hash) * 8, // value index offset,+ 0, // hashtable size (unused, thus 0)+ $key_start // hashtable offset);// offsetsforeach ($offsets as $offset) {diff --git a/system/functions/plural.php b/system/functions/plural.phpold mode 100644new mode 100755index c8b9e78..3a5d0eb--- a/system/functions/plural.php+++ b/system/functions/plural.php@@ -23,7 +23,8 @@namespace Vvveb\System\Functions;class Plural {- public static $plural = [+ /** @var array<string, string> */+ public static array $plural = ['taxonomy' => 'taxonomies','points' => 'points','currency' => 'currencies',@@ -34,9 +35,15 @@ class Plural {'media' => 'media',];- public static $singular = [];+ /** @var array<string, string> */+ public static array $singular = [];- public static function tablePlural($tableName) {+ /**+ * @param string $tableName+ *+ * @return string+ */+ public static function tablePlural(string $tableName): string {if (isset(self :: $plural[$tableName])) {return self :: $plural[$tableName];}@@ -44,7 +51,12 @@ class Plural {return $tableName . 's';}- public static function tableSingular($tableName) {+ /**+ * @param string $tableName+ *+ * @return string+ */+ public static function tableSingular(string $tableName): string {if (isset(self :: $singular[$tableName])) {return self :: $singular[$tableName];}diff --git a/system/functions/security.php b/system/functions/security.phpnew file mode 100755index 0000000..4b2fc9c--- /dev/null+++ b/system/functions/security.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;++/**+ * Escape a URL for HTML output.+ *+ * @param string $url URL to escape+ *+ * @return string Escaped URL+ */+function escUrl(string $url): string {+ return htmlspecialchars($url, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML5, 'UTF-8');+}++/**+ * Escape an attribute value for HTML output.+ *+ * @param string $attr Attribute value to escape+ *+ * @return string Escaped attribute value+ */+function escAttr(string $attr): string {+ return htmlspecialchars($attr, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML5, 'UTF-8');+}++/**+ * Escape a string for HTML output.+ *+ * @param string $string String to escape+ *+ * @return string Escaped string+ */+function escHtml(string $string): string {+ return htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML5, 'UTF-8');+}++/**+ * Sanitize filename by removing dangerous characters.+ *+ * @param string $file The filename to sanitize.+ * @param bool $normalizePath Whether to normalize directory separators to the OS separator.+ *+ * @return string The sanitized filename.+ */+function sanitizeFileName(string $file, bool $normalizePath = true): string {+ if (!$file) {+ return $file;+ }++ //remove null bytes+ $file = str_replace(chr(0), '', $file);+ //sanitize, remove double dot .. and remove get parameters if any+ $prev = '';+ while ($prev != $file) {+ $prev = $file;+ $file = preg_replace('@\?.*$|\.{2,}|[^\w\-\./ \\\]@', '', $file);+ }+ //replace directory separators with OS specific separator+ if ($normalizePath) {+ $file = str_replace(['\\', '/'], DS, $file);+ }++ return $file;+}++/**+ * Sanitizes HTML by removing dangerous elements and attributes.+ *+ * @param mixed $string The string to sanitize. Non-string values are returned as-is.+ *+ * @return mixed The sanitized string, or the original value if not a string.+ */+function sanitizeHTML(mixed $string): mixed {+ if (!is_string($string)) {+ return $string;+ }++ // Fix &entity\n;+ //add <> before tag entities to allow regex matching+ $string = str_replace(['<', '>'], ['<<', '>>'], $string);+ $string = str_replace(['&', '<', '>'], ['&amp;', '&lt;', '&gt;'], $string);+ $string = preg_replace('/(&#*\w+)[\x00-\x20]+;/u', '$1;', $string);+ $string = preg_replace('/(&#x*[0-9A-F]+);*/iu', '$1;', $string);+ $string = html_entity_decode($string, ENT_COMPAT | ENT_HTML5, 'UTF-8');++ // Remove any attribute starting with "on" or xmlns+ $string = preg_replace('#(<[^>]+?[\x00-\x20"\'/])(?:on|xmlns)[^>]*+>#iu', '$1>', $string);+ $string = preg_replace('#(<\s*\w+[^>]*?[\x00-\x20"\'/])(?:on\w+|xmlns)[\x00-\x20]*=[^>]*+\z#iu', '$1>', $string);+ $string = preg_replace('#[\x00-\x20"\'/](on|xmlns)[:\w]+[\x00-\x20"\'/]*=[\x00-\x20"\'/]*([\'"]+).+?\2#iu', '', $string);++ // Remove javascript: and vbscript: protocols+ $string = preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([`\'"]*)[\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2nojavascript...', $string);+ $string = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*v[\x00-\x20]*b[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2novbscript...', $string);+ $string = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#u', '$1=$2nomozbinding...', $string);++ // Only works in IE: <span style="width: expression(alert('Ping!'));"></span>+ $string = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?expression[\x00-\x20]*\([^>]*+>#i', '$1>', $string);+ $string = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?behaviour[\x00-\x20]*\([^>]*+>#i', '$1>', $string);+ $string = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:*[^>]*+>#iu', '$1>', $string);++ // Remove namespaced elements (we do not need them)+ $string = preg_replace('#</*\w+:\w[^>]*+>#i', '', $string);++ do {+ // Remove really unwanted tags+ $old_data = $string;+ //$string = preg_replace('#</*(?:applet|b(?:ase|gsound|link)|embed|frame(?:set)?|i(?:frame|layer)|l(?:ayer|ink)|meta|object|s(?:cript|tyle)|title|xml)[^>]*+>#i', '', $string);+ $string = preg_replace('#</*(?:applet|b(?:ase|gsound|link)|embed|frame(?:set)?|i(?:layer)|l(?:ayer|ink)|meta|object|s(?:cript|tyle)|title|xml)[^>]*+>#i', '', $string) ?? $string;+ } while ($old_data !== $string);++ //restore entities+ return str_replace(['<<', '>>'], ['<', '>'], $string);+}++/**+ * Removes specified HTML tags from a string.+ *+ * @param string $string The string to process.+ * @param array<array-key, mixed> $tags The tag names to strip (default ['script', 'iframe', 'applet']).+ *+ * @return string The string with tags removed.+ */+function stripTags(string $string, array $tags = ['script', 'iframe', 'applet']): string {+ if ($string && $tags) {+ foreach ($tags as $tag) {+ $string = preg_replace('@<\s*' . $tag . '.*?>.*?</' . $tag . '\s*>@im', '', $string) ?? $string;+ }+ }++ return $string;+}++/**+ * Recursively strips tags from all string values in an array.+ *+ * @param array<array-key, mixed> $array The array to process.+ * @param array<array-key, mixed> $tags The tag names to strip.+ *+ * @return array<array-key, mixed> The array with tags stripped from string values.+ */+function stripTagsArray(array $array, array $tags): array {+ if ($tags) {+ foreach ($array as $key => &$value) {+ if (is_string($value)) {+ $value = stripTags($value, $tags);+ } elseif (is_array($value)) {+ $value = stripTagsArray($value, $tags);+ }+ }+ unset($value);+ }++ return $array;+}++/**+ * Removes specified characters from a string.+ *+ * @param string $string The string to process.+ * @param array<array-key, mixed> $chars The characters to remove.+ *+ * @return string The string with characters removed.+ */+function stripChars(string $string, array $chars = ['(', ')', '{', '}', ':', '<', '>']): string {+ return str_replace($chars, '', $string);+}++/**+ * Validates URL and resolves hostname to prevent SSRF attacks.+ *+ * @param string $url The URL to validate.+ *+ * @return list<string> The cURL resolve entries, or empty array for invalid URLs or private/reserved IPs.+ */+function validateUrl(string $url): array {+ $p = parse_url($url);+ $scheme = $p['scheme'] ?? 'https';+ $port = (string)($p['port'] ?? ($scheme === 'http' ? '80' : '443'));++ if (!$p || !in_array($scheme, ['http', 'https'], true) || !in_array($port, ['80', '443'], true) || empty($p['host'])) {+ return [];+ }++ if (($scheme === 'http' && $port !== '80') || ($scheme === 'https' && $port !== '443')) {+ return [];+ }++ $ips = gethostbynamel($p['host']) ?: [];++ $results = [];+ foreach ($ips as $ip) {+ $results[] = $p['host'] . ':' . $port . ':[' . $ip . ']';++ if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {+ return []; // private / reserved / loopback / link-local+ }+ }++ return $results;+}++/**+ * Detects bot-challenge pages (Cloudflare "Just a moment", Turnstile)+ * from a response head sample. Conservative on purpose: the generic word+ * "cloudflare" alone never matches (articles about Cloudflare exist),+ * only challenge chrome does. Pure, tested.+ *+ * @param string $sample First bytes of the response body.+ *+ * @return bool True when the sample looks like a bot challenge page.+ */+function isChallengePage(string $sample): bool {+ $head = mb_substr($sample, 0, 4096);++ if (preg_match('/<title>\s*Just a moment/i', $head)) {+ return true;+ }++ return (bool)preg_match('/cf-challenge|cf_challenge|__cf_chl_|turnstile/i', $head);+}++/**+ * Encrypts a string using OpenSSL with specified cipher and digest.+ *+ * @param string $key The encryption key.+ * @param string $value The plaintext string to encrypt.+ * @param string $cipher The cipher method (default 'aes256').+ * @param string $digest The digest method for key derivation (default 'sha256').+ * @param string|null &$tag The authentication tag output.+ * @param string $aad Additional authenticated data.+ * @param int $tag_length The authentication tag length (default 16).+ *+ * @return string The base64-encoded encrypted string.+ */+function encrypt(string $key, string $value, string $cipher = 'aes256', string $digest = 'sha256', ?string &$tag = null, string $aad = '', int $tag_length = 16): string {+ $key = openssl_digest($key, $digest, true);+ $iv_length = openssl_cipher_iv_length($cipher);+ $iv = openssl_random_pseudo_bytes($iv_length);++ return base64_encode($iv . openssl_encrypt($value, $cipher, $key, OPENSSL_RAW_DATA, $iv, $tag, $aad, $tag_length));+}++/**+ * Decrypts an OpenSSL-encrypted string.+ *+ * @param string $key The decryption key.+ * @param string $value The base64-encoded encrypted string.+ * @param string $cipher The cipher method (default 'aes256').+ * @param string $digest The digest method for key derivation (default 'sha256').+ * @param string|null &$tag The authentication tag output.+ * @param string $aad Additional authenticated data.+ *+ * @return string|false The decrypted string, or false on failure.+ */+function decrypt(string $key, string $value, string $cipher = 'aes256', string $digest = 'sha256', ?string &$tag = null, string $aad = ''): string|false {+ $result = false;++ $key = openssl_digest($key, $digest, true);+ $iv_length = openssl_cipher_iv_length($cipher);+ $value = base64_decode($value);+ $iv = substr($value, 0, $iv_length);+ $value = substr($value, $iv_length);++ if (strlen($iv) == $iv_length) {+ $result = openssl_decrypt($value, $cipher, $key, OPENSSL_RAW_DATA, $iv, $tag, $aad);+ }++ return $result;+}++/**+ * Prefix marking a value encrypted with encryptSecret() (versioned envelope).+ */+const SECRET_ENC_PREFIX = 'enc:v1:';++/**+ * Check if a setting key likely holds a secret.+ *+ * Mirrors the gateway `isSensitive()` heuristic (`key|secret|password|+ * signature|token|private`) plus account logins (`username|login`) so+ * flat payment settings and nested omnipay/payum credentials are covered.+ * Explicit per-plugin `SECRET_KEYS` lists (e.g. payment-stripe) take+ * precedence over this heuristic — see `encryptSettings()`.+ *+ * Public identifiers are never secrets: `publishable_*`, `public_*` and+ * `*_public_key` (Stripe publishable, Braintree public, etc.) stay plaintext+ * so they remain debuggable. Already-encrypted `enc:v1:` envelopes still+ * decrypt regardless of key name (see `decryptSettings()`).+ *+ * @param string $key Setting/parameter name.+ *+ * @return bool True when the value should be encrypted at rest.+ */+function isSensitiveSettingKey(string $key): bool {+ $lower = strtolower($key);++ if (str_starts_with($lower, 'publishable_') || str_starts_with($lower, 'public_') || str_ends_with($lower, '_public_key')) {+ return false;+ }++ //token *counts*, not token secrets (ai max_tokens, usage quotas, etc.)+ if ($lower === 'max_tokens' || str_ends_with($lower, '_tokens') || str_ends_with($lower, '_token_count') || str_ends_with($lower, '_token_limit')) {+ return false;+ }++ return (bool)preg_match('/key|secret|password|signature|token|private|username|login/i', $key);+}++/**+ * Check if a value is an encrypted secret envelope.+ *+ * @param mixed $value Value to check.+ *+ * @return bool True when the value starts with the secret prefix.+ */+function isEncryptedSecret(mixed $value): bool {+ return is_string($value) && str_starts_with($value, SECRET_ENC_PREFIX);+}++/**+ * Resolve the app secret key used for secret encryption.+ *+ * @param string|null $key Explicit key override, defaults to `app.key` config.+ *+ * @return string App key or empty string when not configured.+ */+function appSecretKey(?string $key = null): string {+ if ($key !== null && $key !== '') {+ return $key;+ }++ if (function_exists('Vvveb\\getConfig')) {+ return (string)(getConfig('app.key', '') ?? '');+ }++ return '';+}++/**+ * Derive the 32-byte raw encryption key from the app key.+ *+ * @param string|null $key Explicit app key override.+ *+ * @return string|false Raw 32-byte key or false when no app key is configured.+ */+function secretRawKey(?string $key = null): string|false {+ $appKey = appSecretKey($key);++ if ($appKey === '') {+ return false;+ }++ return hash('sha256', $appKey, true);+}++/**+ * Encrypt a secret for database storage using the install-generated app key.+ *+ * Authenticated encryption only: libsodium secretbox when available,+ * otherwise OpenSSL AES-256-GCM. The envelope is versioned (`enc:v1:` ++ * base64(`0x01|nonce|ciphertext` or `0x02|iv|tag|ciphertext`)) so ciphers+ * can rotate without breaking existing rows. Plaintext DB dumps stay opaque+ * without the filesystem key; a full server compromise (DB + `config/app.php`)+ * is still unrecoverable by design — this protects DB-only disclosure+ * (dumps, SQLi, backups, snapshots, dev clones).+ *+ * @param string $plaintext Plaintext secret, empty string stays empty.+ * @param string|null $key Explicit app key override.+ *+ * @return string|false Encrypted envelope, empty string passthrough, or false when no key/crypto is available.+ */+function encryptSecret(string $plaintext, ?string $key = null): string|false {+ if ($plaintext === '') {+ return '';+ }++ $raw = secretRawKey($key);++ if ($raw === false) {+ return false;+ }++ //prefer libsodium secretbox (XSalsa20-Poly1305, nonce-misuse resistant API)+ if (function_exists('sodium_crypto_secretbox')) {+ try {+ $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);+ $cipher = sodium_crypto_secretbox($plaintext, $nonce, $raw);++ return SECRET_ENC_PREFIX . base64_encode("\x01" . $nonce . $cipher);+ } catch (\Throwable $e) {+ }+ }++ //fallback to AES-256-GCM with random 96-bit IV and 128-bit tag+ if (function_exists('openssl_encrypt')) {+ try {+ $iv = random_bytes(12);+ $tag = '';+ $cipher = openssl_encrypt($plaintext, 'aes-256-gcm', $raw, OPENSSL_RAW_DATA, $iv, $tag, '', 16);++ if ($cipher !== false && strlen($tag) === 16) {+ return SECRET_ENC_PREFIX . base64_encode("\x02" . $iv . $tag . $cipher);+ }+ } catch (\Throwable $e) {+ }+ }++ return false;+}++/**+ * Decrypt a secret envelope created by encryptSecret().+ *+ * Non-envelopes pass through unchanged so plaintext rows written before+ * encryption migrate transparently on first save.+ *+ * @param mixed $value Stored value (envelope or legacy plaintext).+ * @param string|null $key Explicit app key override.+ *+ * @return mixed Decrypted string, the original value when not encrypted, or false on failure.+ */+function decryptSecret(mixed $value, ?string $key = null): mixed {+ if (!is_string($value) || !isEncryptedSecret($value)) {+ return $value;+ }++ $raw = secretRawKey($key);++ if ($raw === false) {+ return false;+ }++ $payload = base64_decode(substr($value, strlen(SECRET_ENC_PREFIX)), true);++ if ($payload === false || strlen($payload) < 2) {+ return false;+ }++ $algo = $payload[0];++ try {+ if ($algo === "\x01" && function_exists('sodium_crypto_secretbox_open')) {+ $nonce = substr($payload, 1, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);+ $cipher = substr($payload, 1 + SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);++ if (strlen($nonce) === SODIUM_CRYPTO_SECRETBOX_NONCEBYTES && $cipher !== '') {+ $plain = sodium_crypto_secretbox_open($cipher, $nonce, $raw);++ return $plain === false ? false : $plain;+ }+ }++ if ($algo === "\x02" && function_exists('openssl_decrypt')) {+ $iv = substr($payload, 1, 12);+ $tag = substr($payload, 13, 16);+ $cipher = substr($payload, 29);++ if (strlen($iv) === 12 && strlen($tag) === 16 && $cipher !== '') {+ $plain = openssl_decrypt($cipher, 'aes-256-gcm', $raw, OPENSSL_RAW_DATA, $iv, $tag);++ return $plain === false ? false : $plain;+ }+ }+ } catch (\Throwable $e) {+ return false;+ }++ return false;+}++/**+ * Generates a string of random digits of specified length.+ *+ * @param int $length Number of digits to generate+ *+ * @return string Random digit string+ */+function randomDigits(int $length): string {+ $result = '';++ for ($i = 0; $i < $length; $i++) {+ $result .= random_int(0, 9);+ }++ return $result;+}++/**+ * Check php code for syntax errors, return false on errors.+ *+ * @param string $source+ *+ * @return bool+ */+function checkPhpSyntax(string $source): bool {+ try {+ $tokens = token_get_all($source, TOKEN_PARSE);+ } catch (\ParseError $e) {+ return false;+ }++ return true;+}diff --git a/system/functions/settings.php b/system/functions/settings.phpnew file mode 100755index 0000000..2d9bc98--- /dev/null+++ b/system/functions/settings.php@@ -0,0 +1,405 @@+<?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;++/**+ * Get a setting value by namespace and key.+ *+ * @param string $namespace Setting namespace+ * @param string|array<array-key, mixed>|null $key Setting key or array of keys+ * @param mixed $default Default value if key is not found+ * @param int $site_id Site ID+ *+ * @return mixed Setting value+ */+function getSetting(string $namespace, string|array|null $key = null, mixed $default = null, int $site_id = SITE_ID): mixed {+ return System\Setting::getInstance()->get($namespace, $key, $default, $site_id);+}++/**+ * Set a setting value.+ *+ * @param string $namespace Setting namespace+ * @param string|null $key Setting key+ * @param mixed $value Value to set+ * @param int $site_id Site ID+ *+ * @return mixed Result of the set operation+ */+function setSetting(string $namespace, ?string $key = null, mixed $value = null, int $site_id = SITE_ID): mixed {+ return System\Setting::getInstance()->set($namespace, $key, $value, $site_id);+}++/**+ * Delete a setting.+ *+ * @param string $namespace Setting namespace+ * @param string|null $key Setting key+ * @param int $site_id Site ID+ *+ * @return mixed Result of the delete operation+ */+function deleteSetting(string $namespace, ?string $key = null, int $site_id = SITE_ID): mixed {+ return System\Setting::getInstance()->delete($namespace, $key, $site_id);+}++/**+ * Set multiple settings at once.+ *+ * @param string $namespace Setting namespace+ * @param array<array-key, mixed> $settings Array of key-value pairs to set+ * @param int $site_id Site ID+ *+ * @return mixed Result of the set operation+ */+function setMultiSetting(string $namespace, array $settings, int $site_id = SITE_ID): mixed {+ return System\Setting::getInstance()->setMulti($namespace, $settings, $site_id);+}++/**+ * Encrypt sensitive values in a settings array for database storage.+ *+ * Walks flat settings and nested method arrays (omnipay/payum store one+ * JSON row per method) and encrypts every non-empty scalar whose key looks+ * secret. Pass an explicit allowlist to override the `isSensitiveSettingKey()`+ * heuristic, pass an empty array to encrypt nothing. Already-encrypted values+ * are left untouched so saves stay idempotent. Encryption failures fall back+ * to plaintext so a missing `app.key` never loses data.+ *+ * @param array<string, mixed> $settings Settings to encrypt.+ * @param array<int, string>|null $secretKeys Explicit secret keys, null for auto-detect.+ * @param string|null $key Explicit app key override.+ *+ * @return array<string, mixed> Settings with secrets encrypted.+ */+function encryptSettings(array $settings, ?array $secretKeys = null, ?string $key = null): array {+ foreach ($settings as $name => &$value) {+ if (is_array($value)) {+ $value = encryptSettings($value, $secretKeys, $key);+ continue;+ }++ if (!is_string($value) || $value === '' || isEncryptedSecret($value)) {+ continue;+ }++ $secret = (($secretKeys !== null) ? in_array($name, $secretKeys, true) : isSensitiveSettingKey($name));++ if ($secret) {+ $encrypted = encryptSecret($value, $key);++ if (is_string($encrypted) && $encrypted !== '') {+ $value = $encrypted;+ }+ }+ }+ unset($value);++ return $settings;+}++/**+ * Decrypt any secret envelopes in settings data.+ *+ * Key-agnostic: every `enc:v1:` string is decrypted wherever it sits, so+ * renames and heuristic changes stay backward compatible. Legacy plaintext+ * passes through, undecryptable envelopes (missing/rotated key) are kept as+ * stored so admins can re-save instead of losing data.+ *+ * @param mixed $data Settings array or scalar from storage.+ * @param string|null $key Explicit app key override.+ *+ * @return mixed Data with secrets decrypted.+ */+function decryptSettings(mixed $data, ?string $key = null): mixed {+ if (is_array($data)) {+ foreach ($data as &$value) {+ $value = decryptSettings($value, $key);+ }+ unset($value);++ return $data;+ }++ if (isEncryptedSecret($data)) {+ $plain = decryptSecret($data, $key);++ return $plain === false ? $data : $plain;+ }++ return $data;+}++/**+ * Keep stored secrets when the admin leaves a password field blank.+ *+ * Lets secret inputs render empty (instead of echoing plaintext into HTML)+ * without wiping credentials on save.+ *+ * @param array<string, mixed> $posted Submitted settings (possibly nested methods).+ * @param array<string, mixed> $stored Currently stored settings (decrypted).+ * @param array<int, string>|null $secretKeys Explicit secret keys, null for auto-detect.+ *+ * @return array<string, mixed> Posted settings with blanks filled from storage.+ */+function preserveSecretSettings(array $posted, array $stored, ?array $secretKeys = null): array {+ foreach ($posted as $name => &$value) {+ if (is_array($value)) {+ $storedChild = (isset($stored[$name]) && is_array($stored[$name])) ? $stored[$name] : [];+ $value = preserveSecretSettings($value, $storedChild, $secretKeys);+ continue;+ }++ $secret = ($secretKeys !== null) ? in_array($name, $secretKeys, true) : isSensitiveSettingKey($name);++ if ($secret && ($value === '' || $value === null) && isset($stored[$name]) && is_string($stored[$name]) && $stored[$name] !== '') {+ $value = $stored[$name];+ }+ }+ unset($value);++ return $posted;+}++/**+ * Get a single secret setting, decrypted.+ *+ * Thin wrapper over getSetting() for intent-clarity; reads already decrypt+ * transparently via System\Setting.+ *+ * @param string $namespace Setting namespace+ * @param string|null $key Setting key+ * @param mixed $default Default when missing/undecryptable+ * @param int $site_id Site ID+ *+ * @return mixed Decrypted value.+ */+function getSecretSetting(string $namespace, ?string $key = null, mixed $default = null, int $site_id = SITE_ID): mixed {+ return getSetting($namespace, $key, $default, $site_id);+}++/**+ * Set a single secret setting, encrypted at rest.+ *+ * @param string $namespace Setting namespace+ * @param string|null $key Setting key+ * @param mixed $value Value to encrypt and store+ * @param int $site_id Site ID+ *+ * @return mixed Result of the set operation+ */+function setSecretSetting(string $namespace, ?string $key = null, mixed $value = null, int $site_id = SITE_ID): mixed {+ if (is_string($value) && $value !== '' && !isEncryptedSecret($value)) {+ $encrypted = encryptSecret($value);++ if (is_string($encrypted) && $encrypted !== '') {+ $value = $encrypted;+ }+ }++ if (is_array($value)) {+ $value = encryptSettings($value);+ }++ return System\Setting::getInstance()->set($namespace, $key, $value, $site_id);+}++/**+ * Set multiple settings, encrypting secrets at rest.+ *+ * Drop-in for setMultiSetting() for payment/plugin settings. Uses the+ * auto-detect heuristic unless $secretKeys is given.+ *+ * @param string $namespace Setting namespace+ * @param array<string, mixed> $settings Settings to store+ * @param array<int, string>|null $secretKeys Explicit secret keys, null for auto-detect+ * @param int $site_id Site ID+ *+ * @return mixed Result of the set operation+ */+function setMultiSecretSetting(string $namespace, array $settings, ?array $secretKeys = null, int $site_id = SITE_ID): mixed {+ return System\Setting::getInstance()->setMulti($namespace, encryptSettings($settings, $secretKeys), $site_id);+}++/**+ * Masked hint for a configured secret without exposing it.+ *+ * For admin placeholders like `Leave blank to keep ••••abcd`. Returns an+ * empty string when nothing is configured. Only the last 4 characters ever+ * leave the server — never use this for runtime auth, only for display.+ *+ * @param string $namespace Setting namespace+ * @param string $key Setting key+ * @param int $site_id Site ID+ *+ * @return string Masked hint (`••••last4`) or empty string.+ */+function secretHint(string $namespace, string $key, int $site_id = SITE_ID): string {+ $value = getSetting($namespace, $key, null, $site_id);++ if (!is_string($value) || $value === '') {+ return '';+ }++ //never reveal more than the tail for display purposes+ return '••••' . substr($value, -4);+}++/**+ * Blank sensitive values for admin display (`methods_params` JSON, etc.).+ *+ * Prevents decrypted secrets from being embedded in page HTML/JSON while+ * keeping saves safe: blanked fields are restored from storage by+ * `preserveSecretSettings()` on submit.+ *+ * @param array<string, mixed> $data Settings or method rows.+ * @param array<int, string>|null $secretKeys Explicit secret keys, null for auto-detect.+ *+ * @return array<string, mixed> Copy with secrets replaced by empty strings.+ */+function scrubSensitiveSettings(array $data, ?array $secretKeys = null): array {+ foreach ($data as $name => &$value) {+ if (is_array($value)) {+ $value = scrubSensitiveSettings($value, $secretKeys);+ continue;+ }++ if (!is_string($value) || $value === '') {+ continue;+ }++ $secret = ($secretKeys !== null) ? in_array($name, $secretKeys, true) : isSensitiveSettingKey($name);++ if ($secret) {+ $value = '';+ }+ }+ unset($value);++ return $data;+}++/*+ * File-backed global application config (System\Config), persisted to+ * `config/$namespace.php` files at runtime — as opposed to the DB-backed,+ * per-site settings above. Admins edit settings; code edits config.+ */++/**+ * Get a configuration value or the Config instance.+ *+ * @param string|null $key Config key to retrieve, or null for the Config instance+ * @param mixed $default Default value if key is not found+ *+ * @return mixed Configuration value or Config instance+ */+function config(?string $key = null, mixed $default = null): mixed {+ if (is_null($key)) {+ return System\Config::getInstance();+ }++ return System\Config::getInstance()->get($key, $default);+}++/**+ * Get a configuration value.+ *+ * @param string|null $key Config key to retrieve, or null for all config+ * @param mixed $default Default value if key is not found+ *+ * @return mixed Configuration value+ */+function getConfig(?string $key = null, mixed $default = null): mixed {+ return System\Config::getInstance()->get($key, $default);+}++/**+ * Set a configuration value.+ *+ * @param string $key Config key to set+ * @param mixed $value Value to set+ *+ * @return bool True on success+ */+function setConfig(string $key, mixed $value = null): bool {+ return System\Config::getInstance()->set($key, $value);+}++/**+ * Remove a configuration value.+ *+ * @param string $key Config key to remove+ *+ * @return mixed Result of the unset operation+ */+function unsetConfig(string $key): mixed {+ return System\Config::getInstance()->unset($key);+}++/**+ * Get or set session data.+ *+ * When a string is passed, retrieves the session value for that key. When an array is passed, sets all key-value pairs.+ *+ * @param string|array<array-key, mixed> $data Session key to get, or array of key-value pairs to set+ * @param mixed $default Default value to return if key is not found+ *+ * @return mixed Session value when getting, or default value+ */+function session(string|array $data, mixed $default = null): mixed {+ $session = System\Session::getInstance();++ if (!$session) {+ return $default;+ }++ if (is_array($data)) {+ foreach ($data as $key => $value) {+ $session->set($key, $value);+ }+ } else {+ $value = $session->get($data);++ if ($value === null) {+ return $default;+ }++ return $value;+ }++ return $default;+}++/**+ * Get an environment variable value.+ *+ * @param string $key Environment variable name+ * @param mixed $default Default value if variable is not set+ *+ * @return mixed Environment variable value or default+ */+function env(string $key, mixed $default = null): mixed {+ $env = getenv($key);++ return $env === false ? $default : $env;+}diff --git a/system/functions/site.php b/system/functions/site.phpnew file mode 100755index 0000000..5885524--- /dev/null+++ b/system/functions/site.php@@ -0,0 +1,160 @@+<?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;++/**+ * Returns site settings with caching and optional language filtering.+ *+ * @param int $site_id The site ID (default SITE_ID).+ * @param int|false $language_id The language ID to filter by, or false to skip filtering.+ *+ * @return array<array-key, mixed> The site settings array.+ */+function siteSettings(int $site_id = SITE_ID, int|false $language_id = false): array {+ $cache = System\Cache::getInstance();+ $site = $cache->cache(APP, 'site.' . $site_id, function() use ($site_id) {+ $siteSql = new Sql\SiteSQL();+ $site = $siteSql->get(['site_id' => $site_id]);++ if ($site && isset($site['settings'])) {+ $settings = json_decode($site['settings'], true);+ $siteData = $siteSql->getSiteData(['site' => $settings]);++ foreach (['favicon', 'logo', 'logo-sticky', 'logo-dark', 'logo-dark-sticky', 'webbanner'] as $img) {+ if (isset($settings[$img])) {+ $settings["$img-src"] = $settings[$img];+ $settings[$img] = System\Images::image($settings[$img], '');+ }+ }++ return $settings + $siteData;+ }++ return [];+ }, 259200);++ if ($language_id && $site && isset($site['description']) && is_array($site['description'])) {+ $site['description'] = $site['description'][$language_id] ?? $site['description'][1] ?? '';+ }++ return $site;+}++/**+ * Send email using template.+ *+ * @param string|array<array-key, mixed> $to+ * @param string $subject+ * @param string|array<array-key, mixed> $template+ * @param array<array-key, mixed> $data+ * @param array<array-key, mixed> $config+ * @param string|null $app+ * @param int $site_id+ * @param array<array-key, mixed> $additionalOptions+ *+ * @return bool+ */+function email(string|array $to, string $subject, string|array $template, array $data = [], array $config = [], ?string $app = null, int $site_id = SITE_ID, array $additionalOptions = []): bool {+ $email = System\Email::getInstance($additionalOptions);++ if (is_array($template)) {+ $html = $template['html'] ?? '';+ $txt = $template['txt'] ?? '';+ } else {+ $htmlView = new System\Core\View($app);+ $htmlView->setTheme();+ $htmlView->set($data);+ //get email html template+ $htmlView->template("email/$template.html");+ $html = $htmlView->render(true, false, true);++ //get email text template+ $txtView = new System\Core\View($app);+ $txtView->setTheme();+ $txtView->set($data);+ $txtView->template("email/$template.txt.html");+ $txt = $txtView->render(true, false, true);+ $txt = htmlToText($txt);+ }++ //get site contact email for sender and reply to+ $site = siteSettings($site_id, session('language_id') ?? 1);+ $sender = $config['sender'] ?? (is_array($site['description'] ?? null) ? ($site['description']['title'] ?? '') : ($site['description'] ?? ''));+ $from = $config['from'] ?? $site['contact-email'] ?? '';+ $reply = $config['reply'] ?? $site['contact-email'] ?? '';++ $email->setHtml($html);+ $email->setText($txt);+ $email->setTo($to);+ $email->setSender($sender);++ if ($from) {+ $email->setFrom($from);+ }++ if ($reply) {+ $email->setReplyTo($reply);+ }++ $email->setSubject($subject);++ return $email->send();+}++/**+ * Glob with brace expansion support (fallback for systems without GLOB_BRACE).+ *+ * @param string $path Directory path+ * @param array<array-key, mixed> $glob Array of glob patterns+ * @param string $filename Optional filename suffix+ *+ * @return array<array-key, mixed> Array of matching file paths+ */+function globBrace(string $path, array $glob, string $filename = ''): array {+ $files = [];++ if (defined('GLOB_BRACE')) {+ $path .= '{' . implode(',', $glob) . '}' . $filename;+ $files = glob($path, GLOB_BRACE) ?: [];+ } else {+ foreach ($glob as $pattern) {+ //$path already ends with a directory separator (all callers append it)+ $files = array_merge($files, glob($path . $pattern . $filename) ?: []);+ }+ }++ return $files;+}++/**+ * Checks if the current request is over HTTPS.+ *+ * @return bool True if request is secure, false otherwise+ */+function isSecure(): bool {+ return+ (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')+ || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')+ || ($_SERVER['SERVER_PORT'] ?? 80) == 443;+}+diff --git a/system/functions/str.php b/system/functions/str.phpindex 85b7283..081354a 100755--- a/system/functions/str.php+++ b/system/functions/str.php@@ -23,25 +23,48 @@namespace Vvveb\System\Functions;class Str {- public static function sanitizeFilename($filename) {+ /**+ * @param string $filename+ *+ * @return string+ */+ public static function sanitizeFilename(string $filename): string {return preg_replace('([^\w\s\d\.\-_~,;:\[\]\(\)]|[\.]{2,})', '', $filename);}- public static function sanitizePath($filename) {+ /**+ * @param string $filename+ *+ * @return string+ */+ public static function sanitizePath(string $filename): string {return preg_replace('([^\/\w\s\d\.\-_~,;:\[\]\(\)\\]|[\.]{2,})', '', $filename);}- public static function match($pattern, $subject) {+ /**+ * @param string $pattern+ * @param string $subject+ *+ * @return string|array<array-key, mixed>|null+ */+ public static function match(string $pattern, string $subject): string|array|null {if (preg_match($pattern, $subject, $matches)) {if (count($matches) > 2) {return array_slice($matches, 1);- } else {- return $matches[1];}++ return $matches[1] ?? $matches[0];}++ return null;}- public static function random($length = 16) {+ /**+ * @param int $length+ *+ * @return string+ */+ public static function random(int $length = 16): string {$string = '';while (($len = strlen($string)) < $length) {diff --git a/system/functions/text.php b/system/functions/text.phpnew file mode 100755index 0000000..4b1370c--- /dev/null+++ b/system/functions/text.php@@ -0,0 +1,339 @@+<?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;++/**+ * Convert dot notation to array key notation.+ *+ * Converts var.key1.key2 to var['key1']['key2'].+ *+ * @param string $key Dot-notation key string+ *+ * @return string Array key notation string+ */+function dotToArrayKey(string $key): string {+ //var.key1.key2 > var['key1']['key2']+ //var.key1 > var['key1']++ return preg_replace_callback('/\.([-_\w]+)/', fn ($matches) => "['" . str_replace("'", "\'", $matches[1]) . "']", $key);+}++/**+ * Convert form name bracket notation to array key notation.+ *+ * Converts name[key] to ['name']['key'].+ *+ * @param string $key Form name bracket notation string+ *+ * @return string Array key notation string+ */+function postNameToArrayKey(string $key): string {+ $key = str_replace(['][', '[', ']'], ['.', '.', ''], $key);++ return '[\'' . str_replace('.', '\'][\'', $key) . '\']';+}++/**+ * Prefix all array keys with a given prefix.+ *+ * @param string $prefix Prefix to add to each key+ * @param array<array-key, mixed> &$array Array to modify by reference+ *+ * @return array<array-key, mixed> Modified array with prefixed keys+ */+function prefixArrayKeys(string $prefix, array &$array): array {+ foreach ($array as $k => $v) {+ $array["$prefix$k"] = $v;+ unset($array[$k]);+ }++ return $array;+}++/**+ * Converts slug/text to human readable format.+ *+ * @param string $text The text to convert.+ *+ * @return string The human readable text.+ */+function humanReadable(string $text): string {+ return ucfirst(str_replace(['_', '-', '/', '[', ']', '.'], [' ', ' ', ' - ', ' ', ' ', ' '], trim($text, ' /\-_')));+}++/**+ * Cleans text for URL usage without transliteration.+ *+ * @param string $text The text to clean.+ * @param string $divider The divider character to use.+ *+ * @return string The cleaned URL string.+ */+function cleanUrl(string $text, string $divider = '-'): string {+ // replace non letter or digits by divider+ $text = preg_replace('/[^\pL\d]+/u', $divider, $text) ?? $text;++ // remove unwanted characters+ $text = preg_replace('/[^\\-\w]+/', '', $text) ?? $text;++ return trim($text, $divider);+}++/**+ * Creates URL-safe slug from text with transliteration.+ *+ * @param string $text The text to slugify.+ * @param string $divider The divider character to use.+ *+ * @return string The URL-safe slug.+ */+function slugify(string $text, string $divider = '-'): string {+ if (!$text) {+ return $text;+ }+ // replace non letter or digits by divider+ $text = preg_replace('/[^\pL\d]+/u', $divider, $text) ?? $text;++ // transliterate+ if (function_exists('iconv')) {+ $transliterated = @iconv('utf-8', 'us-ascii//TRANSLIT', $text);++ if ($transliterated !== false) {+ $text = $transliterated;+ }+ }++ // remove unwanted characters+ $text = preg_replace('/[^-\w]+/', '', $text) ?? $text;++ // trim+ $text = trim($text, $divider);++ // remove duplicate divider+ $text = preg_replace('/-+/', $divider, $text) ?? $text;++ // lowercase+ return strtolower($text);+}++/**+ * Converts a dash-separated string to CamelCase.+ *+ * @param string $string The string to convert.+ * @param string $dash The dash character used as separator.+ *+ * @return string The CamelCase string.+ */+function dashesToCamelCase(string $string, string $dash = '-'): string {+ return str_replace($dash, '', ucwords($string, $dash));+}++/**+ * Converts CamelCase string to dash/underscore-separated lowercase.+ *+ * @param string $string The CamelCase string to convert.+ * @param string $us The separator character (default '-').+ *+ * @return string The converted string.+ */+function camelToUnderscore(string $string, string $us = '-'): string {+ return strtolower(preg_replace(+ '/(?<=\d)(?=[A-Za-z])|(?<=[A-Za-z])(?=\d)|(?<=[a-z])(?=[A-Z])/',+ $us,+ $string+ ));+}++/**+ * Recursively converts underscore-separated array keys to camelCase.+ *+ * @param array<array-key, mixed> $array The array whose keys to convert.+ *+ * @return array<array-key, mixed> The array with converted keys.+ */+function arrayKeysToCamelCase(array &$array): array {+ foreach ($array as $key => &$value) {+ if (is_array($value)) {+ $value = arrayKeysToCamelCase($value);+ }++ $newKey = lcfirst(dashesToCamelCase($key, '_'));++ if ($newKey != $key) {+ $array[$newKey] = $value;+ unset($array[$key]);+ }+ }++ return $array;+}++/**+ * Recursively converts camelCase array keys to dash-separated lowercase.+ *+ * @param array<array-key, mixed> &$array The array to convert keys for.+ * @param string $us The separator character (default '-').+ *+ * @return array<array-key, mixed> The array with converted keys.+ */+function arrayKeysToUnderscore(array &$array, string $us = '-'): array {+ foreach ($array as $key => &$value) {+ if (is_array($value)) {+ $value = arrayKeysToUnderscore($value, $us);+ }++ $newKey = camelToUnderscore($key, $us);++ if ($newKey != $key) {+ $array[$newKey] = $value;+ unset($array[$key]);+ }+ }++ return $array;+}++/**+ * Removes extra spaces from a string.+ *+ * @param string $string The string to process.+ *+ * @return string The string with extra spaces removed.+ */+function stripExtraSpaces(string $string): string {+ foreach (['\t', '\n', '\r', ' '] as $space) {+ $string = preg_replace('/(' . $space . ')' . $space . '+/', '\1', $string);+ }++ return $string;+}++/**+ * Truncates text to specified number of characters.+ *+ * @param string $text The text to truncate.+ * @param int $limit The maximum number of characters.+ *+ * @return string The truncated text.+ */+function truncateWords(string $text, int $limit): string {+ $parts = preg_split('/(\s+)/ms', substr($text, 0, $limit * 2), 0, PREG_SPLIT_DELIM_CAPTURE);+ $partsCount = count($parts);++ $length = 0;+ $lastPart = 0;+ for (; $lastPart < $partsCount; $lastPart++) {+ $partlen = strlen($parts[$lastPart]);+ $length += $partlen;+ if ($length >= $limit) {+ //don't include less than two letter last word or spaces+ $partlen = $lastPart > 0 ? strlen($parts[$lastPart - 1]) : 0;+ while (($partlen < 3) && $lastPart > 3) {+ $lastPart--;+ $partlen = strlen($parts[$lastPart - 1]);+ }+ break;+ }+ }++ return implode('', array_slice($parts, 0, $lastPart));+}++/**+ * Sanitize text by encoding special characters.+ *+ * @param string $data Text to sanitize+ *+ * @return string Sanitized text+ */+function filterText(string $data): string {+ //no urldecode after sanitizing - it would re-introduce percent-encoded+ //special chars (eg %3Cscript%3E -> <script>) defeating the filter+ return filter_var($data, FILTER_SANITIZE_FULL_SPECIAL_CHARS, FILTER_FLAG_ENCODE_HIGH | FILTER_FLAG_ENCODE_LOW);+}++/**+ * Regex filter to allow only matched content.+ *+ * @param string $regex Regular expression pattern+ * @param string $input Input string to filter+ * @param int $maxInputSize Maximum input size to test+ *+ * @return string|false Matched content, or false if no match+ */+function filter(string $regex, string $input, int $maxInputSize = 100): string|false {+ $matches = [];++ if (preg_match($regex, substr($input, 0, $maxInputSize), $matches)) {+ return $matches[0];+ } else {+ return false;+ }+}++/**+ * Shortcut for preg_match to return the matched parameter directly.+ *+ * @param string $regex+ * @param string $input+ * @param int $level [false]+ *+ * @return mixed+ */+function pregMatch(string $regex, string $input, int|false $level = false): mixed {+ $matches = [];++ //if (preg_match($regex, $input, $matches, PREG_UNMATCHED_AS_NULL | PREG_PATTERN_ORDER)) {+ if (preg_match($regex, $input, $matches, PREG_UNMATCHED_AS_NULL)) {+ if ($level !== false) {+ return $matches[$level];+ }++ return $matches;+ } else {+ return false;+ }+}++/**+ * Shortcut for preg_match_all to return the matched parameters directly.+ *+ * @param string $regex+ * @param string $input+ * @param int $level [false]+ *+ * @return mixed+ */+function pregMatchAll(string $regex, string $input, int|false $level = false): mixed {+ $matches = [];++ if (preg_match_all($regex, $input, $matches, PREG_UNMATCHED_AS_NULL | PREG_PATTERN_ORDER)) {+ if ($level !== false) {+ return $matches[$level];+ }++ return $matches;+ } else {+ return false;+ }+}diff --git a/system/functions/themes.php b/system/functions/themes.phpnew file mode 100755index 0000000..deef192--- /dev/null+++ b/system/functions/themes.php@@ -0,0 +1,154 @@+<?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;++/**+ * Return list of theme folders.+ *+ * @param string|false $theme The theme name, or false to use the current theme.+ *+ * @return array<array-key, mixed> The list of theme folders.+ */+function getThemeFolderList(string|false $theme = false): array {+ $skipFolders = ['src', 'source', 'backup', 'sections', 'blocks', 'inputs', 'css', 'scss', 'fonts', 'img', 'import', 'node_modules', 'screenshots', 'video', 'js'];++ if (!$theme) {+ $theme = \Vvveb\System\Sites::getTheme(SITE_ID);+ }++ $themeFolder = DIR_THEMES . $theme;+ $files = glob("$themeFolder/*", GLOB_ONLYDIR) ?: [];+ $pages['/'] = ['name' => '/', 'title' => '/', 'filename' => '/', 'file' => '/', 'path' => '/', 'folder' => $theme];++ foreach ($files as $file) {+ $folder = preg_replace('@^.*/themes/[^/]+/@', '', $file);+ $filename = basename($file);++ if (in_array($folder, $skipFolders)) {+ continue;+ }++ $pages[$file] = ['name' => $filename, 'title' => "/$filename", 'filename' => $filename, 'file' => $filename, 'folder' => $theme];+ }++ return $pages;+}++/**+ * Return list of default template filenames.+ *+ * @return array<array-key, mixed> List of default template filenames.+ */+function getDefaultTemplateList(): array {+ return [+ 'index.html',+ 'index.coming-soon.html',+ 'index.maintenance.html',+ 'blank.html',+ 'error404.html',+ 'error500.html',+ 'contact.html',+ 'search/index.html',+ 'content/post.html',+ 'content/page.html',+ 'content/index.html',+ 'content/category.html',+ 'content/tag.html',+ 'product/index.html',+ 'product/product.html',+ 'product/category.html',+ ];+}++/**+ * Return list of available templates for a theme.+ *+ * @param string|null $theme The theme name, or null to use the current theme.+ * @param array<array-key, mixed> $skip List of folder names to skip.+ *+ * @return array<array-key, mixed> Associative array of templates.+ */+function getTemplateList(?string $theme = null, array $skip = []): array {+ $friendlyNames = [+ 'index' => ['name' => __('Home page'), 'description' => __('Website homepage'), 'global' => true],+ 'index.coming-soon' => ['name' => __('Coming soon'), 'description' => __('Coming soon message page'), 'global' => true],+ 'index.maintenance' => ['name' => __('Under maintenance'), 'description' => __('Website under maintenance message page'), 'global' => true],+ 'contact' => ['name' => __('Contact us page'), 'description' => __('Contact us page')],+ 'blank' => ['name' => __('Blank page'), 'description' => __('Template page used for new pages')],+ 'product' => ['name' => __('Product page'), 'description' => __('Used to display a product'), 'editor' => ['template' => 'product'], 'global' => true],+ 'error404' => ['name' => __('Page not found'), 'description' => __('Shows when a page is not available'), 'global' => true],+ 'error500' => ['name' => __('Server error'), 'description' => __('Site error display page'), 'global' => true],+ 'content-index' => ['name' => __('Blog homepage'), 'description' => __('Blog page with latest posts'), 'global' => true],+ 'content-post' => ['name' => __('Blog post'), 'description' => __('Blog post'), 'editor' => ['template' => 'post'], 'global' => true],+ 'content-page' => ['name' => __('Page'), 'description' => __('Page'), 'editor' => ['template' => 'page'], 'global' => true],+ 'product-index' => ['name' => __('Shop page'), 'description' => __('Shop homepage'), 'global' => true],+ 'search-index' => ['name' => __('Search page'), 'description' => __('Search page'), 'global' => true],+ 'user-index' => ['name' => __('Dashboard'), 'description' => __('User dashboard'), 'global' => true],+ ];++ $skipFolders = array_merge(['src', 'source', 'backup', 'sections', 'blocks', 'inputs', 'css', 'scss', 'screenshots', 'locale', 'node_modules'], $skip);++ if (!$theme) {+ $theme = \Vvveb\System\Sites::getTheme(SITE_ID);+ }+ $pages = [];+ $themeFolder = DIR_THEMES . $theme;+ //$files = glob("$themeFolder/{,*/*/,*/}*.html", GLOB_BRACE);+ $glob = ['', '*/*/', '*/'];+ $files = globBrace($themeFolder . DS, $glob, '*.html');++ foreach ($files as $file) {+ $file = preg_replace('@^.*[\\\/]themes[\\\/][^\\\/]+[\\\/]@', '', $file);+ $filename = basename($file);++ $folder = \Vvveb\System\Functions\Str::match('@(\w+)/.*?$@', $file);+ $path = $folder;+ $folder ??= DS;++ if (in_array($folder, $skipFolders)) {+ continue;+ }+ $name = $title = str_replace('.html', '', $filename);+ $description = '';+ $name = (!empty($folder) && $folder != DS) ? "$folder-$name" : $name;++ if (isset($friendlyNames[$name])) {+ $description = $friendlyNames[$name]['description'];++ $title = $friendlyNames[$name]['name'];+ }++ $url = PUBLIC_PATH . "themes/$theme/$file";+ $title = str_replace('index', 'home', $title);++ $pages[$name] = ['name' => $name, 'filename' => $filename, 'file' => $file, 'url' => $url, 'title' => humanReadable($title), 'folder' => $path, 'description' => $description, 'global' => $friendlyNames[$name]['global'] ?? false];++ if (isset($friendlyNames[$name]['editor'])) {+ $pages[$name]['editor'] = $friendlyNames[$name]['editor'];+ }+ }++ //ksort($pages);++ return $pages;+}diff --git a/system/functions/translation.php b/system/functions/translation.phpnew file mode 100755index 0000000..e49f297--- /dev/null+++ b/system/functions/translation.php@@ -0,0 +1,104 @@+<?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;++if ((!defined('GETTEXT') || GETTEXT == true) && function_exists('_')) {+ /**+ * Translates text using gettext.+ *+ * @param string $text The text to translate.+ * @param string|false $plural The plural form of the text.+ * @param int|false $count The count for plural translation.+ * @param bool $nocache Whether to bypass the translation cache.+ *+ * @return string The translated text.+ */+ function __($text, string|false $plural = false, int|false $count = false, bool $nocache = false): string {+ if ($plural) {+ $translation = ngettext($text, $plural, (int)$count);+ } else {+ $translation = gettext($text);+ }++ //list($text, $plural, $count, $translation) = System\Event::trigger(__NAMESPACE__, '__', $text, $plural, $count, $translation);++ return $translation;+ }+} else {+ /**+ * Translates text using custom PO file parser.+ *+ * @param string $text The text to translate.+ * @param string|false $plural The plural form of the text.+ * @param int|false $count The count for plural translation.+ * @param bool $nocache Whether to bypass the translation cache.+ *+ * @return string The translated text.+ */+ function __($text, string|false $plural = false, int|false $count = false, bool $nocache = false): string {+ static $translations;++ if (($translations === null || $nocache) && !isEditor()) {+ $translations = [];+ $lang = System\Locale::getLanguage();++ $cacheFile = DIR_CACHE . $lang . '-translations.php';++ if (file_exists($cacheFile)) {+ $translations = require $cacheFile;+ } else {+ $folder = DIR_ROOT . 'locale' . DS . $lang . DS . 'LC_MESSAGES' . DS;+ if (is_dir($folder)) {+ require_once DIR_SYSTEM . 'functions' . DS . 'php-mo.php';++ foreach (['vvveb', 'user'] as $domain) {+ $poFile = $folder . $domain . '.po';+ if (file_exists($poFile) && ($t = phpmo_parse_po_file($poFile) ?: [])) {+ $translations = array_merge($translations, $t);+ }+ }++ foreach ($translations as $id => &$msg) {+ $msg = $msg['msgstr'];+ }++ file_put_contents($cacheFile, '<?php return ' . var_export($translations, true) . ';');+ }+ }+ }++ if (isset($translations[$text])) {+ if ($count && $plural) {+ $translation = $translations[$text][1] ?? $translations[$text][0] ?? $text;+ } else {+ $translation = $translations[$text][0] ?? $text;+ }+ } else {+ $translation = $text;+ }++ //list($text, $plural, $count, $translation) = System\Event::trigger(__NAMESPACE__, '__', $text, $plural, $count, $translation);++ return $translation;+ }+}diff --git a/system/functions/ui.php b/system/functions/ui.phpnew file mode 100755index 0000000..553c667--- /dev/null+++ b/system/functions/ui.php@@ -0,0 +1,444 @@+<?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;++/**+ * Convert a date to a human-friendly relative format.+ *+ * @param string|int $date Date string or Unix timestamp+ *+ * @return string|int Human-friendly date string, or original timestamp if too far in the future+ */+function friendlyDate(string|int $date): string|int {+ $fileformats = [+ 1 => static fn ($i) => __('%d second', '%d seconds', $i),+ 60 => static fn ($i) => __('%d minute', '%d minutes', $i),+ 3600 => static fn ($i) => __('%d hour', '%d hours', $i),+ 86400 => static fn ($i) => __('%d day', '%d days', $i),+ 604800 => static fn ($i) => __('%d week', '%d weeks', $i),+ 2592000 => static fn ($i) => __('%d month', '%d months', $i),+ 31536000 => static fn ($i) => __('%d year', '%d years', $i),+ 315360000 => static fn ($i) => __('%d decade', '%d decades', $i),+ 3153600000 => static fn ($i) => __('%d century', '%d centuries', $i),+ ];++ $time_direction = __(' ago');++ if (is_string($date)) {+ $timestamp = strtotime($date);++ if ($timestamp === false) {+ return $date;+ }++ $date = $timestamp;+ }++ $diff = time() - $date + 10;++ if ($diff < 0) {+ $time_direction = __(' from now');+ $diff = abs($diff);+ }++ $lastTime = 1;+ //keep the closure, it is called with the computed unit count below+ $lastText = $fileformats[1];++ foreach ($fileformats as $time => $text) {+ if ($diff < $time) {+ $units = floor($diff / $lastTime);++ return sprintf($lastText($units), $units) . $time_direction;+ }+ $lastText = $text;+ $lastTime = $time;+ }++ return $date;+}++/**+ * Returns Bootstrap CSS class for order status badge.+ *+ * @param int $order_status_id Order status ID (1-7)+ *+ * @return string CSS class string for the badge+ */+function orderStatusBadgeClass(int $order_status_id = 1): string {+ $classes = [+ 1 => 'bg-primary-subtle text-body', //pending+ 2 => 'bg-info-subtle text-body', //processing+ 3 => 'bg-primary', //processed+ 4 => 'bg-success', //complete+ 5 => 'bg-danger', //canceled+ 6 => 'bg-secondary', //archived+ 7 => 'bg-warning', //requires_action+ ];++ return $classes[$order_status_id] ?? 'bg-warning text-dark';+}++/**+ * Returns Bootstrap CSS class for payment status badge.+ *+ * @param int $payment_status_id Payment status ID (1-10)+ *+ * @return string CSS class string for the badge+ */+function paymentStatusBadgeClass(int $payment_status_id = 1): string {+ $classes = [+ 1 => 'bg-warning-subtle text-body', //not_paid+ 2 => 'bg-success-subtle text-body', //awaiting+ 3 => 'bg-danger-subtle text-body', //captured+ 4 => 'bg-success', //paid+ 5 => 'bg-danger', //canceled+ 6 => 'bg-danger', //refunded+ 7 => 'bg-danger', //partially_refunded+ 8 => 'bg-danger', //chargeback+ 9 => 'bg-danger', //requires_action+ 10 => 'bg-danger', //fraud+ ];++ return $classes[$payment_status_id] ?? 'bg-warning text-dark';+}++/**+ * Returns Bootstrap CSS class for shipping status badge.+ *+ * @param int $shipping_status_id Shipping status ID (1-10)+ *+ * @return string CSS class string for the badge+ */+function shippingStatusBadgeClass(int $shipping_status_id = 1): string {+ $classes = [+ 1 => 'bg-warning-subtle text-body', //not_fulfilled+ 2 => 'bg-success-subtle text-body', //fulfilled+ 3 => 'bg-success-subtle text-body', //partially_fulfilled+ 4 => 'bg-success', //shipped+ 5 => 'bg-success-subtle text-body', //partially_shipped+ 6 => 'bg-danger-subtle text-body', //returned+ 7 => 'bg-danger-subtle text-body', //partially_returned+ 8 => 'bg-success', //delivered+ 9 => 'bg-danger', //canceled+ 10 => 'bg-warning', //requires_action+ ];++ return $classes[$shipping_status_id] ?? 'bg-warning text-dark';+}++/**+ * Returns Bootstrap CSS class for comment status badge.+ *+ * @param int $status Comment status ID (0-3)+ *+ * @return string CSS class string for the badge+ */+function commentStatusBadgeClass(int $status = 0): string {+ $classes = [+ 0 => 'bg-primary-subtle text-body', //pending+ 1 => 'bg-success-subtle text-body', //approved+ 2 => 'bg-warning-subtle text-body', //spam+ 3 => 'bg-danger-subtle text-body', //trash+ ];++ return $classes[$status] ?? 'bg-secondary-subtle text-dark';+}++/**+ * Return all available field type definitions.+ *+ * @return array<array-key, mixed> Associative array of field types grouped by category.+ */+function getFieldTypes(): array {+ return+ [+ 'basic' => [+ 'text' => [+ 'name' => __('Text'),+ 'icon' => 'text-size',+ ],+ 'textarea' => [+ 'name' => __('Textarea'),+ 'icon' => 'file-text',+ ],+ 'number' => [+ 'name' => __('Number'),+ 'icon' => 'file-text',+ ],+ 'range' => [+ 'name' => __('Range'),+ 'icon' => 'git-commit',+ ],+ 'email' => [+ 'name' => __('Email'),+ 'icon' => 'mail',+ ],+ 'url' => [+ 'name' => __('Url'),+ 'icon' => 'link',+ ],+ 'tel' => [+ 'name' => __('Telephone'),+ 'icon' => 'phone-call',+ ],+ 'password' => [+ 'name' => __('Password'),+ 'icon' => 'lock-open',+ ],+ 'select' => [+ 'name' => __('Select'),+ 'icon' => 'circle-chevron-down',+ ],+ ],+ 'content' => [+ 'image' => [+ 'name' => __('Image'),+ 'icon' => 'photo',+ ],+ 'file' => [+ 'name' => __('File'),+ 'icon' => 'file',+ ],+ 'wysiwyg' => [+ 'name' => __('Wysiwyg Editor'),+ 'icon' => 'pencil',+ ],+ 'oembed' => [+ 'name' => __('oEmbed'),+ 'icon' => 'video',+ ],+ 'gallery' => [+ 'name' => __('Gallery'),+ 'icon' => 'photo',+ ],+ ],+ 'choice' => [+ 'select' => [+ 'name' => __('Select'),+ 'icon' => 'circle-chevron-down',+ ],+ 'checkbox' => [+ 'name' => __('Checkbox'),+ 'icon' => 'checkbox',+ ],+ 'radio' => [+ 'name' => __('Radio Button'),+ 'icon' => 'circle-check',+ ],+ 'toggle' => [+ 'name' => __('Toggle'),+ 'icon' => 'toggle-left',+ ],+ ],+ 'relational' => [+ 'link' => [+ 'name' => __('Link'),+ 'icon' => 'link',+ ],+ 'post' => [+ 'name' => __('Post'),+ 'icon' => 'file-text',+ ],+ 'product' => [+ 'name' => __('Product'),+ 'icon' => 'box',+ ],+ 'relationship' => [+ 'name' => __('Relationship'),+ 'icon' => 'link',+ ],+ 'taxonomy' => [+ 'name' => __('Taxonomy'),+ 'icon' => 'grid-dots',+ ],+ 'user' => [+ 'name' => __('User'),+ 'icon' => 'user',+ ],+ ],+ 'widgets' => [+ 'google_map' => [+ 'name' => __('Google Map'),+ 'icon' => 'map',+ ],+ 'color' => [+ 'name' => __('Color'),+ 'icon' => 'icon-color-palette-outline',+ ],+ 'time' => [+ 'name' => __('Time'),+ 'icon' => 'clock',+ ],+ 'date' => [+ 'name' => __('Date'),+ 'icon' => 'calendar-month',+ ],+ 'date_time' => [+ 'name' => __('Date time'),+ 'icon' => 'calendar-off',+ ],+ 'month' => [+ 'name' => __('Month'),+ 'icon' => 'calendar',+ ],+ 'week' => [+ 'name' => __('week'),+ 'icon' => 'calendar-month',+ ],+ ],+ 'advanced' => [+ 'message' => [+ 'name' => __('Message'),+ 'icon' => 'circle-chevron-down',+ ],+ 'accordion' => [+ 'name' => __('Accordion'),+ 'icon' => 'circle-chevron-down',+ ],+ 'tab' => [+ 'name' => __('Tab'),+ 'icon' => 'circle-chevron-down',+ ],+ ],+ ];+}++/**+ * Return the fully qualified class name for a field type.+ *+ * @param string $fieldType The field type identifier.+ *+ * @return string|null The fully qualified class name, or null if not found.+ */+function fieldTypeClass(string $fieldType): ?string {+ $field = ucfirst($fieldType);+ $fieldClass = "Vvveb\System\Fields\\$field";++ if (!class_exists($fieldClass)) {+ return null;+ }++ return $fieldClass;+}++/**+ * Returns available post types for a given type category.+ *+ * @param string $type The type category (e.g. 'post', 'product').+ *+ * @return array<array-key, mixed>+ */+function postTypes(string $type): array {+ $defaultTypes = [+ 'post' => [+ 'post' => [+ 'name' => 'Post',+ 'source' => 'default',+ 'site_id' => '0',+ 'type' => 'post',+ 'plural' => 'posts',+ 'icon' => 'file-text',+ 'comments' => true,+ ],+ 'page' => [+ 'name' => 'Page',+ 'source' => 'default',+ 'site_id' => '0',+ 'type' => 'page',+ 'plural' => 'pages',+ 'icon' => 'file',+ 'comments' => false,+ ],+ ],+ 'product' => [+ 'product' => [+ 'name' => 'Product',+ 'type' => 'product',+ 'site_id' => '0',+ 'source' => 'default',+ 'plural' => 'products',+ 'icon' => 'box',+ ],+ ],+ ];++ $default = $defaultTypes[$type] ?? [];+ $typeName = ucfirst($type);+ [$pluginTypes] = System\Event::trigger('Vvveb\postTypes', "custom$typeName", []);+ array_walk($pluginTypes, function(&$type, $key): void {+ $type['source'] = 'plugin';+ $type['name'] = ucfirst($key);+ });++ $userTypes = getSetting($type, 'types', []);++ $params = ['module' => "settings/{$type}-type"];+ $paramsList = ['module' => "settings/{$type}-types"];++ array_walk($userTypes, function(&$type, $key) use ($params, $paramsList): void {+ $type['source'] = 'user';+ $type['name'] = ucfirst($key);+ $type['url'] = \Vvveb\url($params + ['type' => $type['type']]);+ $type['delete-url'] = \Vvveb\url($paramsList + ['action' => 'delete', 'type[]' => $type['type']]);+ });++ return $default + $pluginTypes + $userTypes;+}++/**+ * Formats invoice number by replacing template placeholders with data.+ *+ * @param string $format The format string containing {placeholders} like {year}, {month}, {rand-no-6}+ * @param array<string,mixed> $data Array of replacement values+ *+ * @return string The formatted invoice string+ */+function invoiceFormat(string $format, array $data): string {+ if (!$format) {+ return '';+ }+ $data += ['date_added' => time(), 'year' => date('Y'), 'year2' => date('y'), 'month_name' => date('M'), 'month' => date('m'), 'day' => date('d')];++ return preg_replace_callback('/{(.+?)}/', function($matches) use ($data) {+ $key = $matches[1];++ if (isset($data[$key])) {+ return $data[$key];+ }++ if (str_contains($key, 'rand-no-')) {+ $length = (int)str_replace('rand-no-', '', $key);++ return randomDigits($length);+ }++ if (str_contains($key, 'rand-str-')) {+ $length = (int)str_replace('rand-str-', '', $key);++ return strtoupper(System\Functions\Str::random($length));+ }++ return $matches[0];+ }, $format);+}diff --git a/system/functions/url.php b/system/functions/url.phpnew file mode 100644index 0000000..4dc61e7--- /dev/null+++ b/system/functions/url.php@@ -0,0 +1,413 @@+<?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;++/**+ * Resolve a redirect Location against the current URL (RFC 3986):+ * absolute urls pass through, root-relative resolve against the origin,+ * relative resolve against the containing directory. Pure, tested.+ *+ * @param string $base The current URL.+ * @param string $location The redirect Location value.+ *+ * @return string The resolved absolute URL, or '' when unresolvable.+ */+function resolveUrl(string $base, string $location): string {+ $location = trim($location);++ if (preg_match('#^https?://#i', $location)) {+ return $location;+ }++ $parts = parse_url($base);++ if (!is_array($parts) || ($parts['host'] ?? '') === '') {+ return '';+ }++ $scheme = strtolower($parts['scheme'] ?? 'https');+ $prefix = $scheme . '://' . $parts['host'] . (isset($parts['port']) ? ':' . $parts['port'] : '');++ if (str_starts_with($location, '/')) {+ return $prefix . $location;+ }++ $path = (string)($parts['path'] ?? '');++ if (!str_ends_with($path, '/')) {+ $path = (string)preg_replace('#/[^/]*$#', '', rtrim($path, '/'));+ }++ return $prefix . rtrim($path, '/') . '/' . ltrim($location, '/');+}++/**+ * Generate a URL from a route name or array of parameters.+ *+ * @param string|array<string,mixed> $parameters Route name or URL parameters+ * @param array<string,mixed>|bool $mergeParameters Parameters to merge with existing URL parameters+ * @param bool $useCurrentUrl Whether to use the current URL as base+ *+ * @return string The generated URL+ */+function url(string|array $parameters, array|bool $mergeParameters = false, bool $useCurrentUrl = true): string {+ if (is_string($parameters) && $parameters) {+ $result = '';++ if (isset($mergeParameters['scheme'])) {+ $result .= $mergeParameters['scheme'] . ':';+ unset($mergeParameters['scheme']);+ }++ if (isset($mergeParameters['host'])) {+ $result .= '//' . \Vvveb\System\Sites::url($mergeParameters['host']);+ unset($mergeParameters['host']);++ if (isset($mergeParameters['scheme'])) {+ $result = $mergeParameters['scheme'] . ":$result";+ unset($mergeParameters['scheme']);+ }+ }++ $path = $mergeParameters['path'] ?? SITE_PATH;++ $url = System\Routes::url($parameters, $mergeParameters);+ $result .= V_SUBDIR_INSTALL . $path . ($url ?? '');+ } else {+ static $url = '';+ static $urlParams = [];++ if ($useCurrentUrl && !$url) {+ $url = parse_url($_SERVER['REQUEST_URI'] ?? '');++ if (isset($url['query'])) {+ parse_str($url['query'], $urlParams);+ }+ }++ if (!is_array($parameters)) {+ $parameters = [];+ }++ if ($mergeParameters) {+ if (is_array($mergeParameters)) {+ $mergeParameters = array_merge($urlParams, $mergeParameters);+ } else {+ $mergeParameters = $urlParams;+ }++ if (is_array($mergeParameters)) {+ $parameters = array_merge($mergeParameters, $parameters);+ }+ }++ $result = '';+ $path = $parameters['path'] ?? SITE_PATH;++ if (isset($parameters['host'])) {+ $result .= '//' . \Vvveb\System\Sites::url($parameters['host']);+ unset($parameters['host']);++ if (isset($parameters['scheme'])) {+ $result = $parameters['scheme'] . ":$result";+ unset($parameters['scheme']);+ }+ } else {+ if (!$useCurrentUrl) {+ $result .= V_SUBDIR_INSTALL . $path;+ }+ }++ $result .= ($useCurrentUrl ? $url['path'] ?? '' : '') . ($parameters ? '?' . urldecode(http_build_query($parameters)) : '');+ }++ return $result;+}++/**+ * Get the current template name.+ *+ * @return string|false|null Template name, or false/null if not set+ */+function getCurrentTemplate(): string|false|null {+ return System\Core\View :: getInstance()->template();+}++/**+ * Get route data for a given URL.+ *+ * @param string $url The URL to look up+ *+ * @return array<array-key, mixed>|false Route data array, or false if not found+ */+function getUrlRoute(string $url): array|false {+ return \Vvveb\System\Routes::getUrlData($url);+}++/**+ * Get the current request URI.+ *+ * @return string Current request URI+ */+function getCurrentUrl(): string {+ return $_SERVER['REQUEST_URI'] ?? '';+}++/**+ * Get the admin path URL.+ *+ * @return string Admin path with leading and trailing slashes+ */+function adminPath(): string {+ return V_SUBDIR_INSTALL . '/' . \Vvveb\config('admin.path', 'admin') . '/';+}++/**+ * Get the public URL path.+ *+ * @return string Public URL path+ */+function publicUrlPath(): string {+ $public_path = PUBLIC_PATH;++ if (V_SUBDIR_INSTALL) {+ $public_path = str_replace(V_SUBDIR_INSTALL, '', $public_path);+ }++ if ($public_path == '/public/' || $public_path == '/public/admin/') {+ return PUBLIC_PATH;+ } else {+ return '/';+ }+}++/**+ * Get the current theme URL path.+ *+ * @return string Theme URL path+ */+function themeUrlPath(): string {+ $theme = \Vvveb\System\Core\View::getInstance()->getTheme();+ if (APP == 'app') {+ $path = PUBLIC_THEME_PATH . 'themes/' . $theme . '/';+ } else {+ $path = PUBLIC_THEME_PATH . $theme . '/';+ }++ return $path;+}++/**+ * Return current module name.+ *+ * @return string+ */+function getModuleName(): string {+ return strtolower(\Vvveb\System\Core\FrontController::getModuleName());+}++/**+ * Return current action name.+ *+ * @return string+ */+function getActionName(): string {+ return strtolower(\Vvveb\System\Core\FrontController::getActionName());+}++/**+ * Check if the page is loaded in the editor.+ *+ * @return bool+ */+function isEditor(): bool {+ return isset($_GET['r']);+}++/**+ * Checks if the current user is an admin.+ *+ * @return bool True if the current user is an admin, false otherwise.+ */+function isAdmin(): bool {+ return (bool)System\User\Admin::current();+}++/**+ * Get a request parameter value.+ *+ * @param string $key The request parameter key.+ *+ * @return mixed The parameter value, or false if not set.+ */+function get(string $key): mixed {+ return System\Core\Request::getInstance()->get[$key] ?? false;+}++/**+ * Downloads content from a URL using cURL or file_get_contents.+ *+ * @param string $url The URL to download.+ *+ * @return string|null The downloaded content, or null on failure.+ */+function download(string $url): ?string {+ $result = null;++ $url = html_entity_decode($url);+ $ips = validateUrl($url);++ if (!$ips) {+ return null;+ }++ if (function_exists('curl_init')) {+ $ch = curl_init($url);++ if ($ch) {+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);+ curl_setopt($ch, CURLOPT_RESOLVE, $ips);+ curl_setopt($ch, CURLOPT_FAILONERROR, true);+ curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);+ curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT'] ?? 'Vvveb ' . V_VERSION);+ $result = curl_exec($ch);+ $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);++ if ($httpcode != 200) {+ return null;+ }+ }+ } else {+ if (ini_get('allow_url_fopen') == '1') {+ $context_options = [+ 'http' => [+ 'timeout' => 5,+ 'ignore_errors' => 1,+ ],+ ];+ $context = stream_context_create($context_options);+ $result = @file_get_contents($url, false, $context) ?: null;+ }+ }++ return $result;+}++/**+ * Fetches URL content with caching support.+ *+ * @param string $url The URL to fetch.+ * @param bool $cache Whether to cache the result (default true).+ * @param int $expire Cache expiration in seconds (default 604800).+ * @param int $timeout Request timeout in seconds (default 5).+ * @param bool $exception Whether to throw exceptions on failure (default true).+ *+ * @return mixed The fetched content, or null on failure.+ */+function getUrl(string $url, bool $cache = true, int $expire = 604800, int $timeout = 5, bool $exception = true): mixed {+ $cacheDriver = System\Cache :: getInstance();+ $cacheKey = md5($url);+ $result = false;++ $ips = validateUrl($url);++ if (!$ips) {+ return null;+ }++ if ($cache && ($result = $cacheDriver->get('url', $cacheKey))) {+ return $result;+ } else {+ $result = false;+ $url = html_entity_decode($url);+ //try with curl+ if (function_exists('curl_init') && ($ch = curl_init($url))) {+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);+ curl_setopt($ch, CURLOPT_RESOLVE, $ips);+ curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);+ curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);+ curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT'] ?? 'Vvveb ' . V_VERSION);++ if (DEBUG) {+ curl_setopt($ch, CURLOPT_VERBOSE, true);+ $streamVerboseHandle = fopen('php://temp', 'w+');+ curl_setopt($ch, CURLOPT_STDERR, $streamVerboseHandle);+ }++ $result = curl_exec($ch);++ if ($result) {+ $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);+ if ($httpcode != 200) {+ return null;+ }++ if ($cache) {+ $cacheDriver->set('url', $cacheKey, $result);+ }++ return $result;+ } else {+ if ($exception) {+ $message = 'Curl error: ' . curl_errno($ch) . ' - ' . curl_error($ch);++ if (DEBUG) {+ $message .= "\n" . print_r(curl_getinfo($ch), true);+ rewind($streamVerboseHandle);+ $message .= "\n" . stream_get_contents($streamVerboseHandle);+ }++ throw new \Exception($message);+ }+ }+ } else {+ //try with file get contents+ if (ini_get('allow_url_fopen') == '1') {+ $context_options = [+ 'http' => [+ 'timeout' => $timeout,+ 'ignore_errors' => 1,+ ],+ ];++ $context = stream_context_create($context_options);++ if ($exception) {+ $result = file_get_contents($url, false, $context);+ } else {+ $result = @file_get_contents($url, false, $context);+ }+ }++ if ($result) {+ if ($cache) {+ $cacheDriver->set('url', $cacheKey, $result);+ }++ return $result;+ }+ }+ }++ return $result;+}diff --git a/system/functions/xml.php b/system/functions/xml.phpnew file mode 100644index 0000000..b2b98d2--- /dev/null+++ b/system/functions/xml.php@@ -0,0 +1,297 @@+<?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;++/**+ * Removes XML version declaration to avoid issues with PHP short open tags.+ *+ * @param string|null $xmlString The XML string to process+ *+ * @return string The XML string without the version declaration+ */+function xmlStripVersionDeclr(?string $xmlString): string {+ $xmlString = preg_replace('/<\?xml\s+version[^\?]+\?>\s*/', '', $xmlString ?? '') ?? '';++ //xml stylesheet+ return str_replace('<?xml-', '<?php echo \'<?xml-\';?>', $xmlString);+}++/**+ * Converts a PHP array to XML string using SimpleXMLElement.+ *+ * Supports attribute encoding via @@ prefix and type preservation markers (--array, --boolean, --int, --null, --object).+ *+ * @param array<string,mixed> $array The array to convert+ * @param \SimpleXMLElement|false $xml Existing XML element to append to, or false to create new+ *+ * @return string The XML string representation+ */+function array2xml(array $array, \SimpleXMLElement|false $xml = false): string {+ if ($xml === false) {+ $xml = new \SimpleXMLElement('<root/>');+ }++ foreach ($array as $key => $value) {+ $attributes = [];+ $processAttr = function(&$key) use (&$attributes): void {+ $i = 0;+ $start = 0;++ if ($key) {+ while (($start = strpos($key, '@@', $start))) {+ $i++;+ $start += 2;+ $end = (int)strpos($key, ' ', $start);+ $name = substr($key, $start, $end ? $end - $start : null);++ if ($end == 0) {+ $start += strlen($name);+ } else {+ $start = (int)$end;+ }++ if ($name) {+ $name = explode('=', $name);+ $attributes[$name[0]] = trim($name[1] ?? '', '\'"');+ }+ }++ $key = strstr($key, ' @@', true) ?: $key;+ }+ };++ $processAttr($key);++ if (is_array($value) || is_object($value)) {+ $node = $xml->addChild($key);++ if ($attributes) {+ foreach ($attributes as $key => $val) {+ $node->addAttribute($key, htmlspecialchars($val));+ }+ }+ array2xml($value, $node);+ } else {+ if (substr_compare($key, '--xmlattr', -9, 9) === 0) {+ $key = substr($key, 0, -9);+ $xml->addAttribute($key, htmlspecialchars($value));+ } else {+ $processAttr($value);++ if ($value && is_string($value)) {+ $value = htmlspecialchars($value);+ }+ $node = $xml->addChild($key, $value);++ if ($attributes) {+ foreach ($attributes as $key => $val) {+ $node->addAttribute($key, $val);+ }+ }+ }+ }+ }++ $xmlString = $xml->asXML();++ return xmlStripVersionDeclr($xmlString);+}++/**+ * Removes single-line and multi-line comments from a JSON string.+ *+ * @param string $json The JSON string with comments+ *+ * @return string The JSON string without comments+ */+function removeJsonComments(string $json): string {+ return preg_replace('@^\s*//.*([\r\n]|\s)*|^\s*/\*([\r\n]|.)*?\*/([\r\n]|\s)*@m', '', $json) ?? $json;+}++/**+ * Encodes invalid XML name characters to numeric entity format (_xNNN_).+ *+ * @param string $name The XML element or attribute name to encode+ *+ * @return string The encoded name with invalid characters replaced+ */+function encodeXmlName(string $name): string {+ $len = strlen($name);+ $newName = '';++ for ($i = 0; $i < $len; $i++) {+ $char = $name[$i];+ $code = ord($char);++ // = @ _ - . A-Z a-z 0-9+ if (($code >= 48 && $code <= 57) || ($code >= 65 && $code <= 90) || ($code >= 97 && $code <= 122) || $code === 32 || $code === 34 || $code === 45 || $code === 46 || $code === 61 || $code === 64 || $code === 95) {+ $char = '_x' . sprintf('%03d', $code) . '_';+ }++ $newName .= $char;+ }++ return $newName;+}++/**+ * Decodes encoded XML name characters back to their original form.+ *+ * @param string $name The encoded XML name to decode+ *+ * @return string The decoded name with _xNNN_ entities restored to characters+ */+function decodeXmlName(string $name): string {+ return preg_replace_callback('/_x(\d+)_/', fn ($matches) => chr((int)ltrim($matches[1], '0')), $name);+}++/**+ * Prepares an array for XML/JSON conversion by encoding keys and preserving PHP types.+ *+ * Encodes attribute markers (@, @@), preserves empty arrays/objects, booleans, integers, and nulls+ * using type suffix markers (--array, --boolean, --int, --null, --object).+ *+ * @param array<string,mixed> $array The array to prepare+ *+ * @return array<string,mixed> The prepared array with encoded keys+ */+function prepareJson(array $array): array {+ $helper = [];++ foreach ($array as $key => $value) {+ $key = (string)$key;++ if (is_numeric($key)) {+ $key = 'n--' . $key;+ }++ if ($key !== '' && $key[0] == '@') {+ if (isset($key[1]) && $key[1] == '@') {+ $key = substr($key, 2) . '--xmlattr';+ } else {+ $key = substr($key, 1) . '--attr';+ }+ }++ //keep empty arrays as array type+ if (is_array($value) && [] === $value) {+ $key .= '--array';+ }++ //keep boolean type+ if (is_bool($value)) {+ $key .= '--boolean';+ }++ //keep int type+ if (is_int($value)) {+ $key .= '--int';+ }++ //keep null type+ if ($value === null) {+ $key .= '--null';+ }++ $key = encodeXmlName(trim($key));++ $helper[$key] = is_array($value) ? prepareJson($value) : $value;+ }++ return $helper;+}++/**+ * Reverses prepareJson transformations to restore original array structure.+ *+ * Decodes type suffix markers, restores attribute prefixes, and converts numeric string keys back to integers.+ *+ * @param mixed $array The prepared array to reconstruct (passed by reference)+ * @param bool $removeAttrs Whether to remove @attributes keys entirely+ *+ * @return array<string,mixed>|null The reconstructed array<array-key, mixed>, or null if input is not iterable+ */+function reconstructJson(mixed &$array, bool $removeAttrs = false): mixed {+ if (!is_iterable($array)) {+ return null;+ }+ $helper = [];+ $array = (array)$array;++ foreach ($array as $key => $value) {+ if ($removeAttrs && $key == '@attributes') {+ continue;+ }++ $key = decodeXmlName($key);++ if (substr_compare($key, '--array', -7, 7) === 0) {+ $key = substr($key, 0, -7);+ $value = (array)$value;+ } else {+ if ($value === null) {+ $value = '';+ }+ }++ if (substr_compare($key, '--boolean', -9, 9) === 0) {+ $key = substr($key, 0, -9);+ $value = (bool)$value;+ }++ if (substr_compare($key, '--null', -6, 6) === 0) {+ $key = substr($key, 0, -6);+ $value = null;+ }++ if (substr_compare($key, '--int', -5, 5) === 0) {+ $key = substr($key, 0, -5);+ $value = (int)$value;+ }++ if (substr_compare($key, '--object', -8, 8) === 0) {+ $key = substr($key, 0, -8);+ $value = (object)$value;+ }++ if (substr_compare($key, 'n--', 0, 3) === 0) {+ $newkey = substr($key, 3);++ if (is_numeric($newkey)) {+ $key = (int)$newkey;+ }+ }++ if (substr_compare($key, '--xmlattr', -9, 9) === 0) {+ $key = '@@' . substr($key, 0, -9);+ }++ if (substr_compare($key, '--attr', -6, 6) === 0) {+ $key = '@' . substr($key, 0, -6);+ }++ $helper[$key] = (is_iterable($value)) ? reconstructJson($value, $removeAttrs) : $value;+ }++ return $helper;+}