Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
371a763fb4 | ||
|
|
ee717af750 | ||
|
|
0ad7034a7d | ||
|
|
d29900d6ba | ||
|
|
5ffc068041 | ||
|
|
1935cb2442 |
66
CHANGELOG.md
66
CHANGELOG.md
@@ -1,5 +1,71 @@
|
||||
# Changelog
|
||||
|
||||
## Changes 10/22/2025 (v1.6.0)
|
||||
|
||||
feat(acl): granular per-folder permissions + stricter gates; WebDAV & UI aligned
|
||||
|
||||
- Add granular ACL buckets: create, upload, edit, rename, copy, move, delete, extract, share_file, share_folder
|
||||
- Implement ACL::canX helpers and expand upsert/explicit APIs (preserve read_own)
|
||||
- Enforce “write no longer implies read” in canRead; use granular gates for write-ish ops
|
||||
- WebDAV: use canDelete for DELETE, canUpload/canEdit + disableUpload for PUT; enforce ownership on overwrite
|
||||
- Folder create: require Manage/Owner on parent; normalize paths; seed ACL; rollback on failure
|
||||
- FileController: refactor copy/move/rename/delete/extract to granular gates + folder-scope checks + own-only ownership enforcement
|
||||
- Capabilities API: compute effective actions with scope + readOnly/disableUpload; protect root
|
||||
- Admin Panel (v1.6.0): new Folder Access editor with granular caps, inheritance hints, bulk toggles, and UX validations
|
||||
- getFileList: keep root visible but inert for users without visibility; apply own-only filtering server-side
|
||||
- Bump version to v1.6.0
|
||||
|
||||
---
|
||||
|
||||
## Changes 10/20/2025 (v1.5.3)
|
||||
|
||||
security(acl): enforce folder-scope & own-only; fix file list “Select All”; harden ops
|
||||
|
||||
### fileListView.js (v1.5.3)
|
||||
|
||||
- Restore master “Select All” checkbox behavior and row highlighting.
|
||||
- Keep selection working with own-only filtered lists.
|
||||
- Build preview/thumb URLs via secure API endpoints; avoid direct /uploads.
|
||||
- Minor UI polish: slider wiring and pagination focus handling.
|
||||
|
||||
### FileController.php (v1.5.3)
|
||||
|
||||
- Add enforceFolderScope($folder, $user, $perms, $need) and apply across actions.
|
||||
- Copy/Move: require read on source, write on destination; apply scope on both.
|
||||
- When user only has read_own, enforce per-file ownership (uploader==user).
|
||||
- Extract ZIP: require write + scope; consistent 403 messages.
|
||||
- Save/Rename/Delete/Create: tighten ACL checks; block dangerous extensions; consistent CSRF/Auth handling and error codes.
|
||||
- Download/ZIP: honor read vs read_own; own-only gates by uploader; safer headers.
|
||||
|
||||
### FolderController.php (v1.5.3)
|
||||
|
||||
- Align with ACL: enforce folder-scope for non-admins; require owner or bypass for destructive ops.
|
||||
- Create/Rename/Delete: gate by write on parent/target + ownership when needed.
|
||||
- Share folder link: require share capability; forbid root sharing for non-admins; validate expiry; optional password.
|
||||
- Folder listing: return only folders user can fully view or has read_own.
|
||||
- Shared downloads/uploads: stricter validation, headers, and error handling.
|
||||
|
||||
This commits a consistent, least-privilege ACL model (owners/read/write/share/read_own), fixes bulk-select in the UI, and closes scope/ownership gaps across file & folder actions.
|
||||
|
||||
feat(dnd): default cards to sidebar on medium screens when no saved layout
|
||||
|
||||
- Adds one-time responsive default in loadSidebarOrder() (uses layoutDefaultApplied_v1)
|
||||
- Preserves existing sidebarOrder/headerOrder and small-screen behavior
|
||||
- Keeps user changes persistent; no override once a layout exists
|
||||
|
||||
feat(editor): make modal non-blocking; add SRI + timeout for CodeMirror mode loads
|
||||
|
||||
- Build the editor modal immediately and wire close (✖, Close button, and Esc) before any async work, so the UI is always dismissible.
|
||||
- Restore MODE_URL and add normalizeModeName() to resolve aliases (text/html → htmlmixed, php → application/x-httpd-php).
|
||||
- Add SRI for each lazily loaded mode (MODE_SRI) and apply integrity/crossOrigin on script tags; switch to async and improved error messages.
|
||||
- Introduce MODE_LOAD_TIMEOUT_MS=2500 and Promise.race() to init in text/plain if a mode is slow; auto-upgrade to the real mode once it arrives.
|
||||
- Graceful fallback: if CodeMirror core isn’t present, keep textarea, enable Save, and proceed.
|
||||
- Minor UX: disable Save until the editor is ready, support theme toggling, better resize handling, and font size controls without blocking.
|
||||
|
||||
Security: Locks CDN mode scripts with SRI.
|
||||
|
||||
---
|
||||
|
||||
## Changes 10/19/2025 (v1.5.2)
|
||||
|
||||
fix(admin): modal bugs; chore(api): update ReDoc SRI; docs(openapi): add annotations + spec
|
||||
|
||||
66
README.md
66
README.md
@@ -4,14 +4,20 @@
|
||||
[](https://hub.docker.com/r/error311/filerise-docker)
|
||||
[](https://github.com/error311/filerise-docker/actions/workflows/main.yml)
|
||||
[](https://github.com/error311/FileRise/actions/workflows/ci.yml)
|
||||
[](https://demo.filerise.net) **demo / demo**
|
||||
[](https://demo.filerise.net)
|
||||
[](https://github.com/error311/FileRise/releases)
|
||||
[](LICENSE)
|
||||
|
||||
**Quick links:** [Demo](#live-demo) • [Install](#installation--setup) • [Docker](#1-running-with-docker-recommended) • [Unraid](#unraid) • [WebDAV](#quick-start-mount-via-webdav) • [FAQ](#faq--troubleshooting)
|
||||
|
||||
**Elevate your File Management** – A modern, self-hosted web file manager.
|
||||
Upload, organize, and share files or folders through a sleek web interface. **FileRise** is lightweight yet powerful: think of it as your personal cloud drive that you control. With drag-and-drop uploads, in-browser editing, secure user logins (with SSO and 2FA support), and one-click sharing, **FileRise** makes file management on your server a breeze.
|
||||
**Elevate your File Management** – A modern, self-hosted web file manager.
|
||||
Upload, organize, and share files or folders through a sleek, responsive web interface.
|
||||
**FileRise** is lightweight yet powerful — your personal cloud drive that you fully control.
|
||||
|
||||
Now featuring **Granular Access Control (ACL)** with per-folder permissions, inheritance, and live admin editing.
|
||||
Grant precise capabilities like *view*, *upload*, *rename*, *delete*, or *manage* on a per-user, per-folder basis — enforced across the UI, API, and WebDAV.
|
||||
|
||||
With drag-and-drop uploads, in-browser editing, secure user logins (SSO & TOTP 2FA), and one-click public sharing, **FileRise** brings professional-grade file management to your own server — simple to deploy, easy to scale, and fully self-hosted.
|
||||
|
||||
> ⚠️ **Security fix in v1.5.0** — ACL hardening. If you’re on ≤1.4.x, please upgrade.
|
||||
|
||||
@@ -26,33 +32,57 @@ Upload, organize, and share files or folders through a sleek web interface. **Fi
|
||||
|
||||
## Features at a Glance or [Full Features Wiki](https://github.com/error311/FileRise/wiki/Features)
|
||||
|
||||
- 🚀 **Easy File Uploads:** Upload multiple files and folders via drag & drop or file picker. Supports large files with pause/resumable chunked uploads and shows real-time progress for each file. FileRise will pick up where it left off if your connection drops.
|
||||
- 🚀 **Easy File Uploads:** Upload multiple files and folders via drag & drop or file picker. Supports large files with resumable chunked uploads, pause/resume, and real-time progress. If your connection drops, FileRise resumes automatically.
|
||||
|
||||
- 🗂️ **File Management:** Full set of file/folder operations – move or copy files (via intuitive drag-drop or dialogs), rename items, and delete in batches. You can download selected files as a ZIP archive or extract uploaded ZIP files server-side. Organize content with an interactive folder tree and breadcrumb navigation for quick jumps.
|
||||
- 🗂️ **File Management:** Full suite of operations — move/copy (via drag-drop or dialogs), rename, and batch delete. Download selected files as ZIPs or extract uploaded ZIPs server-side. Organize with an interactive folder tree and breadcrumbs for instant navigation.
|
||||
|
||||
- 🗃️ **Folder Sharing & File Sharing:** Share entire folders via secure, expiring public links. Folder shares can be password-protected, and shared folders support file uploads from outside users with a separate, secure upload mechanism. Folder listings are paginated (10 items/page); file sizes are displayed in MB. Share individual files with one-time or expiring links (optional password protection).
|
||||
- 🗃️ **Folder & File Sharing:** Share folders or individual files with expiring, optionally password-protected links. Shared folders can accept external uploads (if enabled). Listings are paginated (10 items/page) with file sizes shown in MB.
|
||||
|
||||
- 🔐 **Fine-grained Access Control (ACL):** Per-folder grants for **owners**, **read** (view all), **read_own** (own-only visibility), **write** (upload/edit), and **share**.
|
||||
- _Note:_ **write no longer implies read**. Grant **read** if uploaders should see all files; or **read_own** for self-only listings.
|
||||
- Enforced server-side across UI, API, and WebDAV. Includes an admin UI for bulk editing (atomic updates) and safe defaults.
|
||||
- 🔐 **Granular Access Control (ACL):**
|
||||
Per-folder permissions for **owners**, **view**, **view (own)**, **write**, **manage**, **share**, and extended granular capabilities.
|
||||
Each grant controls specific actions across the UI, API, and WebDAV:
|
||||
|
||||
- 🔌 **WebDAV Support (ACL-aware):** Mount FileRise as a network drive **or use it headless from the CLI**. Standard WebDAV ops (upload / download / delete) work in Cyberduck, WinSCP, GNOME Files, Finder, etc., and you can script with `curl`. Listings require **read**; users with **read_own** only see their own files; writes require **write**.
|
||||
| Permission | Description |
|
||||
|-------------|-------------|
|
||||
| **Manage (Owner)** | Full control of folder and subfolders. Can edit ACLs, rename/delete/create folders, and share items. Implies all other permissions for that folder and below. |
|
||||
| **View (All)** | Allows viewing all files within the folder. Required for folder-level sharing. |
|
||||
| **View (Own)** | Restricts visibility to files uploaded by the user only. Ideal for drop zones or limited-access users. |
|
||||
| **Write** | Grants general write access — enables renaming, editing, moving, copying, deleting, and extracting files. |
|
||||
| **Create** | Allows creating subfolders. Automatically granted to *Manage* users. |
|
||||
| **Upload** | Allows uploading new files without granting full write privileges. |
|
||||
| **Edit / Rename / Copy / Move / Delete / Extract** | Individually toggleable granular file operations. |
|
||||
| **Share File / Share Folder** | Controls sharing capabilities. Folder shares require full View (All). |
|
||||
|
||||
- 📚 **API Documentation:** Auto-generated OpenAPI spec (`openapi.json`) and interactive HTML docs (`api.html`) powered by Redoc.
|
||||
- **Automatic Propagation:** Enabling **Manage** on a folder applies to all subfolders; deselecting subfolder permissions overrides inheritance in the UI.
|
||||
|
||||
- 📝 **Built-in Editor & Preview:** View images, videos, audio, and PDFs inline with a preview modal. Edit text/code files in your browser with a CodeMirror-based editor with syntax highlighting and line numbers.
|
||||
ACL enforcement is centralized and atomic across:
|
||||
- **Admin Panel:** Interactive ACL editor with batch save and dynamic inheritance visualization.
|
||||
- **API Endpoints:** All file/folder operations validate server-side.
|
||||
- **WebDAV:** Uses the same ACL engine — View / Own determine listings, granular permissions control upload/edit/delete/create.
|
||||
|
||||
- 🏷️ **Tags & Search:** Categorize your files with color-coded tags and locate them instantly using indexed real-time search. **Advanced Search** adds fuzzy matching across file names, tags, uploader fields, and within text file contents.
|
||||
- 🔌 **WebDAV (ACL-Aware):** Mount FileRise as a drive (Cyberduck, WinSCP, Finder, etc.) or access via `curl`.
|
||||
- Listings require **View** or **View (Own)**.
|
||||
- Uploads require **Upload**.
|
||||
- Overwrites require **Edit**.
|
||||
- Deletes require **Delete**.
|
||||
- Creating folders requires **Create** or **Manage**.
|
||||
- All ACLs and ownership rules are enforced exactly as in the web UI.
|
||||
|
||||
- 🔒 **Auth & SSO:** Username/password login, optional TOTP 2FA, and OIDC (Google/Authentik/Keycloak). Per-user flags like **readOnly**/**disableUpload** still supported, but folder access is governed by the ACL above.
|
||||
- 📚 **API Documentation:** Auto-generated OpenAPI spec (`openapi.json`) with interactive HTML docs (`api.html`) via Redoc.
|
||||
|
||||
- 🗑️ **Trash & Recovery:** Deleted items go to Trash first; **admins** can restore or empty. Old trash entries auto-purge (default 3 days).
|
||||
- 📝 **Built-in Editor & Preview:** Inline preview for images, video, audio, and PDFs. CodeMirror-based editor for text/code with syntax highlighting and line numbers.
|
||||
|
||||
- 🎨 **Responsive UI (Dark/Light Mode):** Mobile-friendly layout with theme toggle. The interface remembers your preferences (layout, items per page, last visited folder, etc.).
|
||||
- 🏷️ **Tags & Search:** Add color-coded tags and search by name, tag, uploader, or content. Advanced fuzzy search indexes metadata and file contents.
|
||||
|
||||
- 🌐 **Internationalization & Localization:** Switch languages via the UI (English, Spanish, French, German). Contributions welcome.
|
||||
- 🔒 **Authentication & SSO:** Username/password, optional TOTP 2FA, and OIDC (Google, Authentik, Keycloak).
|
||||
|
||||
- ⚙️ **Lightweight & Self-Contained:** Runs on PHP **8.3+** with no external database. Single-folder install or Docker image. Low footprint; scales to thousands of files with pagination and sorting.
|
||||
- 🗑️ **Trash & Recovery:** Deleted items move to Trash for recovery (default 3-day retention). Admins can restore or purge globally.
|
||||
|
||||
- 🎨 **Responsive UI (Dark/Light Mode):** Modern, mobile-friendly design with persistent preferences (theme, layout, last folder, etc.).
|
||||
|
||||
- 🌐 **Internationalization:** English, Spanish, French, and German available. Community translations welcome.
|
||||
|
||||
- ⚙️ **Lightweight & Self-Contained:** Runs on PHP 8.3+, no external DB required. Single-folder or Docker deployment with minimal footprint, optimized for Unraid and self-hosting.
|
||||
|
||||
(For full features and changelogs, see the [Wiki](https://github.com/error311/FileRise/wiki), [CHANGELOG](https://github.com/error311/FileRise/blob/master/CHANGELOG.md) or [Releases](https://github.com/error311/FileRise/releases).)
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ if (!defined('DEFAULT_CAN_SHARE')) define('DEFAULT_CAN_SHARE', true);
|
||||
if (!defined('DEFAULT_CAN_ZIP')) define('DEFAULT_CAN_ZIP', true);
|
||||
if (!defined('DEFAULT_VIEW_OWN_ONLY')) define('DEFAULT_VIEW_OWN_ONLY', false);
|
||||
define('FOLDER_OWNERS_FILE', META_DIR . 'folder_owners.json');
|
||||
define('ACL_INHERIT_ON_CREATE', true);
|
||||
|
||||
// Encryption helpers
|
||||
function encryptData($data, $encryptionKey)
|
||||
|
||||
@@ -1,28 +1,5 @@
|
||||
<?php
|
||||
// public/api/admin/acl/getGrants.php
|
||||
|
||||
/**
|
||||
* @OA\Get(
|
||||
* path="/api/admin/acl/getGrants.php",
|
||||
* summary="Get ACL grants for a user",
|
||||
* tags={"Admin","ACL"},
|
||||
* security={{"cookieAuth":{}}},
|
||||
* @OA\Parameter(name="user", in="query", required=true, @OA\Schema(type="string")),
|
||||
* @OA\Response(
|
||||
* response=200,
|
||||
* description="Map of folder → grant flags",
|
||||
* @OA\JsonContent(
|
||||
* type="object",
|
||||
* required={"grants"},
|
||||
* @OA\Property(property="grants", ref="#/components/schemas/GrantsMap")
|
||||
* )
|
||||
* ),
|
||||
* @OA\Response(response=400, description="Invalid user"),
|
||||
* @OA\Response(response=401, description="Unauthorized")
|
||||
* )
|
||||
*/
|
||||
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
require_once __DIR__ . '/../../../../config/config.php';
|
||||
@@ -32,7 +9,6 @@ require_once PROJECT_ROOT . '/src/models/FolderModel.php';
|
||||
if (session_status() !== PHP_SESSION_ACTIVE) session_start();
|
||||
header('Content-Type: application/json');
|
||||
|
||||
// Admin only
|
||||
if (empty($_SESSION['authenticated']) || empty($_SESSION['isAdmin'])) {
|
||||
http_response_code(401); echo json_encode(['error'=>'Unauthorized']); exit;
|
||||
}
|
||||
@@ -55,7 +31,7 @@ try {
|
||||
} catch (Throwable $e) { /* ignore */ }
|
||||
|
||||
if (empty($folders)) {
|
||||
$aclPath = META_DIR . 'folder_acl.json';
|
||||
$aclPath = rtrim(META_DIR, "/\\") . DIRECTORY_SEPARATOR . 'folder_acl.json';
|
||||
if (is_file($aclPath)) {
|
||||
$data = json_decode((string)@file_get_contents($aclPath), true);
|
||||
if (is_array($data['folders'] ?? null)) {
|
||||
@@ -74,29 +50,36 @@ $has = function(array $arr, string $u): bool {
|
||||
|
||||
$out = [];
|
||||
foreach ($folderList as $f) {
|
||||
$rec = ACL::explicit($f); // owners, read, write, share, read_own
|
||||
$rec = ACL::explicitAll($f); // legacy + granular
|
||||
|
||||
$isOwner = $has($rec['owners'], $user);
|
||||
$canUpload = $isOwner || $has($rec['write'], $user);
|
||||
|
||||
// IMPORTANT: full view only if owner or explicit read
|
||||
$isOwner = $has($rec['owners'], $user);
|
||||
$canViewAll = $isOwner || $has($rec['read'], $user);
|
||||
|
||||
// own-only view reflects explicit read_own (we keep it separate even if they have full view)
|
||||
$canViewOwn = $has($rec['read_own'], $user);
|
||||
$canShare = $isOwner || $has($rec['share'], $user);
|
||||
$canUpload = $isOwner || $has($rec['write'], $user) || $has($rec['upload'], $user);
|
||||
|
||||
// Share only if owner or explicit share
|
||||
$canShare = $isOwner || $has($rec['share'], $user);
|
||||
|
||||
if ($canViewAll || $canViewOwn || $canUpload || $isOwner || $canShare) {
|
||||
if ($canViewAll || $canViewOwn || $canUpload || $canShare || $isOwner
|
||||
|| $has($rec['create'],$user) || $has($rec['edit'],$user) || $has($rec['rename'],$user)
|
||||
|| $has($rec['copy'],$user) || $has($rec['move'],$user) || $has($rec['delete'],$user)
|
||||
|| $has($rec['extract'],$user) || $has($rec['share_file'],$user) || $has($rec['share_folder'],$user)) {
|
||||
$out[$f] = [
|
||||
'view' => $canViewAll,
|
||||
'viewOwn' => $canViewOwn,
|
||||
'upload' => $canUpload,
|
||||
'manage' => $isOwner,
|
||||
'share' => $canShare,
|
||||
'view' => $canViewAll,
|
||||
'viewOwn' => $canViewOwn,
|
||||
'write' => $has($rec['write'], $user) || $isOwner,
|
||||
'manage' => $isOwner,
|
||||
'share' => $canShare, // legacy
|
||||
'create' => $isOwner || $has($rec['create'], $user),
|
||||
'upload' => $isOwner || $has($rec['upload'], $user) || $has($rec['write'],$user),
|
||||
'edit' => $isOwner || $has($rec['edit'], $user) || $has($rec['write'],$user),
|
||||
'rename' => $isOwner || $has($rec['rename'], $user) || $has($rec['write'],$user),
|
||||
'copy' => $isOwner || $has($rec['copy'], $user) || $has($rec['write'],$user),
|
||||
'move' => $isOwner || $has($rec['move'], $user) || $has($rec['write'],$user),
|
||||
'delete' => $isOwner || $has($rec['delete'], $user) || $has($rec['write'],$user),
|
||||
'extract' => $isOwner || $has($rec['extract'], $user)|| $has($rec['write'],$user),
|
||||
'shareFile' => $isOwner || $has($rec['share_file'], $user) || $has($rec['share'],$user),
|
||||
'shareFolder' => $isOwner || $has($rec['share_folder'], $user) || $has($rec['share'],$user),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
echo json_encode(['grants' => $out], JSON_UNESCAPED_SLASHES);
|
||||
echo json_encode(['grants' => $out], JSON_UNESCAPED_SLASHES);
|
||||
|
||||
@@ -1,27 +1,5 @@
|
||||
<?php
|
||||
// public/api/admin/acl/saveGrants.php
|
||||
|
||||
/**
|
||||
* @OA\Post(
|
||||
* path="/api/admin/acl/saveGrants.php",
|
||||
* summary="Save ACL grants (single-user or batch)",
|
||||
* tags={"Admin","ACL"},
|
||||
* security={{"cookieAuth":{}}},
|
||||
* @OA\RequestBody(
|
||||
* required=true,
|
||||
* description="Either {user,grants} or {changes:[{user,grants}]}",
|
||||
* @OA\JsonContent(oneOf={
|
||||
* @OA\Schema(ref="#/components/schemas/SaveGrantsSingle"),
|
||||
* @OA\Schema(ref="#/components/schemas/SaveGrantsBatch")
|
||||
* })
|
||||
* ),
|
||||
* @OA\Response(response=200, description="Saved"),
|
||||
* @OA\Response(response=400, description="Invalid payload"),
|
||||
* @OA\Response(response=401, description="Unauthorized"),
|
||||
* @OA\Response(response=403, description="Invalid CSRF")
|
||||
* )
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
require_once __DIR__ . '/../../../../config/config.php';
|
||||
@@ -47,22 +25,38 @@ if (empty($_SESSION['csrf_token']) || $csrf !== $_SESSION['csrf_token']) {
|
||||
}
|
||||
|
||||
// ---- Helpers ---------------------------------------------------------------
|
||||
/**
|
||||
* Sanitize a grants map to allowed flags only:
|
||||
* view | viewOwn | upload | manage | share
|
||||
*/
|
||||
function normalize_caps(array $row): array {
|
||||
// booleanize known keys
|
||||
$bool = function($v){ return !empty($v) && $v !== 'false' && $v !== 0; };
|
||||
$k = [
|
||||
'view','viewOwn','upload','manage','share',
|
||||
'create','edit','rename','copy','move','delete','extract',
|
||||
'shareFile','shareFolder','write'
|
||||
];
|
||||
$out = [];
|
||||
foreach ($k as $kk) $out[$kk] = $bool($row[$kk] ?? false);
|
||||
|
||||
// BUSINESS RULES:
|
||||
// A) Share Folder REQUIRES View (all). If shareFolder is true but view is false, force view=true.
|
||||
if ($out['shareFolder'] && !$out['view']) {
|
||||
$out['view'] = true;
|
||||
}
|
||||
|
||||
// B) Share File requires at least View (own). If neither view nor viewOwn set, set viewOwn=true.
|
||||
if ($out['shareFile'] && !$out['view'] && !$out['viewOwn']) {
|
||||
$out['viewOwn'] = true;
|
||||
}
|
||||
|
||||
// C) "write" does NOT imply view. It also does not imply granular here; ACL expands legacy write if present.
|
||||
return $out;
|
||||
}
|
||||
|
||||
function sanitize_grants_map(array $grants): array {
|
||||
$allowed = ['view','viewOwn','upload','manage','share'];
|
||||
$out = [];
|
||||
foreach ($grants as $folder => $caps) {
|
||||
if (!is_string($folder)) $folder = (string)$folder;
|
||||
if (!is_array($caps)) $caps = [];
|
||||
$row = [];
|
||||
foreach ($allowed as $k) {
|
||||
$row[$k] = !empty($caps[$k]);
|
||||
}
|
||||
// include folder even if all false (signals "remove all for this user on this folder")
|
||||
$out[$folder] = $row;
|
||||
$out[$folder] = normalize_caps($caps);
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
@@ -124,4 +118,4 @@ if (isset($in['changes']) && is_array($in['changes'])) {
|
||||
|
||||
// ---- Fallback --------------------------------------------------------------
|
||||
http_response_code(400);
|
||||
echo json_encode(['error' => 'Invalid payload: expected {user,grants} or {changes:[{user,grants}]}']);
|
||||
echo json_encode(['error' => 'Invalid payload: expected {user,grants} or {changes:[{user,grants}]}']);
|
||||
|
||||
@@ -51,7 +51,7 @@
|
||||
* )
|
||||
*/
|
||||
|
||||
|
||||
declare(strict_types=1);
|
||||
if (session_status() !== PHP_SESSION_ACTIVE) session_start();
|
||||
|
||||
require_once __DIR__ . '/../../../config/config.php';
|
||||
@@ -88,30 +88,50 @@ function loadPermsFor(string $u): array {
|
||||
return [];
|
||||
}
|
||||
|
||||
function isAdminUser(string $u, array $perms): bool {
|
||||
if (!empty($perms['admin']) || !empty($perms['isAdmin'])) return true;
|
||||
if (!empty($_SESSION['isAdmin']) && $_SESSION['isAdmin'] === true) return true;
|
||||
$role = $_SESSION['role'] ?? null;
|
||||
if ($role === 'admin' || $role === '1' || $role === 1) return true;
|
||||
if ($u) {
|
||||
$r = userModel::getUserRole($u);
|
||||
if ($r === '1') return true;
|
||||
function isOwnerOrAncestorOwner(string $user, array $perms, string $folder): bool {
|
||||
$f = ACL::normalizeFolder($folder);
|
||||
// direct owner
|
||||
if (ACL::isOwner($user, $perms, $f)) return true;
|
||||
// ancestor owner
|
||||
while ($f !== '' && strcasecmp($f, 'root') !== 0) {
|
||||
$pos = strrpos($f, '/');
|
||||
if ($pos === false) break;
|
||||
$f = substr($f, 0, $pos);
|
||||
if ($f === '' || strcasecmp($f, 'root') === 0) break;
|
||||
if (ACL::isOwner($user, $perms, $f)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* folder-only scope:
|
||||
* - Admins: always in scope
|
||||
* - Non folder-only accounts: always in scope
|
||||
* - Folder-only accounts: in scope iff:
|
||||
* - folder == username OR subpath of username, OR
|
||||
* - user is owner of this folder (or any ancestor)
|
||||
*/
|
||||
function inUserFolderScope(string $folder, string $u, array $perms, bool $isAdmin): bool {
|
||||
if ($isAdmin) return true;
|
||||
$folderOnly = !empty($perms['folderOnly']) || !empty($perms['userFolderOnly']) || !empty($perms['UserFolderOnly']);
|
||||
if (!$folderOnly) return true;
|
||||
$f = trim($folder);
|
||||
if ($f === '' || strcasecmp($f, 'root') === 0) return false; // non-admin folderOnly: not root
|
||||
return ($f === $u) || (strpos($f, $u . '/') === 0);
|
||||
//$folderOnly = !empty($perms['folderOnly']) || !empty($perms['userFolderOnly']) || !empty($perms['UserFolderOnly']);
|
||||
//if (!$folderOnly) return true;
|
||||
|
||||
$f = ACL::normalizeFolder($folder);
|
||||
if ($f === 'root' || $f === '') {
|
||||
// folder-only users cannot act on root unless they own a subfolder (handled below)
|
||||
return isOwnerOrAncestorOwner($u, $perms, $f);
|
||||
}
|
||||
|
||||
if ($f === $u || str_starts_with($f, $u . '/')) return true;
|
||||
|
||||
// Treat ownership as in-scope
|
||||
return isOwnerOrAncestorOwner($u, $perms, $f);
|
||||
}
|
||||
|
||||
// --- inputs ---
|
||||
$folder = isset($_GET['folder']) ? trim((string)$_GET['folder']) : 'root';
|
||||
// validate folder path: allow "root" or nested segments matching REGEX_FOLDER_NAME
|
||||
|
||||
// validate folder path
|
||||
if ($folder !== 'root') {
|
||||
$parts = array_filter(explode('/', trim($folder, "/\\ ")));
|
||||
if (empty($parts)) {
|
||||
@@ -129,44 +149,90 @@ if ($folder !== 'root') {
|
||||
$folder = implode('/', $parts);
|
||||
}
|
||||
|
||||
$perms = loadPermsFor($username);
|
||||
$isAdmin = isAdminUser($username, $perms);
|
||||
// --- user + flags ---
|
||||
$perms = loadPermsFor($username);
|
||||
$isAdmin = ACL::isAdmin($perms);
|
||||
$readOnly = !empty($perms['readOnly']);
|
||||
$disableUp = !empty($perms['disableUpload']);
|
||||
$inScope = inUserFolderScope($folder, $username, $perms, $isAdmin);
|
||||
|
||||
// base permissions via ACL
|
||||
$canRead = $isAdmin || ACL::canRead($username, $perms, $folder);
|
||||
$canWrite = $isAdmin || ACL::canWrite($username, $perms, $folder);
|
||||
$canShare = $isAdmin || ACL::canShare($username, $perms, $folder);
|
||||
// --- ACL base abilities ---
|
||||
$canViewBase = $isAdmin || ACL::canRead($username, $perms, $folder);
|
||||
$canViewOwn = $isAdmin || ACL::canReadOwn($username, $perms, $folder);
|
||||
$canWriteBase = $isAdmin || ACL::canWrite($username, $perms, $folder);
|
||||
$canShareBase = $isAdmin || ACL::canShare($username, $perms, $folder);
|
||||
|
||||
// scope + flags
|
||||
$inScope = inUserFolderScope($folder, $username, $perms, $isAdmin);
|
||||
$readOnly = !empty($perms['readOnly']);
|
||||
$disableUpload = !empty($perms['disableUpload']);
|
||||
$canManageBase = $isAdmin || ACL::canManage($username, $perms, $folder);
|
||||
|
||||
$canUpload = $canWrite && !$readOnly && !$disableUpload && $inScope;
|
||||
$canCreateFolder = $canWrite && !$readOnly && $inScope;
|
||||
$canRename = $canWrite && !$readOnly && $inScope;
|
||||
$canDelete = $canWrite && !$readOnly && $inScope;
|
||||
$canMoveIn = $canWrite && !$readOnly && $inScope;
|
||||
// granular base
|
||||
$gCreateBase = $isAdmin || ACL::canCreate($username, $perms, $folder);
|
||||
$gRenameBase = $isAdmin || ACL::canRename($username, $perms, $folder);
|
||||
$gDeleteBase = $isAdmin || ACL::canDelete($username, $perms, $folder);
|
||||
$gMoveBase = $isAdmin || ACL::canMove($username, $perms, $folder);
|
||||
$gUploadBase = $isAdmin || ACL::canUpload($username, $perms, $folder);
|
||||
$gEditBase = $isAdmin || ACL::canEdit($username, $perms, $folder);
|
||||
$gCopyBase = $isAdmin || ACL::canCopy($username, $perms, $folder);
|
||||
$gExtractBase = $isAdmin || ACL::canExtract($username, $perms, $folder);
|
||||
$gShareFile = $isAdmin || ACL::canShareFile($username, $perms, $folder);
|
||||
$gShareFolder = $isAdmin || ACL::canShareFolder($username, $perms, $folder);
|
||||
|
||||
// (optional) owner info if you need it client-side
|
||||
$owner = FolderModel::getOwnerFor($folder);
|
||||
// --- Apply scope + flags to effective UI actions ---
|
||||
$canView = $canViewBase && $inScope; // keep scope for folder-only
|
||||
$canUpload = $gUploadBase && !$readOnly && !$disableUpload && $inScope;
|
||||
$canCreate = $canManageBase && !$readOnly && $inScope; // Create **folder**
|
||||
$canRename = $canManageBase && !$readOnly && $inScope; // Rename **folder**
|
||||
$canDelete = $gDeleteBase && !$readOnly && $inScope;
|
||||
// Destination can receive items if user can create/write (or manage) here
|
||||
$canReceive = ($gUploadBase || $gCreateBase || $canManageBase) && !$readOnly && $inScope;
|
||||
// Back-compat: expose as canMoveIn (used by toolbar/context-menu/drag&drop)
|
||||
$canMoveIn = $canReceive;
|
||||
$canEdit = $gEditBase && !$readOnly && $inScope;
|
||||
$canCopy = $gCopyBase && !$readOnly && $inScope;
|
||||
$canExtract = $gExtractBase && !$readOnly && $inScope;
|
||||
|
||||
// Sharing respects scope; optionally also gate on readOnly
|
||||
$canShare = $canShareBase && $inScope; // legacy umbrella
|
||||
$canShareFileEff = $gShareFile && $inScope;
|
||||
$canShareFoldEff = $gShareFolder && $inScope;
|
||||
|
||||
// never allow destructive ops on root
|
||||
$isRoot = ($folder === 'root');
|
||||
if ($isRoot) {
|
||||
$canRename = false;
|
||||
$canDelete = false;
|
||||
$canShareFoldEff = false;
|
||||
}
|
||||
|
||||
$owner = null;
|
||||
try { $owner = FolderModel::getOwnerFor($folder); } catch (Throwable $e) {}
|
||||
|
||||
// output
|
||||
echo json_encode([
|
||||
'user' => $username,
|
||||
'folder' => $folder,
|
||||
'isAdmin' => $isAdmin,
|
||||
'flags' => [
|
||||
'folderOnly' => !empty($perms['folderOnly']) || !empty($perms['userFolderOnly']) || !empty($perms['UserFolderOnly']),
|
||||
'user' => $username,
|
||||
'folder' => $folder,
|
||||
'isAdmin' => $isAdmin,
|
||||
'flags' => [
|
||||
//'folderOnly' => !empty($perms['folderOnly']) || !empty($perms['userFolderOnly']) || !empty($perms['UserFolderOnly']),
|
||||
'readOnly' => $readOnly,
|
||||
'disableUpload' => $disableUpload,
|
||||
'disableUpload' => $disableUp,
|
||||
],
|
||||
'owner' => $owner,
|
||||
'canView' => $canRead,
|
||||
'canUpload' => $canUpload,
|
||||
'canCreate' => $canCreateFolder,
|
||||
'canRename' => $canRename,
|
||||
'canDelete' => $canDelete,
|
||||
'canMoveIn' => $canMoveIn,
|
||||
'canShare' => $canShare,
|
||||
'owner' => $owner,
|
||||
|
||||
// viewing
|
||||
'canView' => $canView,
|
||||
'canViewOwn' => $canViewOwn,
|
||||
|
||||
// write-ish
|
||||
'canUpload' => $canUpload,
|
||||
'canCreate' => $canCreate,
|
||||
'canRename' => $canRename,
|
||||
'canDelete' => $canDelete,
|
||||
'canMoveIn' => $canMoveIn,
|
||||
'canEdit' => $canEdit,
|
||||
'canCopy' => $canCopy,
|
||||
'canExtract' => $canExtract,
|
||||
|
||||
// sharing
|
||||
'canShare' => $canShare, // legacy
|
||||
'canShareFile' => $canShareFileEff,
|
||||
'canShareFolder' => $canShareFoldEff,
|
||||
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
File diff suppressed because it is too large
Load Diff
@@ -5,32 +5,74 @@
|
||||
// It also includes functions to handle the drag-and-drop events, including mouse movements and drop zones.
|
||||
// It uses CSS classes to manage the appearance of the sidebar and header drop zones during drag-and-drop operations.
|
||||
|
||||
// ---- responsive defaults ----
|
||||
const MEDIUM_MIN = 1205; // matches your small-screen cutoff
|
||||
const MEDIUM_MAX = 1600; // tweak as you like
|
||||
|
||||
function isMediumScreen() {
|
||||
const w = window.innerWidth;
|
||||
return w >= MEDIUM_MIN && w < MEDIUM_MAX;
|
||||
}
|
||||
|
||||
// Moves cards into the sidebar based on the saved order in localStorage.
|
||||
export function loadSidebarOrder() {
|
||||
const sidebar = document.getElementById('sidebarDropArea');
|
||||
if (!sidebar) return;
|
||||
const orderStr = localStorage.getItem('sidebarOrder');
|
||||
if (orderStr) {
|
||||
const order = JSON.parse(orderStr);
|
||||
if (order.length > 0) {
|
||||
// Ensure main wrapper is visible.
|
||||
const mainWrapper = document.querySelector('.main-wrapper');
|
||||
if (mainWrapper) {
|
||||
mainWrapper.style.display = 'flex';
|
||||
const sidebar = document.getElementById('sidebarDropArea');
|
||||
if (!sidebar) return;
|
||||
|
||||
const orderStr = localStorage.getItem('sidebarOrder');
|
||||
const headerOrderStr = localStorage.getItem('headerOrder');
|
||||
const defaultAppliedKey = 'layoutDefaultApplied_v1'; // bump the suffix if you ever change logic
|
||||
|
||||
// If we have a saved order (sidebar or header), just honor it as before
|
||||
if (orderStr) {
|
||||
const order = JSON.parse(orderStr || '[]');
|
||||
if (Array.isArray(order) && order.length > 0) {
|
||||
const mainWrapper = document.querySelector('.main-wrapper');
|
||||
if (mainWrapper) mainWrapper.style.display = 'flex';
|
||||
order.forEach(id => {
|
||||
const card = document.getElementById(id);
|
||||
if (card && card.parentNode?.id !== 'sidebarDropArea') {
|
||||
sidebar.appendChild(card);
|
||||
animateVerticalSlide(card);
|
||||
}
|
||||
// For each saved ID, move the card into the sidebar.
|
||||
order.forEach(id => {
|
||||
const card = document.getElementById(id);
|
||||
if (card && card.parentNode.id !== 'sidebarDropArea') {
|
||||
sidebar.appendChild(card);
|
||||
// Animate vertical slide for sidebar card
|
||||
animateVerticalSlide(card);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
updateSidebarVisibility();
|
||||
return;
|
||||
}
|
||||
updateSidebarVisibility();
|
||||
}
|
||||
|
||||
// No sidebar order saved yet: if user has header icons saved, do nothing (they've customized)
|
||||
const headerOrder = JSON.parse(headerOrderStr || '[]');
|
||||
if (Array.isArray(headerOrder) && headerOrder.length > 0) {
|
||||
updateSidebarVisibility();
|
||||
return;
|
||||
}
|
||||
|
||||
// One-time default: on medium screens, start cards in the sidebar
|
||||
const alreadyApplied = localStorage.getItem(defaultAppliedKey) === '1';
|
||||
if (!alreadyApplied && isMediumScreen()) {
|
||||
const mainWrapper = document.querySelector('.main-wrapper');
|
||||
if (mainWrapper) mainWrapper.style.display = 'flex';
|
||||
|
||||
const candidates = ['uploadCard', 'folderManagementCard'];
|
||||
const moved = [];
|
||||
candidates.forEach(id => {
|
||||
const card = document.getElementById(id);
|
||||
if (card && card.parentNode?.id !== 'sidebarDropArea') {
|
||||
sidebar.appendChild(card);
|
||||
animateVerticalSlide(card);
|
||||
moved.push(id);
|
||||
}
|
||||
});
|
||||
|
||||
if (moved.length) {
|
||||
localStorage.setItem('sidebarOrder', JSON.stringify(moved));
|
||||
localStorage.setItem(defaultAppliedKey, '1');
|
||||
}
|
||||
}
|
||||
|
||||
updateSidebarVisibility();
|
||||
}
|
||||
|
||||
|
||||
export function loadHeaderOrder() {
|
||||
|
||||
@@ -9,29 +9,62 @@ const EDITOR_BLOCK_THRESHOLD = 10 * 1024 * 1024; // >10 MiB => block editing
|
||||
|
||||
// Lazy-load CodeMirror modes on demand
|
||||
const CM_CDN = "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.5/";
|
||||
|
||||
// Which mode file to load for a given name/mime
|
||||
const MODE_URL = {
|
||||
// core you've likely already loaded:
|
||||
"xml": "mode/xml/xml.min.js",
|
||||
"css": "mode/css/css.min.js",
|
||||
// core/common
|
||||
"xml": "mode/xml/xml.min.js",
|
||||
"css": "mode/css/css.min.js",
|
||||
"javascript": "mode/javascript/javascript.min.js",
|
||||
|
||||
// extras you may want on-demand:
|
||||
"htmlmixed": "mode/htmlmixed/htmlmixed.min.js",
|
||||
// meta / combos
|
||||
"htmlmixed": "mode/htmlmixed/htmlmixed.min.js",
|
||||
"application/x-httpd-php": "mode/php/php.min.js",
|
||||
"php": "mode/php/php.min.js",
|
||||
"markdown": "mode/markdown/markdown.min.js",
|
||||
"python": "mode/python/python.min.js",
|
||||
"sql": "mode/sql/sql.min.js",
|
||||
"shell": "mode/shell/shell.min.js",
|
||||
"yaml": "mode/yaml/yaml.min.js",
|
||||
|
||||
// docs / data
|
||||
"markdown": "mode/markdown/markdown.min.js",
|
||||
"yaml": "mode/yaml/yaml.min.js",
|
||||
"properties": "mode/properties/properties.min.js",
|
||||
"text/x-csrc": "mode/clike/clike.min.js",
|
||||
"text/x-c++src": "mode/clike/clike.min.js",
|
||||
"text/x-java": "mode/clike/clike.min.js",
|
||||
"text/x-csharp": "mode/clike/clike.min.js",
|
||||
"text/x-kotlin": "mode/clike/clike.min.js"
|
||||
"sql": "mode/sql/sql.min.js",
|
||||
|
||||
// shells
|
||||
"shell": "mode/shell/shell.min.js",
|
||||
|
||||
// languages
|
||||
"python": "mode/python/python.min.js",
|
||||
"text/x-csrc": "mode/clike/clike.min.js",
|
||||
"text/x-c++src": "mode/clike/clike.min.js",
|
||||
"text/x-java": "mode/clike/clike.min.js",
|
||||
"text/x-csharp": "mode/clike/clike.min.js",
|
||||
"text/x-kotlin": "mode/clike/clike.min.js"
|
||||
};
|
||||
|
||||
// Map any mime/alias to the key we use in MODE_URL
|
||||
function normalizeModeName(modeOption) {
|
||||
const name = typeof modeOption === "string" ? modeOption : (modeOption && modeOption.name);
|
||||
if (!name) return null;
|
||||
if (name === "text/html") return "htmlmixed"; // CodeMirror uses htmlmixed for HTML
|
||||
if (name === "php") return "application/x-httpd-php"; // prefer the full mime
|
||||
return name;
|
||||
}
|
||||
|
||||
const MODE_SRI = {
|
||||
"mode/xml/xml.min.js": "sha512-LarNmzVokUmcA7aUDtqZ6oTS+YXmUKzpGdm8DxC46A6AHu+PQiYCUlwEGWidjVYMo/QXZMFMIadZtrkfApYp/g==",
|
||||
"mode/css/css.min.js": "sha512-oikhYLgIKf0zWtVTOXh101BWoSacgv4UTJHQOHU+iUQ1Dol3Xjz/o9Jh0U33MPoT/d4aQruvjNvcYxvkTQd0nA==",
|
||||
"mode/javascript/javascript.min.js": "sha512-I6CdJdruzGtvDyvdO4YsiAq+pkWf2efgd1ZUSK2FnM/u2VuRASPC7GowWQrWyjxCZn6CT89s3ddGI+be0Ak9Fg==",
|
||||
"mode/htmlmixed/htmlmixed.min.js": "sha512-HN6cn6mIWeFJFwRN9yetDAMSh+AK9myHF1X9GlSlKmThaat65342Yw8wL7ITuaJnPioG0SYG09gy0qd5+s777w==",
|
||||
"mode/php/php.min.js": "sha512-jZGz5n9AVTuQGhKTL0QzOm6bxxIQjaSbins+vD3OIdI7mtnmYE6h/L+UBGIp/SssLggbkxRzp9XkQNA4AyjFBw==",
|
||||
"mode/markdown/markdown.min.js": "sha512-DmMao0nRIbyDjbaHc8fNd3kxGsZj9PCU6Iu/CeidLQT9Py8nYVA5n0PqXYmvqNdU+lCiTHOM/4E7bM/G8BttJg==",
|
||||
"mode/python/python.min.js": "sha512-2M0GdbU5OxkGYMhakED69bw0c1pW3Nb0PeF3+9d+SnwN1ryPx3wiDdNqK3gSM7KAU/pEV+2tFJFbMKjKAahOkQ==",
|
||||
"mode/sql/sql.min.js": "sha512-u8r8NUnG9B9L2dDmsfvs9ohQ0SO/Z7MB8bkdLxV7fE0Q8bOeP7/qft1D4KyE8HhVrpH3ihSrRoDiMbYR1VQBWQ==",
|
||||
"mode/shell/shell.min.js": "sha512-HoC6JXgjHHevWAYqww37Gfu2c1G7SxAOv42wOakjR8csbTUfTB7OhVzSJ95LL62nII0RCyImp+7nR9zGmJ1wRQ==",
|
||||
"mode/yaml/yaml.min.js": "sha512-+aXDZ93WyextRiAZpsRuJyiAZ38ztttUyO/H3FZx4gOAOv4/k9C6Um1CvHVtaowHZ2h7kH0d+orWvdBLPVwb4g==",
|
||||
"mode/properties/properties.min.js": "sha512-P4OaO+QWj1wPRsdkEHlrgkx+a7qp6nUC8rI6dS/0/HPjHtlEmYfiambxowYa/UfqTxyNUnwTyPt5U6l1GO76yw==",
|
||||
"mode/clike/clike.min.js": "sha512-l8ZIWnQ3XHPRG3MQ8+hT1OffRSTrFwrph1j1oc1Fzc9UKVGef5XN9fdO0vm3nW0PRgQ9LJgck6ciG59m69rvfg=="
|
||||
};
|
||||
|
||||
const MODE_LOAD_TIMEOUT_MS = 2500; // allow closing immediately; don't wait forever
|
||||
|
||||
function loadScriptOnce(url) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const key = `cm:${url}`;
|
||||
@@ -39,30 +72,47 @@ function loadScriptOnce(url) {
|
||||
if (s) {
|
||||
if (s.dataset.loaded === "1") return resolve();
|
||||
s.addEventListener("load", () => resolve());
|
||||
s.addEventListener("error", reject);
|
||||
s.addEventListener("error", () => reject(new Error(`Load failed: ${url}`)));
|
||||
return;
|
||||
}
|
||||
s = document.createElement("script");
|
||||
s.src = url;
|
||||
s.defer = true;
|
||||
s.async = true;
|
||||
s.dataset.key = key;
|
||||
|
||||
// 🔒 Add SRI if we have it
|
||||
const relPath = url.replace(/^https:\/\/cdnjs\.cloudflare\.com\/ajax\/libs\/codemirror\/5\.65\.5\//, "");
|
||||
const sri = MODE_SRI[relPath];
|
||||
if (sri) {
|
||||
s.integrity = sri;
|
||||
s.crossOrigin = "anonymous";
|
||||
// (Optional) further tighten referrer behavior:
|
||||
// s.referrerPolicy = "no-referrer";
|
||||
}
|
||||
|
||||
s.addEventListener("load", () => { s.dataset.loaded = "1"; resolve(); });
|
||||
s.addEventListener("error", reject);
|
||||
s.addEventListener("error", () => reject(new Error(`Load failed: ${url}`)));
|
||||
document.head.appendChild(s);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
async function ensureModeLoaded(modeOption) {
|
||||
if (!window.CodeMirror) return; // CM core must be present
|
||||
const name = typeof modeOption === "string" ? modeOption : (modeOption && modeOption.name);
|
||||
if (!window.CodeMirror) return;
|
||||
|
||||
const name = normalizeModeName(modeOption);
|
||||
if (!name) return;
|
||||
// Already registered?
|
||||
if ((CodeMirror.modes && CodeMirror.modes[name]) || (CodeMirror.mimeModes && CodeMirror.mimeModes[name])) {
|
||||
return;
|
||||
}
|
||||
|
||||
const isRegistered = () =>
|
||||
(window.CodeMirror?.modes && window.CodeMirror.modes[name]) ||
|
||||
(window.CodeMirror?.mimeModes && window.CodeMirror.mimeModes[name]);
|
||||
|
||||
if (isRegistered()) return;
|
||||
|
||||
const url = MODE_URL[name];
|
||||
if (!url) return; // unknown -> fallback to text/plain
|
||||
// Dependencies (htmlmixed needs xml/css/js; php highlighting with HTML also benefits from htmlmixed)
|
||||
if (!url) return; // unknown -> stay in text/plain
|
||||
|
||||
// Dependencies
|
||||
if (name === "htmlmixed") {
|
||||
await Promise.all([
|
||||
ensureModeLoaded("xml"),
|
||||
@@ -73,6 +123,7 @@ async function ensureModeLoaded(modeOption) {
|
||||
if (name === "application/x-httpd-php") {
|
||||
await ensureModeLoaded("htmlmixed");
|
||||
}
|
||||
|
||||
await loadScriptOnce(CM_CDN + url);
|
||||
}
|
||||
|
||||
@@ -81,67 +132,39 @@ function getModeForFile(fileName) {
|
||||
const ext = dot >= 0 ? fileName.slice(dot + 1).toLowerCase() : "";
|
||||
|
||||
switch (ext) {
|
||||
// markup
|
||||
case "html":
|
||||
case "htm":
|
||||
return "text/html"; // ensureModeLoaded will map to htmlmixed
|
||||
case "xml":
|
||||
return "xml";
|
||||
case "htm": return "text/html";
|
||||
case "xml": return "xml";
|
||||
case "md":
|
||||
case "markdown":
|
||||
return "markdown";
|
||||
case "markdown": return "markdown";
|
||||
case "yml":
|
||||
case "yaml":
|
||||
return "yaml";
|
||||
|
||||
// styles & scripts
|
||||
case "css":
|
||||
return "css";
|
||||
case "js":
|
||||
return "javascript";
|
||||
case "json":
|
||||
return { name: "javascript", json: true };
|
||||
|
||||
// server / langs
|
||||
case "php":
|
||||
return "application/x-httpd-php";
|
||||
case "py":
|
||||
return "python";
|
||||
case "sql":
|
||||
return "sql";
|
||||
case "yaml": return "yaml";
|
||||
case "css": return "css";
|
||||
case "js": return "javascript";
|
||||
case "json": return { name: "javascript", json: true };
|
||||
case "php": return "application/x-httpd-php";
|
||||
case "py": return "python";
|
||||
case "sql": return "sql";
|
||||
case "sh":
|
||||
case "bash":
|
||||
case "zsh":
|
||||
case "bat":
|
||||
return "shell";
|
||||
|
||||
// config-y files
|
||||
case "bat": return "shell";
|
||||
case "ini":
|
||||
case "conf":
|
||||
case "config":
|
||||
case "properties":
|
||||
return "properties";
|
||||
|
||||
// C-family / JVM
|
||||
case "properties": return "properties";
|
||||
case "c":
|
||||
case "h":
|
||||
return "text/x-csrc";
|
||||
case "h": return "text/x-csrc";
|
||||
case "cpp":
|
||||
case "cxx":
|
||||
case "hpp":
|
||||
case "hh":
|
||||
case "hxx":
|
||||
return "text/x-c++src";
|
||||
case "java":
|
||||
return "text/x-java";
|
||||
case "cs":
|
||||
return "text/x-csharp";
|
||||
case "hxx": return "text/x-c++src";
|
||||
case "java": return "text/x-java";
|
||||
case "cs": return "text/x-csharp";
|
||||
case "kt":
|
||||
case "kts":
|
||||
return "text/x-kotlin";
|
||||
|
||||
default:
|
||||
return "text/plain";
|
||||
case "kts": return "text/x-kotlin";
|
||||
default: return "text/plain";
|
||||
}
|
||||
}
|
||||
export { getModeForFile };
|
||||
@@ -158,18 +181,15 @@ export { adjustEditorSize };
|
||||
|
||||
function observeModalResize(modal) {
|
||||
if (!modal) return;
|
||||
const resizeObserver = new ResizeObserver(() => {
|
||||
adjustEditorSize();
|
||||
});
|
||||
const resizeObserver = new ResizeObserver(() => adjustEditorSize());
|
||||
resizeObserver.observe(modal);
|
||||
}
|
||||
export { observeModalResize };
|
||||
|
||||
export function editFile(fileName, folder) {
|
||||
// destroy any previous editor
|
||||
let existingEditor = document.getElementById("editorContainer");
|
||||
if (existingEditor) {
|
||||
existingEditor.remove();
|
||||
}
|
||||
if (existingEditor) existingEditor.remove();
|
||||
|
||||
const folderUsed = folder || window.currentFolder || "root";
|
||||
const folderPath = folderUsed === "root"
|
||||
@@ -179,9 +199,7 @@ export function editFile(fileName, folder) {
|
||||
|
||||
fetch(fileUrl, { method: "HEAD" })
|
||||
.then(response => {
|
||||
const lenHeader =
|
||||
response.headers.get("content-length") ??
|
||||
response.headers.get("Content-Length");
|
||||
const lenHeader = response.headers.get("content-length") ?? response.headers.get("Content-Length");
|
||||
const sizeBytes = lenHeader ? parseInt(lenHeader, 10) : null;
|
||||
|
||||
if (sizeBytes !== null && sizeBytes > EDITOR_BLOCK_THRESHOLD) {
|
||||
@@ -192,104 +210,143 @@ export function editFile(fileName, folder) {
|
||||
})
|
||||
.then(() => fetch(fileUrl))
|
||||
.then(response => {
|
||||
if (!response.ok) {
|
||||
throw new Error("HTTP error! Status: " + response.status);
|
||||
}
|
||||
const lenHeader =
|
||||
response.headers.get("content-length") ??
|
||||
response.headers.get("Content-Length");
|
||||
if (!response.ok) throw new Error("HTTP error! Status: " + response.status);
|
||||
const lenHeader = response.headers.get("content-length") ?? response.headers.get("Content-Length");
|
||||
const sizeBytes = lenHeader ? parseInt(lenHeader, 10) : null;
|
||||
return Promise.all([response.text(), sizeBytes]);
|
||||
})
|
||||
.then(([content, sizeBytes]) => {
|
||||
const forcePlainText =
|
||||
sizeBytes !== null && sizeBytes > EDITOR_PLAIN_THRESHOLD;
|
||||
const forcePlainText = sizeBytes !== null && sizeBytes > EDITOR_PLAIN_THRESHOLD;
|
||||
|
||||
// --- Build modal immediately and wire close controls BEFORE any async loads ---
|
||||
const modal = document.createElement("div");
|
||||
modal.id = "editorContainer";
|
||||
modal.classList.add("modal", "editor-modal");
|
||||
modal.setAttribute("tabindex", "-1"); // for Escape handling
|
||||
modal.innerHTML = `
|
||||
<div class="editor-header">
|
||||
<h3 class="editor-title">${t("editing")}: ${escapeHTML(fileName)}${
|
||||
forcePlainText ? " <span style='font-size:.8em;opacity:.7'>(plain text mode)</span>" : ""
|
||||
}</h3>
|
||||
<div class="editor-controls">
|
||||
<button id="decreaseFont" class="btn btn-sm btn-secondary">${t("decrease_font")}</button>
|
||||
<button id="increaseFont" class="btn btn-sm btn-secondary">${t("increase_font")}</button>
|
||||
<div class="editor-header">
|
||||
<h3 class="editor-title">
|
||||
${t("editing")}: ${escapeHTML(fileName)}
|
||||
${forcePlainText ? " <span style='font-size:.8em;opacity:.7'>(plain text mode)</span>" : ""}
|
||||
</h3>
|
||||
<div class="editor-controls">
|
||||
<button id="decreaseFont" class="btn btn-sm btn-secondary">${t("decrease_font")}</button>
|
||||
<button id="increaseFont" class="btn btn-sm btn-secondary">${t("increase_font")}</button>
|
||||
</div>
|
||||
<button id="closeEditorX" class="editor-close-btn" aria-label="${t("close")}">×</button>
|
||||
</div>
|
||||
<button id="closeEditorX" class="editor-close-btn">×</button>
|
||||
</div>
|
||||
<textarea id="fileEditor" class="editor-textarea">${escapeHTML(content)}</textarea>
|
||||
<div class="editor-footer">
|
||||
<button id="saveBtn" class="btn btn-primary">${t("save")}</button>
|
||||
<button id="closeBtn" class="btn btn-secondary">${t("close")}</button>
|
||||
</div>
|
||||
`;
|
||||
<textarea id="fileEditor" class="editor-textarea">${escapeHTML(content)}</textarea>
|
||||
<div class="editor-footer">
|
||||
<button id="saveBtn" class="btn btn-primary" disabled>${t("save")}</button>
|
||||
<button id="closeBtn" class="btn btn-secondary">${t("close")}</button>
|
||||
</div>
|
||||
`;
|
||||
document.body.appendChild(modal);
|
||||
modal.style.display = "block";
|
||||
modal.focus();
|
||||
|
||||
const isDarkMode = document.body.classList.contains("dark-mode");
|
||||
const theme = isDarkMode ? "material-darker" : "default";
|
||||
|
||||
// choose mode + lighter settings for large files
|
||||
const mode = forcePlainText ? "text/plain" : getModeForFile(fileName);
|
||||
const cmOptions = {
|
||||
lineNumbers: !forcePlainText,
|
||||
mode: mode,
|
||||
theme: theme,
|
||||
viewportMargin: forcePlainText ? 20 : Infinity,
|
||||
lineWrapping: false,
|
||||
let canceled = false;
|
||||
const doClose = () => {
|
||||
canceled = true;
|
||||
window.currentEditor = null;
|
||||
modal.remove();
|
||||
};
|
||||
|
||||
// ✅ LOAD MODE FIRST, THEN INSTANTIATE CODEMIRROR
|
||||
ensureModeLoaded(mode).finally(() => {
|
||||
const editor = CodeMirror.fromTextArea(
|
||||
// Wire close actions right away
|
||||
modal.addEventListener("keydown", (e) => { if (e.key === "Escape") doClose(); });
|
||||
document.getElementById("closeEditorX").addEventListener("click", doClose);
|
||||
document.getElementById("closeBtn").addEventListener("click", doClose);
|
||||
|
||||
// Keep buttons responsive even before editor exists
|
||||
const decBtn = document.getElementById("decreaseFont");
|
||||
const incBtn = document.getElementById("increaseFont");
|
||||
decBtn.addEventListener("click", () => {});
|
||||
incBtn.addEventListener("click", () => {});
|
||||
|
||||
// Theme + mode selection
|
||||
const isDarkMode = document.body.classList.contains("dark-mode");
|
||||
const theme = isDarkMode ? "material-darker" : "default";
|
||||
const desiredMode = forcePlainText ? "text/plain" : getModeForFile(fileName);
|
||||
|
||||
// Helper to check whether a mode is currently registered
|
||||
const modeName = typeof desiredMode === "string" ? desiredMode : (desiredMode && desiredMode.name);
|
||||
const isModeRegistered = () =>
|
||||
(window.CodeMirror?.modes && window.CodeMirror.modes[modeName]) ||
|
||||
(window.CodeMirror?.mimeModes && window.CodeMirror.mimeModes[modeName]);
|
||||
|
||||
// Start mode loading (don’t block closing)
|
||||
const modePromise = ensureModeLoaded(desiredMode);
|
||||
|
||||
// Wait up to MODE_LOAD_TIMEOUT_MS; then proceed with whatever is available
|
||||
const timeout = new Promise((res) => setTimeout(res, MODE_LOAD_TIMEOUT_MS));
|
||||
|
||||
Promise.race([modePromise, timeout]).then(() => {
|
||||
if (canceled) return;
|
||||
if (!window.CodeMirror) {
|
||||
// Core not present: keep plain <textarea>; enable Save and bail gracefully
|
||||
document.getElementById("saveBtn").disabled = false;
|
||||
observeModalResize(modal);
|
||||
return;
|
||||
}
|
||||
|
||||
const initialMode = (forcePlainText || !isModeRegistered()) ? "text/plain" : desiredMode;
|
||||
const cmOptions = {
|
||||
lineNumbers: !forcePlainText,
|
||||
mode: initialMode,
|
||||
theme,
|
||||
viewportMargin: forcePlainText ? 20 : Infinity,
|
||||
lineWrapping: false
|
||||
};
|
||||
|
||||
const editor = window.CodeMirror.fromTextArea(
|
||||
document.getElementById("fileEditor"),
|
||||
cmOptions
|
||||
);
|
||||
|
||||
window.currentEditor = editor;
|
||||
|
||||
setTimeout(() => {
|
||||
adjustEditorSize();
|
||||
}, 50);
|
||||
|
||||
setTimeout(adjustEditorSize, 50);
|
||||
observeModalResize(modal);
|
||||
|
||||
// Font controls (now that editor exists)
|
||||
let currentFontSize = 14;
|
||||
editor.getWrapperElement().style.fontSize = currentFontSize + "px";
|
||||
const wrapper = editor.getWrapperElement();
|
||||
wrapper.style.fontSize = currentFontSize + "px";
|
||||
editor.refresh();
|
||||
|
||||
document.getElementById("closeEditorX").addEventListener("click", function () {
|
||||
modal.remove();
|
||||
});
|
||||
|
||||
document.getElementById("decreaseFont").addEventListener("click", function () {
|
||||
decBtn.addEventListener("click", function () {
|
||||
currentFontSize = Math.max(8, currentFontSize - 2);
|
||||
editor.getWrapperElement().style.fontSize = currentFontSize + "px";
|
||||
wrapper.style.fontSize = currentFontSize + "px";
|
||||
editor.refresh();
|
||||
});
|
||||
|
||||
document.getElementById("increaseFont").addEventListener("click", function () {
|
||||
incBtn.addEventListener("click", function () {
|
||||
currentFontSize = Math.min(32, currentFontSize + 2);
|
||||
editor.getWrapperElement().style.fontSize = currentFontSize + "px";
|
||||
wrapper.style.fontSize = currentFontSize + "px";
|
||||
editor.refresh();
|
||||
});
|
||||
|
||||
document.getElementById("saveBtn").addEventListener("click", function () {
|
||||
// Save
|
||||
const saveBtn = document.getElementById("saveBtn");
|
||||
saveBtn.disabled = false;
|
||||
saveBtn.addEventListener("click", function () {
|
||||
saveFile(fileName, folderUsed);
|
||||
});
|
||||
|
||||
document.getElementById("closeBtn").addEventListener("click", function () {
|
||||
modal.remove();
|
||||
});
|
||||
|
||||
// Theme switch
|
||||
function updateEditorTheme() {
|
||||
const isDark = document.body.classList.contains("dark-mode");
|
||||
editor.setOption("theme", isDark ? "material-darker" : "default");
|
||||
}
|
||||
const toggle = document.getElementById("darkModeToggle");
|
||||
if (toggle) toggle.addEventListener("click", updateEditorTheme);
|
||||
|
||||
// If we started in plain text due to timeout, flip to the real mode once it arrives
|
||||
modePromise.then(() => {
|
||||
if (!canceled && !forcePlainText && isModeRegistered()) {
|
||||
editor.setOption("mode", desiredMode);
|
||||
}
|
||||
}).catch(() => {
|
||||
// If the mode truly fails to load, we just stay in plain text
|
||||
});
|
||||
});
|
||||
})
|
||||
.catch(error => {
|
||||
@@ -298,7 +355,6 @@ export function editFile(fileName, folder) {
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
export function saveFile(fileName, folder) {
|
||||
const editor = window.currentEditor;
|
||||
if (!editor) {
|
||||
|
||||
@@ -65,6 +65,59 @@ import {
|
||||
return `/api/file/download.php?${q.toString()}`;
|
||||
}
|
||||
|
||||
// Wire "select all" header checkbox for the current table render
|
||||
function wireSelectAll(fileListContent) {
|
||||
// Be flexible about how the header checkbox is identified
|
||||
const selectAll = fileListContent.querySelector(
|
||||
'thead input[type="checkbox"].select-all, ' +
|
||||
'thead .select-all input[type="checkbox"], ' +
|
||||
'thead input#selectAll, ' +
|
||||
'thead input#selectAllCheckbox, ' +
|
||||
'thead input[data-select-all]'
|
||||
);
|
||||
if (!selectAll) return;
|
||||
|
||||
const getRowCbs = () =>
|
||||
Array.from(fileListContent.querySelectorAll('tbody .file-checkbox'))
|
||||
.filter(cb => !cb.disabled);
|
||||
|
||||
// Toggle all rows when the header checkbox changes
|
||||
selectAll.addEventListener('change', () => {
|
||||
const checked = selectAll.checked;
|
||||
getRowCbs().forEach(cb => {
|
||||
cb.checked = checked;
|
||||
updateRowHighlight(cb);
|
||||
});
|
||||
updateFileActionButtons();
|
||||
// No indeterminate state when explicitly toggled
|
||||
selectAll.indeterminate = false;
|
||||
});
|
||||
|
||||
// Keep header checkbox state in sync with row selections
|
||||
const syncHeader = () => {
|
||||
const cbs = getRowCbs();
|
||||
const total = cbs.length;
|
||||
const checked = cbs.filter(cb => cb.checked).length;
|
||||
if (!total) {
|
||||
selectAll.checked = false;
|
||||
selectAll.indeterminate = false;
|
||||
return;
|
||||
}
|
||||
selectAll.checked = checked === total;
|
||||
selectAll.indeterminate = checked > 0 && checked < total;
|
||||
};
|
||||
|
||||
// Listen for any row checkbox changes to refresh header state
|
||||
fileListContent.addEventListener('change', (e) => {
|
||||
if (e.target && e.target.classList.contains('file-checkbox')) {
|
||||
syncHeader();
|
||||
}
|
||||
});
|
||||
|
||||
// Initial sync on mount
|
||||
syncHeader();
|
||||
}
|
||||
|
||||
/* -----------------------------
|
||||
Helper: robust JSON handling
|
||||
----------------------------- */
|
||||
@@ -607,6 +660,8 @@ import {
|
||||
const bottomControlsHTML = buildBottomControls(itemsPerPageSetting);
|
||||
|
||||
fileListContent.innerHTML = combinedTopHTML + headerHTML + rowsHTML + bottomControlsHTML;
|
||||
|
||||
wireSelectAll(fileListContent);
|
||||
|
||||
// PATCH each row's preview/thumb to use the secure API URLs
|
||||
if (totalFiles > 0) {
|
||||
@@ -985,6 +1040,7 @@ import {
|
||||
|
||||
// render
|
||||
fileListContent.innerHTML = galleryHTML;
|
||||
|
||||
|
||||
// pagination buttons for gallery
|
||||
const prevBtn = document.getElementById("prevPageBtn");
|
||||
|
||||
@@ -86,26 +86,26 @@ export function getParentFolder(folder) {
|
||||
Breadcrumb Functions
|
||||
----------------------*/
|
||||
|
||||
function setControlEnabled(el, enabled) {
|
||||
if (!el) return;
|
||||
if ('disabled' in el) el.disabled = !enabled;
|
||||
el.classList.toggle('disabled', !enabled);
|
||||
el.setAttribute('aria-disabled', String(!enabled));
|
||||
el.style.pointerEvents = enabled ? '' : 'none';
|
||||
el.style.opacity = enabled ? '' : '0.5';
|
||||
}
|
||||
|
||||
async function applyFolderCapabilities(folder) {
|
||||
try {
|
||||
const res = await fetch(`/api/folder/capabilities.php?folder=${encodeURIComponent(folder)}`, { credentials: 'include' });
|
||||
if (!res.ok) return;
|
||||
const caps = await res.json();
|
||||
const res = await fetch(`/api/folder/capabilities.php?folder=${encodeURIComponent(folder)}`, { credentials: 'include' });
|
||||
if (!res.ok) return;
|
||||
const caps = await res.json();
|
||||
window.currentFolderCaps = caps;
|
||||
|
||||
// top buttons
|
||||
const createBtn = document.getElementById('createFolderBtn');
|
||||
const renameBtn = document.getElementById('renameFolderBtn');
|
||||
const deleteBtn = document.getElementById('deleteFolderBtn');
|
||||
const shareBtn = document.getElementById('shareFolderBtn');
|
||||
|
||||
if (createBtn) createBtn.disabled = !caps.canCreate;
|
||||
if (renameBtn) renameBtn.disabled = !caps.canRename || folder === 'root';
|
||||
if (deleteBtn) deleteBtn.disabled = !caps.canDelete || folder === 'root';
|
||||
if (shareBtn) shareBtn.disabled = !caps.canShare || folder === 'root';
|
||||
|
||||
// keep for later if you want context menu to reflect caps
|
||||
window.currentFolderCaps = caps;
|
||||
} catch {}
|
||||
const isRoot = (folder === 'root');
|
||||
setControlEnabled(document.getElementById('createFolderBtn'), !!caps.canCreate);
|
||||
setControlEnabled(document.getElementById('renameFolderBtn'), !isRoot && !!caps.canRename);
|
||||
setControlEnabled(document.getElementById('deleteFolderBtn'), !isRoot && !!caps.canDelete);
|
||||
setControlEnabled(document.getElementById('shareFolderBtn'), !isRoot && !!caps.canShareFolder);
|
||||
}
|
||||
|
||||
// --- Breadcrumb Delegation Setup ---
|
||||
@@ -146,6 +146,7 @@ function breadcrumbClickHandler(e) {
|
||||
document.querySelectorAll(".folder-option").forEach(el => el.classList.remove("selected"));
|
||||
const target = document.querySelector(`.folder-option[data-folder="${folder}"]`);
|
||||
if (target) target.classList.add("selected");
|
||||
applyFolderCapabilities(window.currentFolder);
|
||||
|
||||
loadFileList(folder);
|
||||
}
|
||||
@@ -824,6 +825,7 @@ function folderManagerContextMenuHandler(e) {
|
||||
const folder = target.getAttribute("data-folder");
|
||||
if (!folder) return;
|
||||
window.currentFolder = folder;
|
||||
applyFolderCapabilities(window.currentFolder);
|
||||
|
||||
// Visual selection
|
||||
document.querySelectorAll(".folder-option, .breadcrumb-link").forEach(el => el.classList.remove("selected"));
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -96,6 +96,11 @@ class FolderController
|
||||
return false;
|
||||
}
|
||||
|
||||
private static function isFolderOnly(array $perms): bool
|
||||
{
|
||||
return !empty($perms['folderOnly']) || !empty($perms['userFolderOnly']) || !empty($perms['UserFolderOnly']);
|
||||
}
|
||||
|
||||
private static function requireNotReadOnly(): void
|
||||
{
|
||||
$perms = self::getPerms();
|
||||
@@ -126,25 +131,84 @@ class FolderController
|
||||
return round($bytes / 1073741824, 2) . " GB";
|
||||
}
|
||||
|
||||
/** Enforce "user folder only" scope for non-admins. Returns error string or null if allowed. */
|
||||
private static function enforceFolderScope(string $folder, string $username, array $perms): ?string
|
||||
/** Return true if user is explicit owner of the folder or any of its ancestors (admins also true). */
|
||||
private static function ownsFolderOrAncestor(string $folder, string $username, array $perms): bool
|
||||
{
|
||||
if (self::isAdmin($perms)) return null;
|
||||
|
||||
$folderOnly = !empty($perms['folderOnly']) || !empty($perms['userFolderOnly']) || !empty($perms['UserFolderOnly']);
|
||||
if (!$folderOnly) return null;
|
||||
|
||||
$folder = trim($folder);
|
||||
if ($folder === '' || strcasecmp($folder, 'root') === 0) {
|
||||
return "Forbidden: non-admins may not operate on the root folder.";
|
||||
if (self::isAdmin($perms)) return true;
|
||||
$folder = ACL::normalizeFolder($folder);
|
||||
$f = $folder;
|
||||
while ($f !== '' && strtolower($f) !== 'root') {
|
||||
if (ACL::isOwner($username, $perms, $f)) return true;
|
||||
$pos = strrpos($f, '/');
|
||||
$f = ($pos === false) ? '' : substr($f, 0, $pos);
|
||||
}
|
||||
|
||||
if ($folder === $username || strpos($folder, $username . '/') === 0) {
|
||||
return null;
|
||||
}
|
||||
return "Forbidden: folder scope violation.";
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enforce per-folder scope for folder-only accounts.
|
||||
* $need: 'read' | 'write' | 'manage' | 'share' | 'read_own' (default 'read')
|
||||
* Returns null if allowed, or an error string if forbidden.
|
||||
*/
|
||||
// In FolderController.php
|
||||
private static function enforceFolderScope(
|
||||
string $folder,
|
||||
string $username,
|
||||
array $perms,
|
||||
string $need = 'read'
|
||||
): ?string {
|
||||
// Admins bypass scope
|
||||
if (self::isAdmin($perms)) return null;
|
||||
|
||||
// If this account isn't folder-scoped, don't gate here
|
||||
if (!self::isFolderOnly($perms)) return null;
|
||||
|
||||
$folder = ACL::normalizeFolder($folder);
|
||||
|
||||
// If user owns folder or an ancestor, allow
|
||||
$f = $folder;
|
||||
while ($f !== '' && strtolower($f) !== 'root') {
|
||||
if (ACL::isOwner($username, $perms, $f)) return null;
|
||||
$pos = strrpos($f, '/');
|
||||
$f = ($pos === false) ? '' : substr($f, 0, $pos);
|
||||
}
|
||||
|
||||
// Normalize aliases so callers can pass either camelCase or snake_case
|
||||
switch ($need) {
|
||||
case 'manage': $ok = ACL::canManage($username, $perms, $folder); break;
|
||||
|
||||
// legacy:
|
||||
case 'write': $ok = ACL::canWrite($username, $perms, $folder); break;
|
||||
case 'share': $ok = ACL::canShare($username, $perms, $folder); break;
|
||||
|
||||
// read flavors:
|
||||
case 'read_own': $ok = ACL::canReadOwn($username, $perms, $folder); break;
|
||||
case 'read': $ok = ACL::canRead($username, $perms, $folder); break;
|
||||
|
||||
// granular write-ish:
|
||||
case 'create': $ok = ACL::canCreate($username, $perms, $folder); break;
|
||||
case 'upload': $ok = ACL::canUpload($username, $perms, $folder); break;
|
||||
case 'edit': $ok = ACL::canEdit($username, $perms, $folder); break;
|
||||
case 'rename': $ok = ACL::canRename($username, $perms, $folder); break;
|
||||
case 'copy': $ok = ACL::canCopy($username, $perms, $folder); break;
|
||||
case 'move': $ok = ACL::canMove($username, $perms, $folder); break;
|
||||
case 'delete': $ok = ACL::canDelete($username, $perms, $folder); break;
|
||||
case 'extract': $ok = ACL::canExtract($username, $perms, $folder); break;
|
||||
|
||||
// granular share (support both key styles)
|
||||
case 'shareFile':
|
||||
case 'share_file': $ok = ACL::canShareFile($username, $perms, $folder); break;
|
||||
case 'shareFolder':
|
||||
case 'share_folder':$ok = ACL::canShareFolder($username, $perms, $folder); break;
|
||||
|
||||
default:
|
||||
// Default to full read if unknown need was passed
|
||||
$ok = ACL::canRead($username, $perms, $folder);
|
||||
}
|
||||
|
||||
return $ok ? null : "Forbidden: folder scope violation.";
|
||||
}
|
||||
|
||||
/** Returns true if caller can ignore ownership (admin or bypassOwnership/default). */
|
||||
private static function canBypassOwnership(array $perms): bool
|
||||
{
|
||||
@@ -152,18 +216,10 @@ class FolderController
|
||||
return (bool)($perms['bypassOwnership'] ?? (defined('DEFAULT_BYPASS_OWNERSHIP') ? DEFAULT_BYPASS_OWNERSHIP : false));
|
||||
}
|
||||
|
||||
/** Returns true if caller can share. */
|
||||
private static function canShare(array $perms): bool
|
||||
/** ACL-aware folder owner check (explicit). */
|
||||
private static function isFolderOwner(string $folder, string $username, array $perms): bool
|
||||
{
|
||||
if (self::isAdmin($perms)) return true;
|
||||
return (bool)($perms['canShare'] ?? (defined('DEFAULT_CAN_SHARE') ? DEFAULT_CAN_SHARE : false));
|
||||
}
|
||||
|
||||
/** Check folder ownership via mapping; returns true if $username is the explicit owner. */
|
||||
private static function isFolderOwner(string $folder, string $username): bool
|
||||
{
|
||||
$owner = FolderModel::getOwnerFor($folder);
|
||||
return is_string($owner) && strcasecmp($owner, $username) === 0;
|
||||
return ACL::isOwner($username, $perms, $folder);
|
||||
}
|
||||
|
||||
/* -------------------- API: Create Folder -------------------- */
|
||||
@@ -171,41 +227,54 @@ class FolderController
|
||||
{
|
||||
header('Content-Type: application/json');
|
||||
self::requireAuth();
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo json_encode(['error' => 'Method not allowed.']); exit; }
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo json_encode(['error' => 'Method not allowed.']); return; }
|
||||
self::requireCsrf();
|
||||
self::requireNotReadOnly();
|
||||
|
||||
$input = json_decode(file_get_contents('php://input'), true);
|
||||
if (!isset($input['folderName'])) { http_response_code(400); echo json_encode(['error' => 'Folder name not provided.']); exit; }
|
||||
try {
|
||||
$input = json_decode(file_get_contents('php://input'), true) ?? [];
|
||||
if (!isset($input['folderName'])) { http_response_code(400); echo json_encode(['error' => 'Folder name not provided.']); return; }
|
||||
|
||||
$folderName = trim((string)$input['folderName']);
|
||||
$parentIn = isset($input['parent']) ? trim((string)$input['parent']) : '';
|
||||
$folderName = trim((string)$input['folderName']);
|
||||
$parentIn = isset($input['parent']) ? trim((string)$input['parent']) : 'root';
|
||||
|
||||
if (!preg_match(REGEX_FOLDER_NAME, $folderName)) {
|
||||
http_response_code(400); echo json_encode(['error' => 'Invalid folder name.']); exit;
|
||||
if (!preg_match(REGEX_FOLDER_NAME, $folderName)) {
|
||||
http_response_code(400); echo json_encode(['error' => 'Invalid folder name.']); return;
|
||||
}
|
||||
if ($parentIn !== '' && strcasecmp($parentIn, 'root') !== 0 && !preg_match(REGEX_FOLDER_NAME, $parentIn)) {
|
||||
http_response_code(400); echo json_encode(['error' => 'Invalid parent folder name.']); return;
|
||||
}
|
||||
|
||||
$parent = ($parentIn === '' ? 'root' : $parentIn);
|
||||
|
||||
$username = $_SESSION['username'] ?? '';
|
||||
$perms = self::getPerms();
|
||||
|
||||
// Need create on parent OR ownership on parent/ancestor
|
||||
if (!(ACL::canCreateFolder($username, $perms, $parent) || self::ownsFolderOrAncestor($parent, $username, $perms))) {
|
||||
http_response_code(403);
|
||||
echo json_encode(['error' => 'Forbidden: manager/owner required on parent.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
// Folder-scope gate for folder-only accounts (need create on parent)
|
||||
if ($msg = self::enforceFolderScope($parent, $username, $perms, 'manage')) {
|
||||
http_response_code(403); echo json_encode(['error' => $msg]); return;
|
||||
}
|
||||
|
||||
$result = FolderModel::createFolder($folderName, $parent, $username);
|
||||
if (empty($result['success'])) {
|
||||
http_response_code(400);
|
||||
echo json_encode($result);
|
||||
return;
|
||||
}
|
||||
|
||||
echo json_encode($result);
|
||||
} catch (Throwable $e) {
|
||||
error_log('createFolder fatal: '.$e->getMessage().' @ '.$e->getFile().':'.$e->getLine());
|
||||
http_response_code(500);
|
||||
echo json_encode(['error' => 'Internal error creating folder.']);
|
||||
}
|
||||
if ($parentIn !== '' && strcasecmp($parentIn, 'root') !== 0 && !preg_match(REGEX_FOLDER_NAME, $parentIn)) {
|
||||
http_response_code(400); echo json_encode(['error' => 'Invalid parent folder name.']); exit;
|
||||
}
|
||||
|
||||
// Normalize parent to an ACL key
|
||||
$parent = ($parentIn === '' || strcasecmp($parentIn, 'root') === 0) ? 'root' : $parentIn;
|
||||
|
||||
$username = $_SESSION['username'] ?? '';
|
||||
$perms = self::getPerms();
|
||||
|
||||
// ACL: must be able to WRITE into the parent folder (admins pass)
|
||||
if (!self::isAdmin($perms) && !ACL::canWrite($username, $perms, $parent)) {
|
||||
http_response_code(403);
|
||||
echo json_encode(['error' => 'Forbidden: no write access to parent folder.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
// Let the model do the filesystem work AND seed ACL owner
|
||||
$result = FolderModel::createFolder($folderName, $parent, $username);
|
||||
|
||||
echo json_encode($result);
|
||||
exit;
|
||||
}
|
||||
|
||||
/* -------------------- API: Delete Folder -------------------- */
|
||||
@@ -220,15 +289,26 @@ class FolderController
|
||||
$input = json_decode(file_get_contents('php://input'), true);
|
||||
if (!isset($input['folder'])) { http_response_code(400); echo json_encode(["error" => "Folder name not provided."]); exit; }
|
||||
|
||||
$folder = trim($input['folder']);
|
||||
$folder = trim((string)$input['folder']);
|
||||
if (strcasecmp($folder, 'root') === 0) { http_response_code(400); echo json_encode(["error" => "Cannot delete root folder."]); exit; }
|
||||
if (!preg_match(REGEX_FOLDER_NAME, $folder)) { http_response_code(400); echo json_encode(["error" => "Invalid folder name."]); exit; }
|
||||
|
||||
$username = $_SESSION['username'] ?? '';
|
||||
$perms = self::getPerms();
|
||||
|
||||
if ($msg = self::enforceFolderScope($folder, $username, $perms)) { http_response_code(403); echo json_encode(["error" => $msg]); exit; }
|
||||
if (!self::canBypassOwnership($perms) && !self::isFolderOwner($folder, $username)) {
|
||||
// Folder-scope: need manage (owner) OR explicit manage grant
|
||||
if ($msg = self::enforceFolderScope($folder, $username, $perms, 'manage')) {
|
||||
http_response_code(403); echo json_encode(["error" => $msg]); exit;
|
||||
}
|
||||
|
||||
// Require either manage permission or ancestor ownership (strong gate)
|
||||
$canManage = ACL::canManage($username, $perms, $folder) || self::ownsFolderOrAncestor($folder, $username, $perms);
|
||||
if (!$canManage) {
|
||||
http_response_code(403); echo json_encode(["error" => "Forbidden: you lack manage rights for this folder."]); exit;
|
||||
}
|
||||
|
||||
// If not bypassing ownership, require ownership (direct or ancestor) as an extra safeguard
|
||||
if (!self::canBypassOwnership($perms) && !self::ownsFolderOrAncestor($folder, $username, $perms)) {
|
||||
http_response_code(403); echo json_encode(["error" => "Forbidden: you are not the folder owner."]); exit;
|
||||
}
|
||||
|
||||
@@ -251,8 +331,8 @@ class FolderController
|
||||
http_response_code(400); echo json_encode(['error' => 'Required folder names not provided.']); exit;
|
||||
}
|
||||
|
||||
$oldFolder = trim($input['oldFolder']);
|
||||
$newFolder = trim($input['newFolder']);
|
||||
$oldFolder = trim((string)$input['oldFolder']);
|
||||
$newFolder = trim((string)$input['newFolder']);
|
||||
|
||||
if (!preg_match(REGEX_FOLDER_NAME, $oldFolder) || !preg_match(REGEX_FOLDER_NAME, $newFolder)) {
|
||||
http_response_code(400); echo json_encode(['error' => 'Invalid folder name(s).']); exit;
|
||||
@@ -261,10 +341,23 @@ class FolderController
|
||||
$username = $_SESSION['username'] ?? '';
|
||||
$perms = self::getPerms();
|
||||
|
||||
if ($msg = self::enforceFolderScope($oldFolder, $username, $perms)) { http_response_code(403); echo json_encode(["error" => $msg]); exit; }
|
||||
if ($msg = self::enforceFolderScope($newFolder, $username, $perms)) { http_response_code(403); echo json_encode(["error" => "New path not allowed: " . $msg]); exit; }
|
||||
// Must be allowed to manage the old folder
|
||||
if ($msg = self::enforceFolderScope($oldFolder, $username, $perms, 'manage')) {
|
||||
http_response_code(403); echo json_encode(["error" => $msg]); exit;
|
||||
}
|
||||
// For the new folder path, require write scope (we're "creating" a path)
|
||||
if ($msg = self::enforceFolderScope($newFolder, $username, $perms, 'manage')) {
|
||||
http_response_code(403); echo json_encode(["error" => "New path not allowed: " . $msg]); exit;
|
||||
}
|
||||
|
||||
if (!self::canBypassOwnership($perms) && !self::isFolderOwner($oldFolder, $username)) {
|
||||
// Strong gates: need manage on old OR ancestor owner; need manage on new parent OR ancestor owner
|
||||
$canManageOld = ACL::canManage($username, $perms, $oldFolder) || self::ownsFolderOrAncestor($oldFolder, $username, $perms);
|
||||
if (!$canManageOld) {
|
||||
http_response_code(403); echo json_encode(['error' => 'Forbidden: you lack manage rights on the source folder.']); exit;
|
||||
}
|
||||
|
||||
// If not bypassing ownership, require ownership (direct or ancestor) on the old folder
|
||||
if (!self::canBypassOwnership($perms) && !self::ownsFolderOrAncestor($oldFolder, $username, $perms)) {
|
||||
http_response_code(403); echo json_encode(['error' => 'Forbidden: you are not the folder owner.']); exit;
|
||||
}
|
||||
|
||||
@@ -275,66 +368,64 @@ class FolderController
|
||||
|
||||
/* -------------------- API: Get Folder List -------------------- */
|
||||
public function getFolderList(): void
|
||||
{
|
||||
header('Content-Type: application/json');
|
||||
self::requireAuth();
|
||||
{
|
||||
header('Content-Type: application/json');
|
||||
self::requireAuth();
|
||||
|
||||
// Optional "folder" filter (supports nested like "team/reports")
|
||||
$parent = $_GET['folder'] ?? null;
|
||||
if ($parent !== null && $parent !== '' && strcasecmp($parent, 'root') !== 0) {
|
||||
$parts = array_filter(explode('/', trim($parent, "/\\ ")), fn($p) => $p !== '');
|
||||
if (empty($parts)) {
|
||||
http_response_code(400);
|
||||
echo json_encode(["error" => "Invalid folder name."]);
|
||||
exit;
|
||||
}
|
||||
foreach ($parts as $seg) {
|
||||
if (!preg_match(REGEX_FOLDER_NAME, $seg)) {
|
||||
// Optional "folder" filter (supports nested like "team/reports")
|
||||
$parent = $_GET['folder'] ?? null;
|
||||
if ($parent !== null && $parent !== '' && strcasecmp($parent, 'root') !== 0) {
|
||||
$parts = array_filter(explode('/', trim($parent, "/\\ ")), fn($p) => $p !== '');
|
||||
if (empty($parts)) {
|
||||
http_response_code(400);
|
||||
echo json_encode(["error" => "Invalid folder name."]);
|
||||
exit;
|
||||
}
|
||||
foreach ($parts as $seg) {
|
||||
if (!preg_match(REGEX_FOLDER_NAME, $seg)) {
|
||||
http_response_code(400);
|
||||
echo json_encode(["error" => "Invalid folder name."]);
|
||||
exit;
|
||||
}
|
||||
}
|
||||
$parent = implode('/', $parts);
|
||||
}
|
||||
$parent = implode('/', $parts);
|
||||
}
|
||||
|
||||
$username = $_SESSION['username'] ?? '';
|
||||
$perms = loadUserPermissions($username) ?: [];
|
||||
$isAdmin = self::isAdmin($perms);
|
||||
$username = $_SESSION['username'] ?? '';
|
||||
$perms = self::getPerms();
|
||||
$isAdmin = self::isAdmin($perms);
|
||||
|
||||
// 1) full list from model
|
||||
$all = FolderModel::getFolderList(); // each row: ["folder","fileCount","metadataFile"]
|
||||
if (!is_array($all)) {
|
||||
echo json_encode([]);
|
||||
// 1) Full list from model
|
||||
$all = FolderModel::getFolderList(); // each row: ["folder","fileCount","metadataFile"]
|
||||
if (!is_array($all)) { echo json_encode([]); exit; }
|
||||
|
||||
// 2) Filter by view rights
|
||||
if (!$isAdmin) {
|
||||
$all = array_values(array_filter($all, function ($row) use ($username, $perms) {
|
||||
$f = $row['folder'] ?? '';
|
||||
if ($f === '') return false;
|
||||
|
||||
// Full view if canRead OR owns ancestor; otherwise allow if read_own granted
|
||||
$fullView = ACL::canRead($username, $perms, $f) || FolderController::ownsFolderOrAncestor($f, $username, $perms);
|
||||
$ownOnly = ACL::hasGrant($username, $f, 'read_own');
|
||||
|
||||
return $fullView || $ownOnly;
|
||||
}));
|
||||
}
|
||||
|
||||
// 3) Optional parent filter (applies to both admin and non-admin)
|
||||
if ($parent && strcasecmp($parent, 'root') !== 0) {
|
||||
$pref = $parent . '/';
|
||||
$all = array_values(array_filter($all, function ($row) use ($parent, $pref) {
|
||||
$f = $row['folder'] ?? '';
|
||||
return ($f === $parent) || (strpos($f, $pref) === 0);
|
||||
}));
|
||||
}
|
||||
|
||||
echo json_encode($all);
|
||||
exit;
|
||||
}
|
||||
|
||||
// 2) Admin sees all; others: include folder if user has full view OR own-only view
|
||||
if (!$isAdmin) {
|
||||
$all = array_values(array_filter($all, function ($row) use ($username, $perms) {
|
||||
$f = $row['folder'] ?? '';
|
||||
if ($f === '') return false;
|
||||
|
||||
$fullView = ACL::canRead($username, $perms, $f); // owners|write|read
|
||||
$ownOnly = ACL::hasGrant($username, $f, 'read_own'); // view-own
|
||||
|
||||
return $fullView || $ownOnly;
|
||||
}));
|
||||
}
|
||||
|
||||
// 3) Optional parent filter (applies to both admin and non-admin)
|
||||
if ($parent && strcasecmp($parent, 'root') !== 0) {
|
||||
$pref = $parent . '/';
|
||||
$all = array_values(array_filter($all, function ($row) use ($parent, $pref) {
|
||||
$f = $row['folder'] ?? '';
|
||||
return ($f === $parent) || (strpos($f, $pref) === 0);
|
||||
}));
|
||||
}
|
||||
|
||||
echo json_encode($all);
|
||||
exit;
|
||||
}
|
||||
|
||||
/* -------------------- Public Shared Folder HTML -------------------- */
|
||||
public function shareFolder(): void
|
||||
{
|
||||
@@ -451,10 +542,10 @@ for ($i = $startPage; $i <= $endPage; $i++): ?>
|
||||
$in = json_decode(file_get_contents("php://input"), true);
|
||||
if (!$in || !isset($in['folder'])) { http_response_code(400); echo json_encode(["error" => "Invalid input."]); exit; }
|
||||
|
||||
$folder = trim($in['folder']);
|
||||
$folder = trim((string)$in['folder']);
|
||||
$value = isset($in['expirationValue']) ? intval($in['expirationValue']) : 60;
|
||||
$unit = $in['expirationUnit'] ?? 'minutes';
|
||||
$password = $in['password'] ?? '';
|
||||
$password = (string)($in['password'] ?? '');
|
||||
$allowUpload = intval($in['allowUpload'] ?? 0);
|
||||
|
||||
if ($folder !== 'root' && !preg_match(REGEX_FOLDER_NAME, $folder)) { http_response_code(400); echo json_encode(["error" => "Invalid folder name."]); exit; }
|
||||
@@ -463,14 +554,18 @@ for ($i = $startPage; $i <= $endPage; $i++): ?>
|
||||
$perms = self::getPerms();
|
||||
$isAdmin = self::isAdmin($perms);
|
||||
|
||||
if (!self::canShare($perms)) { http_response_code(403); echo json_encode(["error" => "Sharing is not permitted for your account."]); exit; }
|
||||
|
||||
if (!$isAdmin) {
|
||||
if (strcasecmp($folder, 'root') === 0) { http_response_code(403); echo json_encode(["error" => "Only admins may share the root folder."]); exit; }
|
||||
if ($msg = self::enforceFolderScope($folder, $username, $perms)) { http_response_code(403); echo json_encode(["error" => $msg]); exit; }
|
||||
// Must have share on this folder OR be ancestor owner
|
||||
if (!(ACL::canShare($username, $perms, $folder) || self::ownsFolderOrAncestor($folder, $username, $perms))) {
|
||||
http_response_code(403); echo json_encode(["error" => "Sharing is not permitted for your account."]); exit;
|
||||
}
|
||||
|
||||
if (!self::canBypassOwnership($perms) && !self::isFolderOwner($folder, $username)) {
|
||||
// Folder-scope: need share capability within scope
|
||||
if ($msg = self::enforceFolderScope($folder, $username, $perms, 'share')) {
|
||||
http_response_code(403); echo json_encode(["error" => $msg]); exit;
|
||||
}
|
||||
|
||||
// Ownership requirement unless bypassed (allow ancestor owners)
|
||||
if (!self::canBypassOwnership($perms) && !self::ownsFolderOrAncestor($folder, $username, $perms)) {
|
||||
http_response_code(403); echo json_encode(["error" => "Forbidden: you are not the owner of this folder."]); exit;
|
||||
}
|
||||
|
||||
|
||||
@@ -57,7 +57,7 @@ class UploadController {
|
||||
$targetFolder = ACL::normalizeFolder($folderParam);
|
||||
|
||||
// Admins bypass folder canWrite checks
|
||||
if (!$isAdmin && !ACL::canWrite($username, $userPerms, $targetFolder)) {
|
||||
if (!$isAdmin && !ACL::canUpload($username, $userPerms, $targetFolder)) {
|
||||
http_response_code(403);
|
||||
echo json_encode(['error' => 'Forbidden: no write access to folder "'.$targetFolder.'".']);
|
||||
return;
|
||||
|
||||
294
src/lib/ACL.php
294
src/lib/ACL.php
@@ -6,23 +6,20 @@ require_once PROJECT_ROOT . '/config/config.php';
|
||||
|
||||
class ACL
|
||||
{
|
||||
/** In-memory cache of the ACL file. */
|
||||
private static $cache = null;
|
||||
/** Absolute path to folder_acl.json */
|
||||
private static $path = null;
|
||||
|
||||
/** Capability buckets we store per folder. */
|
||||
private const BUCKETS = ['owners','read','write','share','read_own']; // + read_own (view own only)
|
||||
private const BUCKETS = [
|
||||
'owners','read','write','share','read_own',
|
||||
'create','upload','edit','rename','copy','move','delete','extract',
|
||||
'share_file','share_folder'
|
||||
];
|
||||
|
||||
/** Compute/cache the ACL storage path. */
|
||||
private static function path(): string {
|
||||
if (!self::$path) {
|
||||
self::$path = rtrim(META_DIR, '/\\') . DIRECTORY_SEPARATOR . 'folder_acl.json';
|
||||
}
|
||||
if (!self::$path) self::$path = rtrim(META_DIR, '/\\') . DIRECTORY_SEPARATOR . 'folder_acl.json';
|
||||
return self::$path;
|
||||
}
|
||||
|
||||
/** Normalize folder names (slashes + root). */
|
||||
public static function normalizeFolder(string $f): string {
|
||||
$f = trim(str_replace('\\', '/', $f), "/ \t\r\n");
|
||||
if ($f === '' || $f === 'root') return 'root';
|
||||
@@ -33,23 +30,19 @@ class ACL
|
||||
$user = (string)$user;
|
||||
$acl = self::$cache ?? self::loadFresh();
|
||||
$changed = false;
|
||||
|
||||
foreach ($acl['folders'] as $folder => &$rec) {
|
||||
foreach (self::BUCKETS as $k) {
|
||||
$before = $rec[$k] ?? [];
|
||||
$before = is_array($rec[$k] ?? null) ? $rec[$k] : [];
|
||||
$rec[$k] = array_values(array_filter($before, fn($u) => strcasecmp((string)$u, $user) !== 0));
|
||||
if ($rec[$k] !== $before) $changed = true;
|
||||
}
|
||||
}
|
||||
unset($rec);
|
||||
|
||||
return $changed ? self::save($acl) : true;
|
||||
}
|
||||
|
||||
/** Load ACL fresh from disk, create/heal if needed. */
|
||||
private static function loadFresh(): array {
|
||||
$path = self::path();
|
||||
|
||||
if (!is_file($path)) {
|
||||
@mkdir(dirname($path), 0755, true);
|
||||
$init = [
|
||||
@@ -59,7 +52,17 @@ class ACL
|
||||
'read' => ['admin'],
|
||||
'write' => ['admin'],
|
||||
'share' => ['admin'],
|
||||
'read_own'=> [], // new bucket; empty by default
|
||||
'read_own'=> [],
|
||||
'create' => [],
|
||||
'upload' => [],
|
||||
'edit' => [],
|
||||
'rename' => [],
|
||||
'copy' => [],
|
||||
'move' => [],
|
||||
'delete' => [],
|
||||
'extract' => [],
|
||||
'share_file' => [],
|
||||
'share_folder' => [],
|
||||
],
|
||||
],
|
||||
'groups' => [],
|
||||
@@ -70,12 +73,9 @@ class ACL
|
||||
$json = (string) @file_get_contents($path);
|
||||
$data = json_decode($json, true);
|
||||
if (!is_array($data)) $data = [];
|
||||
|
||||
// Normalize shape
|
||||
$data['folders'] = isset($data['folders']) && is_array($data['folders']) ? $data['folders'] : [];
|
||||
$data['groups'] = isset($data['groups']) && is_array($data['groups']) ? $data['groups'] : [];
|
||||
|
||||
// Ensure root exists and has all buckets
|
||||
if (!isset($data['folders']['root']) || !is_array($data['folders']['root'])) {
|
||||
$data['folders']['root'] = [
|
||||
'owners' => ['admin'],
|
||||
@@ -84,16 +84,8 @@ class ACL
|
||||
'share' => ['admin'],
|
||||
'read_own' => [],
|
||||
];
|
||||
} else {
|
||||
foreach (self::BUCKETS as $k) {
|
||||
if (!isset($data['folders']['root'][$k]) || !is_array($data['folders']['root'][$k])) {
|
||||
// sensible defaults: admin in the classic buckets, empty for read_own
|
||||
$data['folders']['root'][$k] = ($k === 'read_own') ? [] : ['admin'];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Heal any folder records
|
||||
$healed = false;
|
||||
foreach ($data['folders'] as $folder => &$rec) {
|
||||
if (!is_array($rec)) { $rec = []; $healed = true; }
|
||||
@@ -107,30 +99,22 @@ class ACL
|
||||
unset($rec);
|
||||
|
||||
self::$cache = $data;
|
||||
|
||||
// Persist back if we healed anything
|
||||
if ($healed) {
|
||||
@file_put_contents($path, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), LOCK_EX);
|
||||
}
|
||||
|
||||
if ($healed) @file_put_contents($path, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), LOCK_EX);
|
||||
return $data;
|
||||
}
|
||||
|
||||
/** Persist ACL to disk and refresh cache. */
|
||||
private static function save(array $acl): bool {
|
||||
$ok = @file_put_contents(self::path(), json_encode($acl, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), LOCK_EX) !== false;
|
||||
if ($ok) self::$cache = $acl;
|
||||
return $ok;
|
||||
}
|
||||
|
||||
/** Get a bucket list (owners/read/write/share/read_own) for a folder (explicit only). */
|
||||
private static function listFor(string $folder, string $key): array {
|
||||
$acl = self::$cache ?? self::loadFresh();
|
||||
$f = $acl['folders'][$folder] ?? null;
|
||||
return is_array($f[$key] ?? null) ? $f[$key] : [];
|
||||
}
|
||||
|
||||
/** Ensure a folder record exists (giving an initial owner). */
|
||||
public static function ensureFolderRecord(string $folder, string $owner = 'admin'): void {
|
||||
$folder = self::normalizeFolder($folder);
|
||||
$acl = self::$cache ?? self::loadFresh();
|
||||
@@ -141,18 +125,26 @@ class ACL
|
||||
'write' => [$owner],
|
||||
'share' => [$owner],
|
||||
'read_own' => [],
|
||||
'create' => [],
|
||||
'upload' => [],
|
||||
'edit' => [],
|
||||
'rename' => [],
|
||||
'copy' => [],
|
||||
'move' => [],
|
||||
'delete' => [],
|
||||
'extract' => [],
|
||||
'share_file' => [],
|
||||
'share_folder' => [],
|
||||
];
|
||||
self::save($acl);
|
||||
}
|
||||
}
|
||||
|
||||
/** True if this request is admin. */
|
||||
public static function isAdmin(array $perms = []): bool {
|
||||
if (!empty($_SESSION['isAdmin'])) return true;
|
||||
if (!empty($perms['admin']) || !empty($perms['isAdmin'])) return true;
|
||||
if (isset($perms['role']) && (string)$perms['role'] === '1') return true;
|
||||
if (!empty($_SESSION['role']) && (string)$_SESSION['role'] === '1') return true;
|
||||
// Optional: if you configured DEFAULT_ADMIN_USER, treat that username as admin
|
||||
if (defined('DEFAULT_ADMIN_USER') && !empty($_SESSION['username'])
|
||||
&& strcasecmp((string)$_SESSION['username'], (string)DEFAULT_ADMIN_USER) === 0) {
|
||||
return true;
|
||||
@@ -160,24 +152,19 @@ class ACL
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Case-insensitive membership in a capability bucket. $cap: owner|owners|read|write|share|read_own */
|
||||
public static function hasGrant(string $user, string $folder, string $cap): bool {
|
||||
$folder = self::normalizeFolder($folder);
|
||||
$capKey = ($cap === 'owner') ? 'owners' : $cap;
|
||||
$arr = self::listFor($folder, $capKey);
|
||||
foreach ($arr as $u) {
|
||||
if (strcasecmp((string)$u, $user) === 0) return true;
|
||||
}
|
||||
foreach ($arr as $u) if (strcasecmp((string)$u, $user) === 0) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/** True if user is an explicit owner (or admin). */
|
||||
public static function isOwner(string $user, array $perms, string $folder): bool {
|
||||
if (self::isAdmin($perms)) return true;
|
||||
return self::hasGrant($user, $folder, 'owners');
|
||||
}
|
||||
|
||||
/** "Manage" in UI == owner. */
|
||||
public static function canManage(string $user, array $perms, string $folder): bool {
|
||||
return self::isOwner($user, $perms, $folder);
|
||||
}
|
||||
@@ -185,19 +172,15 @@ class ACL
|
||||
public static function canRead(string $user, array $perms, string $folder): bool {
|
||||
$folder = self::normalizeFolder($folder);
|
||||
if (self::isAdmin($perms)) return true;
|
||||
// IMPORTANT: write no longer implies read
|
||||
return self::hasGrant($user, $folder, 'owners')
|
||||
|| self::hasGrant($user, $folder, 'read');
|
||||
}
|
||||
|
||||
/** Own-only view = read_own OR (any full view). */
|
||||
public static function canReadOwn(string $user, array $perms, string $folder): bool {
|
||||
// if they can full-view, this is trivially true
|
||||
if (self::canRead($user, $perms, $folder)) return true;
|
||||
return self::hasGrant($user, $folder, 'read_own');
|
||||
}
|
||||
|
||||
/** Upload = write OR owner. No bypassOwnership. */
|
||||
public static function canWrite(string $user, array $perms, string $folder): bool {
|
||||
$folder = self::normalizeFolder($folder);
|
||||
if (self::isAdmin($perms)) return true;
|
||||
@@ -205,7 +188,6 @@ class ACL
|
||||
|| self::hasGrant($user, $folder, 'write');
|
||||
}
|
||||
|
||||
/** Share = share OR owner. No bypassOwnership. */
|
||||
public static function canShare(string $user, array $perms, string $folder): bool {
|
||||
$folder = self::normalizeFolder($folder);
|
||||
if (self::isAdmin($perms)) return true;
|
||||
@@ -213,10 +195,7 @@ class ACL
|
||||
|| self::hasGrant($user, $folder, 'share');
|
||||
}
|
||||
|
||||
/**
|
||||
* Return explicit lists for a folder (no inheritance).
|
||||
* Keys: owners, read, write, share, read_own (always arrays).
|
||||
*/
|
||||
// Legacy-only explicit (to avoid breaking existing callers)
|
||||
public static function explicit(string $folder): array {
|
||||
$folder = self::normalizeFolder($folder);
|
||||
$acl = self::$cache ?? self::loadFresh();
|
||||
@@ -235,10 +214,35 @@ class ACL
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Upsert a full explicit record for a folder.
|
||||
* NOTE: preserves existing 'read_own' so older callers don't wipe it.
|
||||
*/
|
||||
// New: full explicit including granular
|
||||
public static function explicitAll(string $folder): array {
|
||||
$folder = self::normalizeFolder($folder);
|
||||
$acl = self::$cache ?? self::loadFresh();
|
||||
$rec = $acl['folders'][$folder] ?? [];
|
||||
$norm = function ($v): array {
|
||||
if (!is_array($v)) return [];
|
||||
$v = array_map('strval', $v);
|
||||
return array_values(array_unique($v));
|
||||
};
|
||||
return [
|
||||
'owners' => $norm($rec['owners'] ?? []),
|
||||
'read' => $norm($rec['read'] ?? []),
|
||||
'write' => $norm($rec['write'] ?? []),
|
||||
'share' => $norm($rec['share'] ?? []),
|
||||
'read_own' => $norm($rec['read_own'] ?? []),
|
||||
'create' => $norm($rec['create'] ?? []),
|
||||
'upload' => $norm($rec['upload'] ?? []),
|
||||
'edit' => $norm($rec['edit'] ?? []),
|
||||
'rename' => $norm($rec['rename'] ?? []),
|
||||
'copy' => $norm($rec['copy'] ?? []),
|
||||
'move' => $norm($rec['move'] ?? []),
|
||||
'delete' => $norm($rec['delete'] ?? []),
|
||||
'extract' => $norm($rec['extract'] ?? []),
|
||||
'share_file' => $norm($rec['share_file'] ?? []),
|
||||
'share_folder' => $norm($rec['share_folder'] ?? []),
|
||||
];
|
||||
}
|
||||
|
||||
public static function upsert(string $folder, array $owners, array $read, array $write, array $share): bool {
|
||||
$folder = self::normalizeFolder($folder);
|
||||
$acl = self::$cache ?? self::loadFresh();
|
||||
@@ -251,24 +255,23 @@ class ACL
|
||||
'read' => $fmt($read),
|
||||
'write' => $fmt($write),
|
||||
'share' => $fmt($share),
|
||||
// preserve any own-only grants unless caller explicitly manages them elsewhere
|
||||
'read_own' => isset($existing['read_own']) && is_array($existing['read_own'])
|
||||
? array_values(array_unique(array_map('strval', $existing['read_own'])))
|
||||
: [],
|
||||
'create' => isset($existing['create']) && is_array($existing['create']) ? array_values(array_unique(array_map('strval', $existing['create']))) : [],
|
||||
'upload' => isset($existing['upload']) && is_array($existing['upload']) ? array_values(array_unique(array_map('strval', $existing['upload']))) : [],
|
||||
'edit' => isset($existing['edit']) && is_array($existing['edit']) ? array_values(array_unique(array_map('strval', $existing['edit']))) : [],
|
||||
'rename' => isset($existing['rename']) && is_array($existing['rename']) ? array_values(array_unique(array_map('strval', $existing['rename']))) : [],
|
||||
'copy' => isset($existing['copy']) && is_array($existing['copy']) ? array_values(array_unique(array_map('strval', $existing['copy']))) : [],
|
||||
'move' => isset($existing['move']) && is_array($existing['move']) ? array_values(array_unique(array_map('strval', $existing['move']))) : [],
|
||||
'delete' => isset($existing['delete']) && is_array($existing['delete']) ? array_values(array_unique(array_map('strval', $existing['delete']))) : [],
|
||||
'extract' => isset($existing['extract']) && is_array($existing['extract']) ? array_values(array_unique(array_map('strval', $existing['extract']))) : [],
|
||||
'share_file' => isset($existing['share_file']) && is_array($existing['share_file']) ? array_values(array_unique(array_map('strval', $existing['share_file']))) : [],
|
||||
'share_folder' => isset($existing['share_folder']) && is_array($existing['share_folder']) ? array_values(array_unique(array_map('strval', $existing['share_folder']))) : [],
|
||||
];
|
||||
return self::save($acl);
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomic per-user update across many folders.
|
||||
* $grants is like:
|
||||
* [
|
||||
* "folderA" => ["view"=>true, "viewOwn"=>false, "upload"=>true, "manage"=>false, "share"=>false],
|
||||
* "folderB" => ["view"=>false, "viewOwn"=>true, "upload"=>false, "manage"=>false, "share"=>false],
|
||||
* ]
|
||||
* If a folder is INCLUDED with all false, the user is removed from all its buckets.
|
||||
* (If the frontend omits a folder entirely, this method leaves that folder unchanged.)
|
||||
*/
|
||||
public static function applyUserGrantsAtomic(string $user, array $grants): array {
|
||||
$user = (string)$user;
|
||||
$path = self::path();
|
||||
@@ -278,7 +281,6 @@ class ACL
|
||||
if (!flock($fh, LOCK_EX)) { fclose($fh); throw new RuntimeException('Cannot lock ACL storage'); }
|
||||
|
||||
try {
|
||||
// Read current content
|
||||
$raw = stream_get_contents($fh);
|
||||
if ($raw === false) $raw = '';
|
||||
$acl = json_decode($raw, true);
|
||||
@@ -290,38 +292,59 @@ class ACL
|
||||
|
||||
foreach ($grants as $folder => $caps) {
|
||||
$ff = self::normalizeFolder((string)$folder);
|
||||
if (!isset($acl['folders'][$ff]) || !is_array($acl['folders'][$ff])) {
|
||||
$acl['folders'][$ff] = ['owners'=>[], 'read'=>[], 'write'=>[], 'share'=>[], 'read_own'=>[]];
|
||||
}
|
||||
if (!isset($acl['folders'][$ff]) || !is_array($acl['folders'][$ff])) $acl['folders'][$ff] = [];
|
||||
$rec =& $acl['folders'][$ff];
|
||||
|
||||
// Remove user from all buckets first (idempotent)
|
||||
foreach (self::BUCKETS as $k) {
|
||||
if (!isset($rec[$k]) || !is_array($rec[$k])) $rec[$k] = [];
|
||||
}
|
||||
foreach (self::BUCKETS as $k) {
|
||||
$arr = is_array($rec[$k]) ? $rec[$k] : [];
|
||||
$rec[$k] = array_values(array_filter(
|
||||
array_map('strval', $rec[$k]),
|
||||
fn($u) => strcasecmp($u, $user) !== 0
|
||||
array_map('strval', $arr),
|
||||
fn($u) => strcasecmp((string)$u, $user) !== 0
|
||||
));
|
||||
}
|
||||
|
||||
$v = !empty($caps['view']); // full view
|
||||
$vo = !empty($caps['viewOwn']); // own-only view
|
||||
$u = !empty($caps['upload']);
|
||||
$m = !empty($caps['manage']);
|
||||
$s = !empty($caps['share']);
|
||||
$v = !empty($caps['view']);
|
||||
$vo = !empty($caps['viewOwn']);
|
||||
$u = !empty($caps['upload']);
|
||||
$m = !empty($caps['manage']);
|
||||
$s = !empty($caps['share']);
|
||||
$w = !empty($caps['write']);
|
||||
|
||||
// Implications
|
||||
if ($m) { $v = true; $u = true; } // owner implies read+write
|
||||
if ($u && !$v && !$vo) $vo = true; // upload needs at least own-only visibility
|
||||
if ($s && !$v) $v = true; // sharing implies full read (can be relaxed if desired)
|
||||
$c = !empty($caps['create']);
|
||||
$ed = !empty($caps['edit']);
|
||||
$rn = !empty($caps['rename']);
|
||||
$cp = !empty($caps['copy']);
|
||||
$mv = !empty($caps['move']);
|
||||
$dl = !empty($caps['delete']);
|
||||
$ex = !empty($caps['extract']);
|
||||
$sf = !empty($caps['shareFile']) || !empty($caps['share_file']);
|
||||
$sfo = !empty($caps['shareFolder']) || !empty($caps['share_folder']);
|
||||
|
||||
// Add back per caps
|
||||
if ($m) $rec['owners'][] = $user;
|
||||
if ($v) $rec['read'][] = $user;
|
||||
if ($vo) $rec['read_own'][]= $user;
|
||||
if ($u) $rec['write'][] = $user;
|
||||
if ($s) $rec['share'][] = $user;
|
||||
if ($m) { $v = true; $w = true; $u = $c = $ed = $rn = $cp = $mv = $dl = $ex = $sf = $sfo = true; }
|
||||
if ($u && !$v && !$vo) $vo = true;
|
||||
//if ($s && !$v) $v = true;
|
||||
if ($w) { $c = $u = $ed = $rn = $cp = $mv = $dl = $ex = true; }
|
||||
|
||||
if ($m) $rec['owners'][] = $user;
|
||||
if ($v) $rec['read'][] = $user;
|
||||
if ($vo) $rec['read_own'][] = $user;
|
||||
if ($w) $rec['write'][] = $user;
|
||||
if ($s) $rec['share'][] = $user;
|
||||
|
||||
if ($u) $rec['upload'][] = $user;
|
||||
if ($c) $rec['create'][] = $user;
|
||||
if ($ed) $rec['edit'][] = $user;
|
||||
if ($rn) $rec['rename'][] = $user;
|
||||
if ($cp) $rec['copy'][] = $user;
|
||||
if ($mv) $rec['move'][] = $user;
|
||||
if ($dl) $rec['delete'][] = $user;
|
||||
if ($ex) $rec['extract'][] = $user;
|
||||
if ($sf) $rec['share_file'][] = $user;
|
||||
if ($sfo)$rec['share_folder'][] = $user;
|
||||
|
||||
// De-dup
|
||||
foreach (self::BUCKETS as $k) {
|
||||
$rec[$k] = array_values(array_unique(array_map('strval', $rec[$k])));
|
||||
}
|
||||
@@ -330,7 +353,6 @@ class ACL
|
||||
unset($rec);
|
||||
}
|
||||
|
||||
// Write back atomically
|
||||
ftruncate($fh, 0);
|
||||
rewind($fh);
|
||||
$ok = fwrite($fh, json_encode($acl, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)) !== false;
|
||||
@@ -344,4 +366,92 @@ class ACL
|
||||
fclose($fh);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Granular write family -----------------------------------------------
|
||||
|
||||
public static function canCreate(string $user, array $perms, string $folder): bool {
|
||||
$folder = self::normalizeFolder($folder);
|
||||
if (self::isAdmin($perms)) return true;
|
||||
return self::hasGrant($user, $folder, 'owners')
|
||||
|| self::hasGrant($user, $folder, 'create')
|
||||
|| self::hasGrant($user, $folder, 'write');
|
||||
}
|
||||
|
||||
public static function canCreateFolder(string $user, array $perms, string $folder): bool {
|
||||
$folder = self::normalizeFolder($folder);
|
||||
if (self::isAdmin($perms)) return true;
|
||||
// Only owners/managers can create subfolders under $folder
|
||||
return self::hasGrant($user, $folder, 'owners');
|
||||
}
|
||||
|
||||
public static function canUpload(string $user, array $perms, string $folder): bool {
|
||||
$folder = self::normalizeFolder($folder);
|
||||
if (self::isAdmin($perms)) return true;
|
||||
return self::hasGrant($user, $folder, 'owners')
|
||||
|| self::hasGrant($user, $folder, 'upload')
|
||||
|| self::hasGrant($user, $folder, 'write');
|
||||
}
|
||||
|
||||
public static function canEdit(string $user, array $perms, string $folder): bool {
|
||||
$folder = self::normalizeFolder($folder);
|
||||
if (self::isAdmin($perms)) return true;
|
||||
return self::hasGrant($user, $folder, 'owners')
|
||||
|| self::hasGrant($user, $folder, 'edit')
|
||||
|| self::hasGrant($user, $folder, 'write');
|
||||
}
|
||||
|
||||
public static function canRename(string $user, array $perms, string $folder): bool {
|
||||
$folder = self::normalizeFolder($folder);
|
||||
if (self::isAdmin($perms)) return true;
|
||||
return self::hasGrant($user, $folder, 'owners')
|
||||
|| self::hasGrant($user, $folder, 'rename')
|
||||
|| self::hasGrant($user, $folder, 'write');
|
||||
}
|
||||
|
||||
public static function canCopy(string $user, array $perms, string $folder): bool {
|
||||
$folder = self::normalizeFolder($folder);
|
||||
if (self::isAdmin($perms)) return true;
|
||||
return self::hasGrant($user, $folder, 'owners')
|
||||
|| self::hasGrant($user, $folder, 'copy')
|
||||
|| self::hasGrant($user, $folder, 'write');
|
||||
}
|
||||
|
||||
public static function canMove(string $user, array $perms, string $folder): bool {
|
||||
$folder = self::normalizeFolder($folder);
|
||||
if (self::isAdmin($perms)) return true;
|
||||
return self::hasGrant($user, $folder, 'owners')
|
||||
|| self::hasGrant($user, $folder, 'move')
|
||||
|| self::hasGrant($user, $folder, 'write');
|
||||
}
|
||||
|
||||
public static function canDelete(string $user, array $perms, string $folder): bool {
|
||||
$folder = self::normalizeFolder($folder);
|
||||
if (self::isAdmin($perms)) return true;
|
||||
return self::hasGrant($user, $folder, 'owners')
|
||||
|| self::hasGrant($user, $folder, 'delete')
|
||||
|| self::hasGrant($user, $folder, 'write');
|
||||
}
|
||||
|
||||
public static function canExtract(string $user, array $perms, string $folder): bool {
|
||||
$folder = self::normalizeFolder($folder);
|
||||
if (self::isAdmin($perms)) return true;
|
||||
return self::hasGrant($user, $folder, 'owners')
|
||||
|| self::hasGrant($user, $folder, 'extract')
|
||||
|| self::hasGrant($user, $folder, 'write');
|
||||
}
|
||||
|
||||
/** Sharing: files use share, folders require share + full-view. */
|
||||
public static function canShareFile(string $user, array $perms, string $folder): bool {
|
||||
$folder = self::normalizeFolder($folder);
|
||||
if (self::isAdmin($perms)) return true;
|
||||
return self::hasGrant($user, $folder, 'owners') || self::hasGrant($user, $folder, 'share');
|
||||
}
|
||||
public static function canShareFolder(string $user, array $perms, string $folder): bool {
|
||||
$folder = self::normalizeFolder($folder);
|
||||
if (self::isAdmin($perms)) return true;
|
||||
$can = self::hasGrant($user, $folder, 'owners') || self::hasGrant($user, $folder, 'share');
|
||||
if (!$can) return false;
|
||||
// require full view too
|
||||
return self::hasGrant($user, $folder, 'owners') || self::hasGrant($user, $folder, 'read');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,48 +169,67 @@ class FolderModel
|
||||
* @param string $parent 'root' or nested key (e.g. 'team/reports')
|
||||
* @param string $creator username to set as initial owner (falls back to 'admin')
|
||||
*/
|
||||
public static function createFolder(string $folderName, string $parent = 'root', string $creator = 'admin'): array
|
||||
public static function createFolder(string $folderName, string $parent, string $creator): array
|
||||
{
|
||||
// -------- Normalize incoming values (use ONLY the parameters) --------
|
||||
$folderName = trim((string)$folderName);
|
||||
$parentIn = trim((string)$parent);
|
||||
|
||||
// If the client sent a path in folderName (e.g., "bob/new-sub") and parent is root/empty,
|
||||
// derive parent = "bob" and folderName = "new-sub" so permission checks hit "bob".
|
||||
$normalized = ACL::normalizeFolder($folderName);
|
||||
if ($normalized !== 'root' && strpos($normalized, '/') !== false &&
|
||||
($parentIn === '' || strcasecmp($parentIn, 'root') === 0)) {
|
||||
$parentIn = trim(str_replace('\\', '/', dirname($normalized)), '/');
|
||||
$folderName = basename($normalized);
|
||||
if ($parentIn === '' || strcasecmp($parentIn, 'root') === 0) $parentIn = 'root';
|
||||
}
|
||||
|
||||
$parent = ($parentIn === '' || strcasecmp($parentIn, 'root') === 0) ? 'root' : $parentIn;
|
||||
$folderName = trim($folderName);
|
||||
$parent = trim($parent);
|
||||
|
||||
if ($folderName === '' || !preg_match(REGEX_FOLDER_NAME, $folderName)) {
|
||||
return ['success' => false, 'error' => 'Invalid folder name', 'code' => 400];
|
||||
if ($folderName === '') return ['success'=>false, 'error' => 'Folder name required'];
|
||||
|
||||
// ACL key for new folder
|
||||
$newKey = ($parent === 'root') ? $folderName : ($parent . '/' . $folderName);
|
||||
|
||||
// -------- Compose filesystem paths --------
|
||||
$base = rtrim((string)UPLOAD_DIR, "/\\");
|
||||
$parentRel = ($parent === 'root') ? '' : str_replace('/', DIRECTORY_SEPARATOR, $parent);
|
||||
$parentAbs = $parentRel ? ($base . DIRECTORY_SEPARATOR . $parentRel) : $base;
|
||||
$newAbs = $parentAbs . DIRECTORY_SEPARATOR . $folderName;
|
||||
|
||||
// -------- Exists / sanity checks --------
|
||||
if (!is_dir($parentAbs)) return ['success'=>false, 'error' => 'Parent folder does not exist'];
|
||||
if (is_dir($newAbs)) return ['success'=>false, 'error' => 'Folder already exists'];
|
||||
|
||||
// -------- Create directory --------
|
||||
if (!@mkdir($newAbs, 0775, true)) {
|
||||
$err = error_get_last();
|
||||
return ['success'=>false, 'error' => 'Failed to create folder' . (!empty($err['message']) ? (': '.$err['message']) : '')];
|
||||
}
|
||||
if ($parent !== '' && strcasecmp($parent, 'root') !== 0 && !preg_match(REGEX_FOLDER_NAME, $parent)) {
|
||||
return ['success' => false, 'error' => 'Invalid parent folder', 'code' => 400];
|
||||
|
||||
// -------- Seed ACL --------
|
||||
$inherit = defined('ACL_INHERIT_ON_CREATE') && ACL_INHERIT_ON_CREATE;
|
||||
try {
|
||||
if ($inherit) {
|
||||
// Copy parent’s explicit (legacy 5 buckets), add creator to owners
|
||||
$p = ACL::explicit($parent); // owners, read, write, share, read_own
|
||||
$owners = array_values(array_unique(array_map('strval', array_merge($p['owners'], [$creator]))));
|
||||
$read = $p['read'];
|
||||
$write = $p['write'];
|
||||
$share = $p['share'];
|
||||
ACL::upsert($newKey, $owners, $read, $write, $share);
|
||||
} else {
|
||||
// Creator owns the new folder
|
||||
ACL::ensureFolderRecord($newKey, $creator);
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
// Roll back FS if ACL seeding fails
|
||||
@rmdir($newAbs);
|
||||
return ['success'=>false, 'error' => 'Failed to seed ACL: ' . $e->getMessage()];
|
||||
}
|
||||
|
||||
// Compute ACL key and filesystem path
|
||||
$aclKey = ($parent === '' || strcasecmp($parent, 'root') === 0) ? $folderName : ($parent . '/' . $folderName);
|
||||
|
||||
$base = rtrim(UPLOAD_DIR, '/\\');
|
||||
$path = ($parent === '' || strcasecmp($parent, 'root') === 0)
|
||||
? $base . DIRECTORY_SEPARATOR . $folderName
|
||||
: $base . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $parent) . DIRECTORY_SEPARATOR . $folderName;
|
||||
|
||||
// Safety: stay inside UPLOAD_DIR
|
||||
$realBase = realpath($base);
|
||||
$realPath = $path; // may not exist yet
|
||||
$parentDir = dirname($path);
|
||||
if (!is_dir($parentDir) && !@mkdir($parentDir, 0775, true)) {
|
||||
return ['success' => false, 'error' => 'Failed to create parent path', 'code' => 500];
|
||||
}
|
||||
|
||||
if (is_dir($path)) {
|
||||
// Idempotent: still ensure ACL record exists
|
||||
ACL::ensureFolderRecord($aclKey, $creator ?: 'admin');
|
||||
return ['success' => true, 'folder' => $aclKey, 'alreadyExists' => true];
|
||||
}
|
||||
|
||||
if (!@mkdir($path, 0775, true)) {
|
||||
return ['success' => false, 'error' => 'Failed to create folder', 'code' => 500];
|
||||
}
|
||||
|
||||
// Seed ACL: owner/read/write/share -> creator; read_own empty
|
||||
ACL::ensureFolderRecord($aclKey, $creator ?: 'admin');
|
||||
|
||||
return ['success' => true, 'folder' => $aclKey];
|
||||
|
||||
return ['success' => true, 'folder' => $newKey];
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
<?php
|
||||
namespace FileRise\WebDAV;
|
||||
|
||||
//src/webdav/FileRiseDirectory.php
|
||||
|
||||
require_once __DIR__ . '/../../config/config.php'; // constants + loadUserPermissions()
|
||||
require_once __DIR__ . '/../../vendor/autoload.php'; // SabreDAV
|
||||
require_once __DIR__ . '/../../src/lib/ACL.php';
|
||||
@@ -166,9 +168,9 @@ class FileRiseDirectory implements ICollection, INode {
|
||||
|
||||
public function createDirectory($name): INode {
|
||||
$parentKey = $this->folderKeyForPath($this->path);
|
||||
if (!$this->isAdmin && !\ACL::canWrite($this->user, $this->perms, $parentKey)) {
|
||||
throw new Forbidden('No permission to create subfolders here');
|
||||
}
|
||||
if (!$this->isAdmin && !\ACL::canManage($this->user, $this->perms, $parentKey)) {
|
||||
throw new Forbidden('No permission to create subfolders here');
|
||||
}
|
||||
|
||||
$full = $this->path . DIRECTORY_SEPARATOR . $name;
|
||||
if (!is_dir($full)) {
|
||||
|
||||
@@ -38,8 +38,9 @@ class FileRiseFile implements IFile, INode {
|
||||
|
||||
public function delete(): void {
|
||||
[$folderKey, $fileName] = $this->split();
|
||||
if (!$this->isAdmin && !\ACL::canWrite($this->user, $this->perms, $folderKey)) {
|
||||
throw new Forbidden('No write access to delete this file');
|
||||
|
||||
if (!$this->isAdmin && !\ACL::canDelete($this->user, $this->perms, $folderKey)) {
|
||||
throw new Forbidden('No delete permission in this folder');
|
||||
}
|
||||
if (!$this->canTouchOwnership($folderKey, $fileName)) {
|
||||
throw new Forbidden('You do not own this file');
|
||||
@@ -67,34 +68,40 @@ class FileRiseFile implements IFile, INode {
|
||||
|
||||
public function put($data): ?string {
|
||||
[$folderKey, $fileName] = $this->split();
|
||||
|
||||
if (!$this->isAdmin && !\ACL::canWrite($this->user, $this->perms, $folderKey)) {
|
||||
throw new Forbidden('No write access to this folder');
|
||||
}
|
||||
if (!empty($this->perms['disableUpload']) && !$this->isAdmin) {
|
||||
throw new Forbidden('Uploads are disabled for your account');
|
||||
}
|
||||
|
||||
// If overwriting existing file, enforce ownership for non-admin unless bypassOwnership
|
||||
|
||||
$exists = is_file($this->path);
|
||||
$bypass = !empty($this->perms['bypassOwnership']);
|
||||
if ($exists && !$this->isAdmin && !$bypass && !$this->isOwner($folderKey, $fileName)) {
|
||||
|
||||
if (!$this->isAdmin) {
|
||||
// uploads disabled blocks both create & overwrite
|
||||
if (!empty($this->perms['disableUpload'])) {
|
||||
throw new Forbidden('Uploads are disabled for your account');
|
||||
}
|
||||
// granular gates
|
||||
if ($exists) {
|
||||
if (!\ACL::canEdit($this->user, $this->perms, $folderKey)) {
|
||||
throw new Forbidden('No edit permission in this folder');
|
||||
}
|
||||
} else {
|
||||
if (!\ACL::canUpload($this->user, $this->perms, $folderKey)) {
|
||||
throw new Forbidden('No upload permission in this folder');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Ownership on overwrite (unless admin/bypass)
|
||||
$bypass = !empty($this->perms['bypassOwnership']) || $this->isAdmin;
|
||||
if ($exists && !$bypass && !$this->isOwner($folderKey, $fileName)) {
|
||||
throw new Forbidden('You do not own the target file');
|
||||
}
|
||||
|
||||
// Write data
|
||||
|
||||
// write + metadata (unchanged)
|
||||
file_put_contents(
|
||||
$this->path,
|
||||
is_resource($data) ? stream_get_contents($data) : (string)$data
|
||||
);
|
||||
|
||||
// Update metadata (uploader on first write; modified every write)
|
||||
$this->updateMetadata($folderKey, $fileName);
|
||||
|
||||
if (function_exists('fastcgi_finish_request')) {
|
||||
fastcgi_finish_request();
|
||||
}
|
||||
return null; // no ETag
|
||||
if (function_exists('fastcgi_finish_request')) fastcgi_finish_request();
|
||||
return null;
|
||||
}
|
||||
|
||||
public function getSize(): int {
|
||||
|
||||
Reference in New Issue
Block a user