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
Added '.tpl' to uploadDenyExtensions, removed superfluous isExecutableFile php is blocked from nginx.conf and .htaccess fix for GHSA-7h6v-ww3f-24pp
Givanb89c5ea323df
diff --git a/admin/controller/editor/code.php b/admin/controller/editor/code.phpold mode 100644new mode 100755index 3943482..3da6a25--- a/admin/controller/editor/code.php+++ b/admin/controller/editor/code.php@@ -31,9 +31,19 @@ use Vvveb\System\User\Admin;class Code extends Base {use MediaTrait;- protected $saveDenyExtensions = ['php', 'tpl', 'svg', 'js', 'exe', 'html', 'phtml', 'htaccess', 'phar'];-- function dirForType($type) {+ /**+ * @var array<int, string> File extensions denied for saving by non-admin roles.+ */+ protected array $saveDenyExtensions = ['php', 'tpl', 'svg', 'js', 'exe', 'html', 'phtml', 'htaccess', 'phar'];++ /**+ * Returns the base directory path for a given type.+ *+ * @param string $type The type (public, plugins, themes).+ *+ * @return string|false The directory path or false if invalid.+ */+ public function dirForType(string $type): string|false {switch ($type) {case 'public':$scandir = DIR_MEDIA;@@ -57,19 +67,29 @@ class Code extends Base {return $scandir;}- function init() {+ /**+ * Initializes the controller, setting the media directory based on type.+ *+ * @return string|null+ */+ public function init(): ?string {$type = $this->request->get['type'] ?? false;$this->dirMedia = $this->dirForType($type);return parent::init();}- function index() {+ /**+ * Main index action - sets up the code editor view with load/save endpoints.+ *+ * @return void+ */+ public function index(): void {$type = $this->request->get['type'] ?? false;$admin_path = \Vvveb\adminPath();$controllerPath = $admin_path . 'index.php?module=editor/code';- if (! $type) {+ if (!$type) {return;}@@ -79,14 +99,19 @@ class Code extends Base {$this->view->saveUrl = "$controllerPath&action=save&type=$type";$this->view->type = $type;- if ($type) {- $this->view->mediaPath = str_replace('/media', "/$type", $this->view->mediaPath);- }+ $this->view->mediaPath = str_replace('/media', "/$type", $this->view->mediaPath);}- function sanitizeFileName($file, $type) {- if (V_SUBDIR_INSTALL && strpos($file, V_SUBDIR_INSTALL) === 0) {- //$path = str_replace(V_SUBDIR_INSTALL, '', $path);+ /**+ * Sanitizes and validates a file path for the given type.+ *+ * @param string $file The raw file path.+ * @param string $type The file type (public, plugins, themes).+ *+ * @return string|false The sanitized full path or false if invalid.+ */+ public function sanitizeFileName(string $file, string $type): string|false {+ if (V_SUBDIR_INSTALL && str_starts_with($file, V_SUBDIR_INSTALL)) {$file = substr_replace($file, '', 0, strlen(V_SUBDIR_INSTALL));}@@ -107,14 +132,20 @@ class Code extends Base {$file = $dir . $file;$file = sanitizeFileName($file);- if (strncmp(realpath($file), $dir, strlen($dir)) !== 0) {+ $real = realpath($file);+ if ($real === false || strncmp($real, $dir, strlen($dir)) !== 0) {return false;}return $file;}- function save() {+ /**+ * Saves a code file with permission and extension checks.+ *+ * @return void+ */+ public function save(): void {$type = $this->request->get['type'];$filename = $this->request->get['file'];$content = $this->request->post['content'];@@ -126,15 +157,15 @@ class Code extends Base {if ($file) {$extension = strtolower(substr($file, strrpos($file, '.') + 1));- if (in_array($extension, $this->saveDenyExtensions) && (($admin = Admin::current()) && ! in_array($admin['role'], ['super_admin', 'admin']))) {+ if (in_array($extension, $this->saveDenyExtensions) && (($admin = Admin::current()) && !in_array($admin['role'], ['super_admin', 'admin']))) {$message = sprintf(__('Saving not allowed for file type %s for this role!'), trim($extension, '.'));$success = false;} else {- if ($extension == 'php' || $this->isExecutableFile($file)) {+ if (str_starts_with($extension, 'php')) {$message .= sprintf(__('File type %s not allowed!'), 'PHP');$success = false;} else {- if (! is_writable($file)) {+ if (!is_writable($file)) {$message = sprintf(__('File not writable: %s Check if file has write permission.'), $filename);$success = false;} else {@@ -152,32 +183,42 @@ class Code extends Base {$this->response->output($output);}- function loadFile() {+ /**+ * Loads and outputs a file's content.+ *+ * @return never+ */+ public function loadFile(): never {$type = $this->request->get['type'];$file = $this->request->get['file'];$file = $this->sanitizeFileName($file, $type);- if (! is_readable($file)) {- die("File not readable: $file");+ if (!is_readable($file)) {+ exit("File not readable: $file");}if ($content = file_get_contents($file)) {- die($content);+ exit($content);}- die("Error loading: $file");+ exit("Error loading: $file");}- function scan() {+ /**+ * Scans a directory tree recursively and outputs the result as JSON.+ *+ * @return void+ */+ public function scan(): void {$type = $this->request->get['type'] ?? 'public';$scandir = $this->dirForType($type);- if (! $scandir) {- return [];+ if (!$scandir) {+ return;}// This function scans the files folder recursively, and builds a large array- $scan = function ($dir) use ($scandir, &$scan) {+ $scan = function(string $dir) use ($scandir, &$scan): array {$files = [];// Is there actually such a folder/file?@@ -187,7 +228,7 @@ class Code extends Base {if ($listdir) {foreach ($listdir as $f) {- if (! $f || $f[0] == '.' || $f == 'node_modules' || $f == 'vendor') {+ if (!$f || $f[0] == '.' || $f == 'node_modules' || $f == 'vendor') {continue; // Ignore hidden files}diff --git a/system/traits/media.php b/system/traits/media.phpold mode 100644new mode 100755index 546384c..4ebd108--- a/system/traits/media.php+++ b/system/traits/media.php@@ -24,24 +24,20 @@ namespace Vvveb\System\Traits;use function Vvveb\__;use function Vvveb\fileUploadErrMessage;+use function Vvveb\humanReadable;use function Vvveb\parseQuantity;use function Vvveb\rrmdir;use function Vvveb\sanitizeFileName;use Vvveb\System\Event;+use Vvveb\System\User\Admin;-/**- * Trait providing file upload, deletion, renaming, folder creation, and directory scanning.- *- * Includes security checks for denied extensions, MIME types, executable signatures,- * and path traversal prevention.- */trait Media {/*** File extensions that are not allowed for upload.** @var list<string>*/- public array $uploadDenyExtensions = ['php', 'svg', 'js', 'exe', 'html', 'phtml', 'htaccess', 'phar'];+ public array $uploadDenyExtensions = ['php', 'tpl', 'svg', 'js', 'exe', 'html', 'phtml', 'htaccess', 'phar'];/*** MIME types that are not allowed for upload.@@ -57,13 +53,6 @@ trait Media {*/public array $stripMetadataMime = ['image/jpg', 'image/jpeg', 'image/png', 'image/webp', 'image/avif'];- /**- * Signatures checked at the start of a file to detect disguised executables.- *- * @var list<string>- */- public array $denySignatures = ['<?php'];-/*** Return the filesystem path for a given directory type.*@@ -71,28 +60,13 @@ trait Media {** @return string|false The directory path, or false if the type is invalid.*/- protected function dirForType(string $type) : string|false {- switch ($type) {- case 'public':- $scandir = DIR_MEDIA;-- break;-- case 'plugins':- $scandir = DIR_PLUGINS;-- break;-- case 'themes':- $scandir = DIR_THEMES;-- break;-- default:- return false;- }-- return $scandir;+ protected function dirForType(string $type): string|false {+ return match ($type) {+ 'public' => DIR_MEDIA,+ 'plugins' => DIR_PLUGINS,+ 'themes' => DIR_THEMES,+ default => false,+ };}/**@@ -103,7 +77,7 @@ trait Media {** @return void*/- protected function setMediaEndpoints(string $controllerPath, string $params = '') : void {+ protected function setMediaEndpoints(string $controllerPath, string $params = ''): void {$this->view->mediaUrl = $controllerPath;$this->view->scanUrl = "$controllerPath&action=scan$params";$this->view->uploadUrl = "$controllerPath&action=upload$params";@@ -113,159 +87,309 @@ trait Media {$this->view->postMaxSize = parseQuantity(ini_get('post_max_size'));}+/**- * Check whether the first 16 bytes of a file contain a denied signature.+ * Create a media library database record for a stored file.*- * @param string $file Absolute file path.+ * @param string $file Media-relative file path as returned by storeMediaFile().+ * @param string|null $type MIME type, detected from the stored file when omitted.*- * @return bool True if the file contains a denied signature (e.g. PHP tag).+ * @return mixed Model result, the existing record, or null when skipped/failed.*/- protected function isExecutableFile(string $file) : bool {- if (file_exists($file)) {- /** @var string|false $header */- $header = file_get_contents($file, false, null, 0, 16);- if ($header) {- foreach ($this->denySignatures as $signature) {- if (strpos($header, $signature) !== false) {- return true;+ protected function createMediaRecord(string $file, ?string $type = null): mixed {+ if ($file === '') {+ return null;+ }++ try {+ $global = (isset($this->global) && is_array($this->global)) ? $this->global : [];+ $model = \Vvveb\model('media_content');++ $existing = $model->get(['file' => $file] + $global);++ if ($existing) {+ return $existing;+ }++ $base = pathinfo(str_replace('\\', '/', $file), PATHINFO_FILENAME);+ $name = humanReadable($base);++ $languageId = $global['language_id'] ?? $global['default_language_id'] ?? 1;++ if ($type === null && isset($this->dirMedia)) {+ $absolute = $this->dirMedia . DS . $file;++ if (is_file($absolute)) {+ $detected = @mime_content_type($absolute);++ if (is_string($detected) && $detected !== '') {+ $type = $detected;}}}++ $media = ['file' => trim($file, " /\n\r\t\v\x00" . DS)];++ if ($type !== null && $type !== '') {+ $media['type'] = $type;+ }++ return $model->add([+ 'media' => $media,+ 'media_content' => [['name' => $name, 'language_id' => $languageId]],+ ]);+ } catch (\Throwable $e) {+ return null;}- return false;}/**- * Handle file upload(s) from the media manager.+ * Store one file in the media library.*- * Validates extensions, MIME types, file signatures, hidden files, and- * path traversal. Moves valid files to the destination directory and- * returns a JSON response.+ * @param string $srcPath Readable temp file with the bytes.+ * @param string $fileName Desired file name (sanitized here).+ * @param string $path Media sub-path, may be empty.+ * @param array{overwrite?: bool, onlyFilename?: bool, size?: int, error?: int, httpUpload?: bool} $opts Upload error code (UPLOAD_ERR_OK), overwrite and return-shape flags.*- * @return void+ * @return array{success: bool, message: string, file: string, size: int} Per-file result.*/- public function upload() : void {- /** @var array<int, array{name: list<string>, tmp_name: list<string>, error: list<int>, size: list<int>}> $files */- $files = $this->request->files['files'] ?? [];- /** @var bool $overwrite */- $overwrite = $this->request->post['overwrite'] ?? false;- $success = false;- $return = '';- $message = '';- /** @var list<array{success: bool, message: string, file: string, size?: int}> $response */- $response = [];+ protected function storeMediaFile(string $srcPath, string $fileName, string $path = '', array $opts = []): array {+ $overwrite = $opts['overwrite'] ?? false;+ $onlyFilename = $opts['onlyFilename'] ?? false;+ $size = $opts['size'] ?? (@filesize($srcPath) ?: 0);+ $error = $opts['error'] ?? UPLOAD_ERR_OK;+ $httpUpload = $opts['httpUpload'] ?? false;+ $success = false;+ $return = $fileName;+ $message = '';++ $path = sanitizeFileName($path);+ $fileName = sanitizeFileName($fileName);++ if (!$fileName || !is_file($srcPath)) {+ return ['success' => false, 'message' => __('Invalid upload!'), 'file' => $fileName, 'size' => 0];+ }- /** @var list<array{name: list<string>, tmp_name: list<string>, error: list<int>, size: list<int>}> $files */- list($files) = Event::trigger(__CLASS__, __FUNCTION__, $files, $this);+ if (V_SUBDIR_INSTALL && str_starts_with($path, V_SUBDIR_INSTALL)) {+ $path = substr_replace($path, '', 0, strlen(V_SUBDIR_INSTALL));+ }- if ($files) {- $length = count($files['name'] ?? []);+ $path = preg_replace('@.*[\\\/]public[\\\/]media|.*[\\\/]media|.*[\\\/]public@', '', $path);+ $extension = strtolower(substr($fileName, strrpos($fileName, '.') + 1));+ $mimeType = mime_content_type($srcPath);- for ($count = 0; $count < $length; $count++) {- $path = sanitizeFileName((string) ($this->request->post['mediaPath'] ?? ''));- $fileName = sanitizeFileName($files['name'][$count]);+ if ($error != UPLOAD_ERR_OK) {+ return ['success' => $success, 'message' => fileUploadErrMessage($error), 'file' => $fileName, 'size' => $size];+ }- if (! $fileName) {- continue;- }+ if (in_array($extension, $this->uploadDenyExtensions)) {+ return ['success' => false, 'message' => sprintf(__('File type %s not allowed!'), $extension), 'file' => $fileName, 'size' => $size];+ }- if (V_SUBDIR_INSTALL && strpos($path, V_SUBDIR_INSTALL) === 0) {- $path = substr_replace($path, '', 0, strlen(V_SUBDIR_INSTALL));- }+ if (in_array($mimeType, $this->uploadDenyMime)) {+ return ['success' => false, 'message' => sprintf(__('File type %s not allowed!'), $mimeType), 'file' => $fileName, 'size' => $size];+ }++ if (in_array($mimeType, $this->stripMetadataMime)) {+ //metadata stripping should be handled by the caller+ }++ //deny hidden files+ if ($fileName[0] === '.') {+ return ['success' => false, 'message' => __('Invalid upload!'), 'file' => $fileName, 'size' => $size];+ }++ //check if the path is inside the allowed path+ /** @var string|false $destination */+ $destination = realpath($this->dirMedia . DS . $path . DS);++ //ensure the media dir ends with a separator so that the prefix+ //check cannot be bypassed by sibling directories that share the+ //same name prefix (e.g. /var/www/media-evil vs /var/www/media)+ $mediaDir = rtrim($this->dirMedia, DS) . DS;+ $destination = $destination === false ? false : rtrim($destination, DS) . DS;++ if ($destination === false || !str_starts_with($destination, $mediaDir)) {+ return ['success' => false, 'message' => __('Invalid upload!'), 'file' => $fileName, 'size' => $size];+ }++ $origFilename = $fileName;+ $i = 1;+ $destination .= DS . $fileName;++ if (!$overwrite) {+ while (file_exists($destination = $this->dirMedia . $path . DS . $fileName) && ($i++ < 5)) {+ $fileName = random_int(0, 10000) . '-' . $origFilename;+ }+ }++ $moved = $httpUpload ? @move_uploaded_file($srcPath, $destination) : @rename($srcPath, $destination);++ if ($moved) {+ $return = $onlyFilename ? $fileName : $path . DS . $fileName;+ $message = __('File uploaded successfully!');++ return ['success' => true, 'message' => $message, 'file' => $return, 'size' => $size];+ }++ $destination = $this->dirMedia . $path . DS;++ if (!is_writable((string)$destination)) {+ $message = sprintf(__('%s not writable!'), $destination);+ } else {+ $message = __('Error moving uploaded file!');+ }++ return ['success' => false, 'message' => $message, 'file' => $return, 'size' => $size];+ }- $path = preg_replace('@.*[\\\/]public[\\\/]media|.*[\\\/]media|.*[\\\/]public@', '', $path);- $extension = strtolower(substr($fileName, strrpos($fileName, '.') + 1));- $mimeType = mime_content_type($files['tmp_name'][$count]);+ /**+ * Create a folder inside the media directory.+ *+ * @param string $path Parent media sub-path, may be empty.+ * @param string $folder New folder name.+ *+ * @return array{success: bool, message: string} Result.+ */+ protected function createMediaFolder(string $path, string $folder): array {+ $folder = sanitizeFileName($folder);+ $path = sanitizeFileName($path);+ $success = false;++ $dirMedia = $this->dirMedia;- if ($files['error'][$count] == UPLOAD_ERR_OK) {+ if (is_dir($dirMedia . $path)) {+ if (is_dir($dirMedia . $path . DS . $folder)) {+ $message = __('Folder already exists!');+ } else {+ if (@mkdir($dirMedia . $path . DS . $folder)) {+ $message = __('Folder created!');$success = true;} else {- $message = fileUploadErrMessage($files['error'][$count]);- $response[] = ['success' => $success, 'message' => $message, 'file' => $fileName];- continue;+ $message = __('Error creating folder!');}+ }+ } else {+ $message = __('Path does not exist!');+ }- if (in_array($extension, $this->uploadDenyExtensions)) {- $message .= sprintf(__('File type %s not allowed!'), $extension);- $success = false;- $response[] = ['success' => $success, 'message' => $message, 'file' => $fileName];- continue;- }+ return ['success' => $success, 'message' => $message];+ }- if (in_array($mimeType, $this->uploadDenyMime)) {- $message .= sprintf(__('File type %s not allowed!'), $mimeType);- $success = false;- $response[] = ['success' => $success, 'message' => $message, 'file' => $fileName];- continue;- }+ /**+ * Rename (or copy) a media file.+ *+ * @param string $file Current media-relative file path.+ * @param string $newfile New media-relative path, alternative to $newname.+ * @param string $newname New file name inside the current directory.+ * @param bool $duplicate Copy instead of renaming.+ *+ * @return array{success: bool, message: string} Result.+ */+ protected function renameMediaFile(string $file, string $newfile = '', string $newname = '', bool $duplicate = false): array {+ $file = sanitizeFileName($file);+ $newfile = sanitizeFileName($newfile);+ $newname = sanitizeFileName($newname);- if (in_array($mimeType, $this->stripMetadataMime)) {- //metadata stripping should be handled by the caller- $files['tmp_name'][$count];- }+ $dirMedia = $this->dirMedia;- //deny hidden files- if ($fileName[0] === '.') {- $message .= __('Invalid upload!');- $success = false;- $response[] = ['success' => $success, 'message' => $message, 'file' => $fileName];- continue;- }+ $currentFile = $dirMedia . DS . $file;+ /** @var string $targetFile */+ $targetFile = $currentFile;- //check if the path is inside the allowed path- /** @var string|false $destination */- $destination = realpath($this->dirMedia . DS . $path . DS);- if (strncmp((string) $destination, $this->dirMedia, strlen($this->dirMedia) - 1) !== 0) {- $message .= __('Invalid upload!');- $success = false;- $response[] = ['success' => $success, 'message' => $message, 'file' => $fileName];- continue;- }+ if ($newfile) {+ $targetFile = $dirMedia . DS . $newfile;+ }- //check if it's not a php file disguised as an image- if ($this->isExecutableFile($files['tmp_name'][$count])) {- $message .= sprintf(__('File type %s not allowed!'), 'PHP');- $success = false;- $response[] = ['success' => $success, 'message' => $message, 'file' => $fileName];- continue;+ if ($newname) {+ $targetFile = dirname($currentFile) . DS . $newname;+ }++ //both ends must resolve inside the media dir (target parent is+ //checked since renames may point at not-yet-existing names)+ $mediaDir = rtrim($dirMedia, DS) . DS;++ foreach ([dirname($currentFile), dirname($targetFile)] as $parent) {+ $real = realpath($parent);++ if ($real === false || !str_starts_with(rtrim($real, DS) . DS, $mediaDir)) {+ return ['success' => false, 'message' => __('Invalid file!')];+ }+ }++ $extension = strtolower(substr($targetFile, strrpos($targetFile, '.') + 1));++ if (in_array($extension, $this->uploadDenyExtensions)) {+ return ['success' => false, 'message' => __('File type not allowed!')];+ }++ if ($duplicate) {+ if (@copy($currentFile, $targetFile)) {+ return ['success' => true, 'message' => __('File copied!')];+ }++ return ['success' => false, 'message' => __('Error copying file!')];+ }++ if (@rename($currentFile, $targetFile)) {+ return ['success' => true, 'message' => __('File renamed!')];+ }++ return ['success' => false, 'message' => __('Error renaming file!')];+ }++ /**+ * Handle file upload(s) from the media manager.+ *+ * @return void+ */+ public function upload(): void {+ /** @var array<int, array{name: list<string>, tmp_name: list<string>, error: list<int>, size: list<int>}> $files */+ $files = $this->request->files['files'] ?? [];+ /** @var list<array{success: bool, message: string, file: string, size?: int}> $response */+ $response = [];++ /** @var list<array{name: list<string>, tmp_name: list<string>, error: list<int>, size: list<int>}> $files */+ [$files] = Event::trigger(__CLASS__, __FUNCTION__, $files, $this);++ if ($files) {+ //normalize single-file uploads to the multi-file shape+ foreach (['name', 'tmp_name', 'error', 'size'] as $key) {+ if (isset($files[$key]) && !is_array($files[$key])) {+ $files[$key] = [$files[$key]];}+ }- $origFilename = $fileName;- $i = 1;+ $length = count($files['name'] ?? []);- if ($success) {- $destination .= DS . $fileName;- $message .= $destination;- if (! $overwrite) {- while (file_exists($destination = $this->dirMedia . $path . DS . $fileName) && ($i++ < 5)) {- $fileName = rand(0, 10000) . '-' . $origFilename;- }- }+ for ($count = 0; $count < $length; $count++) {+ $fileName = sanitizeFileName($files['name'][$count]);- if (@move_uploaded_file($files['tmp_name'][$count], $destination)) {- if (isset($this->request->post['onlyFilename'])) {- $return = $fileName;- } else {- $return = $path . DS . $fileName;- }- $message = __('File uploaded successfully!');- } else {- $destination = $this->dirMedia . $path . DS;- $success = false;+ if (!$fileName) {+ continue;+ }- if (! is_writable((string) $destination)) {- $message = sprintf(__('%s not writable!'), $destination);- } else {- $message = __('Error moving uploaded file!');- }- }+ $stored = $this->storeMediaFile(+ $files['tmp_name'][$count],+ $files['name'][$count],+ (string)($this->request->post['mediaPath'] ?? ''),+ [+ 'overwrite' => $this->request->post['overwrite'] ?? false,+ 'onlyFilename' => isset($this->request->post['onlyFilename']),+ 'size' => $files['size'][$count] ?? 0,+ 'error' => $files['error'][$count] ?? UPLOAD_ERR_OK,+ 'httpUpload' => true,+ ]+ );++ if (($stored['success'] ?? false)) {+ $this->createMediaRecord($stored['file']);}- $response[] = ['success' => $success, 'message' => $message, 'file' => $return, 'size' => $files['size'][$count]];+ $response[] = $stored;}} else {- $message = __('Invalid upload!');- $response[] = ['success' => $success, 'message' => $message, 'file' => $return];+ $response[] = ['success' => false, 'message' => __('Invalid upload!'), 'file' => ''];}$this->response->setType('json');@@ -275,14 +399,11 @@ trait Media {/*** Delete a file or directory from the media folder.*- * Supports deleting a single file/directory or an array of files.- * Returns a JSON response.- ** @return void*/- public function delete() : void {+ public function delete(): void {/** @var string|array<int, string> $file */- $file = $this->request->post['file'];+ $file = $this->request->post['file'] ?? false;/** @var array{success: bool, message: string} $message */$message = ['success' => false, 'message' => __('Error deleting file!')];$themeFolder = $this->dirMedia;@@ -290,7 +411,7 @@ trait Media {if ($file) {if (is_array($file)) {foreach ($file as $f) {- $f = sanitizeFileName($f);+ $f = sanitizeFileName($f);$path = $themeFolder . DS . $f;if (@unlink($path)) {@@ -323,116 +444,59 @@ trait Media {/*** Rename or copy a file in the media folder.*- * When $duplicate is true, the file is copied instead of renamed.- * Returns a JSON response.- ** @return void*/- public function rename() : void {- $file = sanitizeFileName($this->request->post['file']);- $newfile = sanitizeFileName((string) ($this->request->post['newfile'] ?? ''));- $newname = sanitizeFileName((string) ($this->request->post['newname'] ?? ''));- /** @var bool $duplicate */- $duplicate = $this->request->post['duplicate'] ?? false;- $dirMedia = $this->dirMedia;+ public function rename(): void {+ $message = $this->renameMediaFile(+ (string)($this->request->post['file'] ?? ''),+ (string)($this->request->post['newfile'] ?? ''),+ (string)($this->request->post['newname'] ?? ''),+ (bool)($this->request->post['duplicate'] ?? false)+ );$this->response->setType('json');-- $currentFile = $dirMedia . DS . $file;- /** @var string $targetFile */- $targetFile = $currentFile;-- if ($newfile) {- $targetFile = $dirMedia . DS . $newfile;- }-- if ($newname) {- $targetFile = dirname($currentFile) . DS . $newname;- }-- $extension = strtolower(substr($targetFile, strrpos($targetFile, '.') + 1));-- if (in_array($extension, $this->uploadDenyExtensions)) {- $message = ['success' => false, 'message' => __('File type not allowed!')];- $this->response->output($message);- return;- }-- if ($duplicate) {- if (copy($currentFile, $targetFile)) {- $message = ['success' => true, 'message' => __('File copied!')];- } else {- $message = ['success' => false, 'message' => __('Error copying file!')];- }- } else {- if (rename($currentFile, $targetFile)) {- $message = ['success' => true, 'message' => __('File renamed!')];- } else {- $message = ['success' => false, 'message' => __('Error renaming file!')];- }- }-$this->response->output($message);}/*** Create a new folder inside the media directory.*- * Returns a JSON response with success or error message.- ** @return void*/- public function newFolder() : void {- $folder = sanitizeFileName($this->request->post['folder']);- $path = sanitizeFileName($this->request->post['path']);- $success = false;-- $dirMedia = $this->dirMedia;-- if (is_dir($dirMedia . $path)) {- if (is_dir($dirMedia . $path . DS . $folder)) {- $message = __('Folder already exists!');- } else {- if (@mkdir($dirMedia . $path . DS . $folder)) {- $message = __('Folder created!');- $success = true;- } else {- $message = __('Error creating folder!');- }- }- } else {- $message = __('Path does not exist!');- }-- $message = ['success' => $success, 'message' => $message];+ public function newFolder(): void {+ $message = $this->createMediaFolder(+ (string)($this->request->post['path'] ?? ''),+ (string)($this->request->post['folder'] ?? '')+ );$this->response->setType('json');$this->response->output($message);}- /**- * Recursively scan the media directory and return a JSON tree of files and folders.- *- * @return void- */- public function scan() : void {+ public function _scan(string $path = '', $type = 'public', ?int $levels = null, int $start = 0, ?int $limit = null, ?int &$total = null): array {+ $path = sanitizeFileName($path);$scandir = $this->dirMedia;- if (isset($this->dirMediaType) && $this->dirMediaType) {+ if ($type) {/** @var string $type */- $type = $this->request->get['type'] ?? 'public';$scandir = $this->dirForType($type);}- if (! $scandir) {- $this->response->setType('json');- $this->response->output([]);- return;+ if (!$scandir) {+ return [];}- // This function scans the files folder recursively, and builds a large array- /** @var \Closure(string): list<array{name: string, type: string, path: string, items?: mixed[], size?: int}> $scan */- $scan = function (string $dir) use ($scandir, &$scan) : array {+ // node paths stay relative to the media root (not the requested+ // sub-path) so scoped listings splice straight into the client tree+ $mediaRoot = rtrim($scandir, DS);+ $scandir .= ($path ? DS . ltrim($path, DS) : '');++ // Scan one directory level; subfolders recurse only while the depth+ // budget lasts. $levels = 1 lists just the requested folder, deeper+ // folders come back with items=null as an "unloaded" marker for lazy+ // fetch. A null $levels keeps the legacy full-tree behavior.+ /** @var \Closure(string, int): list<array{name: string, type: string, path: string, items?: mixed[], size?: int}> $scan */+ $scan = function(string $dir, int $level = 1) use ($mediaRoot, &$scan, $levels): array {$files = [];// Is there actually such a folder/file?@@ -443,18 +507,24 @@ trait Media {if ($listdir) {foreach ($listdir as $f) {- if (! $f || $f[0] === '.' || $f === 'node_modules' || $f === 'vendor') {- continue;// Ignore hidden files+ if (!$f || $f[0] === '.' || $f === 'node_modules' || $f === 'vendor') {+ continue; // Ignore hidden files}+ $path = '/' . trim(str_replace([$mediaRoot, '\\'], ['', '/'], $dir) . '/' . trim($f, '/'), '/');if (is_dir($dir . DS . $f)) {// The path is a folder+ if ($levels === null || $level < $levels) {+ $items = $scan($dir . DS . $f, $level + 1);+ } else {+ $items = null;+ }$files[] = ['name' => $f,'type' => 'folder',- 'path' => str_replace([$scandir, '\\'], ['', '/'], $dir) . '/' . $f,- 'items' => $scan("$dir/$f"),+ 'path' => $path,+ 'items' => $items,];} else {// It is a file@@ -462,7 +532,7 @@ trait Media {$files[] = ['name' => $f,'type' => 'file',- 'path' => str_replace([$scandir, '\\'], ['', '/'], $dir) . '/' . $f,+ 'path' => $path,'size' => filesize("$dir/$f"),];}@@ -473,14 +543,168 @@ trait Media {return $files;};- $response = $scan($scandir);+ $response = $scan($scandir, 1);- $this->response->setType('json');- $this->response->output([- 'name' => '',+ $total = count($response);++ if ($limit !== null) {+ $dirs = [];+ $files = [];++ foreach ($response as $node) {+ if (($node['type'] ?? '') === 'folder') {+ $dirs[] = $node;+ } else {+ $files[] = $node;+ }+ }++ $response = array_slice(array_merge($dirs, $files), max(0, $start), max(0, $limit));+ }++ return $response;+ }++ /**+ * List one media folder level, a scoped subtree, or filename matches.+ *+ * @param string $path Folder to list, default root.+ * @param int|null $levels Depth budget, default 1 (null = full tree).+ * @param string $search Case-insensitive basename match, flat results.+ * @param string $type Media type root (dirForType key or empty).+ * @param int $limit Cap for search matches.+ *+ * @return mixed[] Root/folder envelope, flat {folders, files} for search.+ */+ protected function listMedia(string $path = '', ?int $levels = null, string $search = '', $type = '', int $limit = 200, int $start = 0): array {+ if ($search !== '') {+ return $this->searchMedia($search, $type, $limit);+ }++ // default entry point used by the browser: root, one level only+ if ($path === '' && $levels === null) {+ $levels = 1;+ }++ $total = 0;+ $response = $this->_scan($path, $type, $levels, $start, $limit, $total);++ if ($path === '') {+ if (!$response && !$total) {+ return [];+ }++ return [+ 'name' => '',+ 'type' => 'folder',+ 'path' => '',+ 'items' => $response,+ 'total' => $total,+ ];+ }++ $nodePath = '/' . trim(str_replace('\\', '/', $path), '/');++ return [+ 'name' => basename($nodePath) ?: $nodePath,'type' => 'folder',- 'path' => '',+ 'path' => $nodePath,'items' => $response,- ]);+ 'total' => $total,+ ];+ }++ /**+ * List one media folder level, a scoped subtree, or filename matches.+ *+ * @param ?string $path+ * @param ?int $levels+ *+ * @return void+ */+ public function scan(?string $path = null, ?int $levels = null): void {+ $get = $this->request->get ?? [];+ $path = isset($get['path']) ? (string)$get['path'] : (string)($path ?? '');+ $levels = isset($get['levels']) ? max(1, (int)$get['levels']) : $levels;+ $search = isset($get['search']) ? trim((string)$get['search']) : '';+ $start = isset($get['start']) ? max(0, (int)$get['start']) : 0;+ $limit = isset($get['limit']) ? max(1, min(500, (int)$get['limit'])) : 100;++ $type = '';+ if (isset($this->dirMediaType) && $this->dirMediaType) {+ /** @var string $type */+ $type = $this->request->get['type'] ?? 'public';+ }++ $this->response->setType('json');+ $this->response->output($this->listMedia($path, $levels, $search, $type, $limit, $start));+ }++ /**+ * Bounded recursive basename search for the media browser.+ *+ * @param string $query Search term, matched case-insensitively.+ * @param string $type Media type root (dirForType key or empty).+ * @param int $limit Max matches returned.+ *+ * @return array{folders: list<array<array-key, mixed>>, files: list<array<array-key, mixed>>} Flat matches.+ */+ public function searchMedia(string $query, $type = 'public', int $limit = 200): array {+ $query = mb_strtolower(trim($query));++ if ($query === '') {+ return ['folders' => [], 'files' => []];+ }++ $scandir = $this->dirMedia;++ if ($type) {+ $scandir = $this->dirForType($type);+ }++ if (!$scandir || !file_exists($scandir)) {+ return ['folders' => [], 'files' => []];+ }++ $mediaRoot = rtrim($scandir, DS);+ $folders = [];+ $files = [];+ $found = 0;+ $visited = 0;+ $stack = [$scandir];++ while ($stack && $found < $limit && $visited < 5000) {+ $dir = array_pop($stack);+ $visited++;++ $listdir = @\scandir($dir);++ if (!$listdir) {+ continue;+ }++ foreach ($listdir as $f) {+ if (!$f || $f[0] === '.' || $f === 'node_modules' || $f === 'vendor') {+ continue;+ }++ $full = $dir . DS . $f;+ $rel = '/' . trim(str_replace([$mediaRoot, '\\'], ['', '/'], $dir) . '/' . trim($f, '/'), '/');++ if (is_dir($full)) {+ $stack[] = $full;++ if (mb_stripos($f, $query) !== false && $found < $limit) {+ $folders[] = ['name' => $f, 'type' => 'folder', 'path' => $rel];+ $found++;+ }+ } elseif (mb_stripos($f, $query) !== false && $found < $limit) {+ $files[] = ['name' => $f, 'type' => 'file', 'path' => $rel, 'size' => @filesize($full) ?: 0];+ $found++;+ }+ }+ }++ return ['folders' => $folders, 'files' => $files];}}