Compare commits

...

95 Commits

Author SHA1 Message Date
Ryan
3351a11927 ci(release): touch version.js to trigger release-on-version workflow 2025-10-27 05:40:36 -04:00
Ryan
4dddcf0f99 chore(ci): remove CodeQL workflow 2025-10-27 05:37:45 -04:00
Ryan
35966964e7 chore(ci,codeql): lint fixes, release trigger; stamp ?v in HTML/CSS; fix editor cache-busting 2025-10-27 05:31:01 -04:00
github-actions[bot]
7fe8e858ae chore(release): set APP_VERSION and stamp assets to v1.6.9 [skip ci] 2025-10-27 08:48:46 +00:00
Ryan
64332211c9 release(v1.6.9): feat(core) localize assets, harden headers, and speed up load 2025-10-27 04:48:31 -04:00
Ryan
3e37738e3f ci(release): touch version.js to trigger release-on-version workflow 2025-10-25 20:57:43 -04:00
Ryan
2ba33f40f8 ci(release): add workflow to auto-publish GitHub Release on version.js change 2025-10-25 20:54:49 -04:00
Ryan
badcf5c02b ci(release): add workflow to auto-publish GitHub Release on version.js updates 2025-10-25 20:51:58 -04:00
github-actions[bot]
89976f444f chore: set APP_VERSION to v1.6.8 2025-10-26 00:33:15 +00:00
Ryan
9c53c37f38 release(v1.6.8): fix(ui) prevent Extract/Create flash on refresh; remember last folder 2025-10-25 20:33:01 -04:00
Ryan
a400163dfb docs(assets): folder access screenshot 2025-10-25 15:08:46 -04:00
Ryan
ebe5939bf5 docs(assets,readme): refresh screenshots and demo video for v1.6.7 2025-10-25 14:26:36 -04:00
Ryan
83757c7470 new video demo date and link in README
Updated the video demo date and link in README.
2025-10-25 13:58:25 -04:00
github-actions[bot]
8e363ea758 chore: set APP_VERSION to v1.6.7 2025-10-25 06:16:13 +00:00
Ryan
2739925f0b release(v1.6.7): Folder Move feature, stable DnD persistence, safer uploads, and ACL/UI polish 2025-10-25 02:16:01 -04:00
github-actions[bot]
b5610cf156 chore: set APP_VERSION to v1.6.6 2025-10-24 07:21:53 +00:00
Ryan
ae932a9aa9 release(v1.6.6): header-mounted toggle, dark-mode polish, persistent layout, and ACL fix 2025-10-24 03:21:39 -04:00
github-actions[bot]
a106d47f77 chore: set APP_VERSION to v1.6.5 2025-10-24 06:12:09 +00:00
Ryan
41d464a4b3 release(v1.6.5): fix PHP warning and upload-flag check in capabilities.php 2025-10-24 02:11:55 -04:00
Ryan
9e69f19e23 chore: add YAML document start markers and fix lint warnings 2025-10-24 01:51:18 -04:00
Ryan
1df7bc3f87 ci(sync-changelog): fix YAML lint error by trimming trailing spaces and ensuring EOF newline 2025-10-24 01:46:58 -04:00
github-actions[bot]
e5f9831d73 chore: set APP_VERSION to v1.6.4 2025-10-24 05:36:43 +00:00
Ryan
553bc84404 release(v1.6.4): runtime version injection + CI bump/sync; caching tweaks 2025-10-24 01:36:30 -04:00
Ryan
88a8857a6f release(v1.6.3): drag/drop card persistence, admin UX fixes, and docs (closes #58) 2025-10-24 00:22:22 -04:00
Ryan
edefaaca36 docs(README): add additional badges 2025-10-23 03:36:27 -04:00
Ryan
ef0a8da696 chore(funding): enable GitHub Sponsors and Ko-fi links 2025-10-23 03:16:27 -04:00
Ryan
ebabb561d6 ui: fix “Change Password” button sizing in User Panel 2025-10-23 01:54:32 -04:00
Ryan
30761b6dad feat(i18n,auth): add Simplified Chinese (zh-CN) and expose in User Panel 2025-10-23 01:43:48 -04:00
Ryan
9ef40da5aa feat(ui): unified zone toggle + polished interactions for sidebar/top cards 2025-10-23 01:06:07 -04:00
Ryan
371a763fb4 docs(README): add permissions & description table 2025-10-22 21:41:08 -04:00
Ryan
ee717af750 feat(acl): granular per-folder permissions + stricter gates; WebDAV & UI aligned 2025-10-22 21:36:04 -04:00
Ryan
0ad7034a7d feat(editor): make modal non-blocking; add SRI + timeout for CodeMirror mode loads 2025-10-20 03:16:20 -04:00
Ryan
d29900d6ba security(acl): enforce folder-scope & own-only; fix file list “Select All”; harden ops 2025-10-20 02:28:03 -04:00
Ryan
5ffc068041 docs(README): remove public demo badge/credentials 2025-10-20 01:18:59 -04:00
Ryan
1935cb2442 feat(dnd): default cards to sidebar on medium screens when no saved layout 2025-10-20 01:12:50 -04:00
Ryan
af9887e651 fix(admin): modal bugs; chore(api): update ReDoc SRI; docs(openapi): add annotations + spec 2025-10-20 00:38:35 -04:00
Ryan
327eea2835 docs(readme): reflect ACL overhaul & WebDAV enforcement 2025-10-19 07:58:38 -04:00
Ryan
3843daa228 docs: add “Security posture” to README and refresh SECURITY.md 2025-10-19 07:54:27 -04:00
Ryan
169e03be5d docs(readme): add Docker CI badge for filerise-docker workflow 2025-10-19 07:29:09 -04:00
Ryan
be605b4522 fix(config/ui): serve safe public config to non-admins; init early; gate trash UI to admins; dynamic title; demo toast (closes #56) 2025-10-19 07:19:29 -04:00
Ryan
090286164d fix(folder-model): resolve syntax error, unexpected token 2025-10-17 03:24:49 -04:00
Ryan
dc1649ace3 fix(folder-model): resolve PHP parse error 2025-10-17 03:20:33 -04:00
Ryan
b6d86b7896 chore(release): v1.5.0 - ACL hardening, Folder Access & WebDAV permissions (closes #31, closes #55) 2025-10-17 03:14:00 -04:00
Ryan
25ce6a76be feat(permissions)!: granular ACL (bypassOwnership/canShare/canZip/viewOwnOnly), admin panel v1.4.0 UI, and broad hardening across controllers/models/frontend (closes #53) 2025-10-15 23:56:39 -04:00
Ryan
f2ab2a96bc CI: set least-privileged GITHUB_TOKEN (permissions: contents: read) 2025-10-09 00:09:27 -04:00
Ryan
c22c8e0f34 CI: fix YAML lint issues 2025-10-09 00:02:12 -04:00
Ryan
070515e7a6 CI: fix YAML lint issues and normalize headers/EOF across configs 2025-10-08 23:55:52 -04:00
Ryan
7a0f4ddbb4 ci: stabilize pipeline with PHP matrix, shellcheck, hadolint, and YAML/JSON/compose lint 2025-10-08 23:49:46 -04:00
Ryan
e1c15eb95a chore: set up CI, add compose, tighten ignores, refresh README 2025-10-08 23:43:26 -04:00
Ryan
2400dcb9eb feat(startup): stream error.log to console by default; add LOG_STREAM selector 2025-10-07 22:30:21 -04:00
Ryan
c717f8be60 feat(start.sh): stream Apache logs to console + startup polish 2025-10-07 22:14:28 -04:00
Ryan
3dd5a8664a feat/perf: large-file handling, faster file list, richer CodeMirror modes (fixes #48) 2025-10-06 00:10:31 -04:00
Ryan
0cb47b4054 fix(admin): OIDC optional by default; validate only when enabled (fixes #44) 2025-10-05 05:48:25 -04:00
Ryan
e3e3aaa475 chore(scanner): skip profile_pics subtree during scans 2025-10-04 03:35:39 -04:00
Ryan
494be05801 fix(scanner): rebuild per-folder metadata to match File/Folder models 2025-10-04 03:15:55 -04:00
Ryan
ceb651894e fix(scanner): resolve dirs via CLI/env/constants; write per-item JSON; skip trash 2025-10-04 03:00:15 -04:00
Ryan
ad72ef74d1 Fix: robust PUID/PGID handling; optional ownership normalization (closes #43) 2025-10-04 02:25:16 -04:00
Ryan
680c82638f Chore: keep BASE_URL fallback, prefer env SHARE_URL; fix HTTPS auto-detect 2025-10-04 01:55:02 -04:00
Ryan
31f54afc74 Fix: index externally added files on startup; harden start.sh (fixes #46) 2025-10-04 01:13:45 -04:00
Ryan
4f39b3a41e Support clipboard paste image uploads with UI cleanup (closes #40) 2025-05-27 23:48:33 -04:00
Ryan
40cecc10ad support CIFS-mounted uploads and automatic scan on container start (closes #34) 2025-05-27 19:53:00 -04:00
Ryan
aee78c9750 REGEX_FOLDER_NAME updated (closes #39) 2025-05-26 18:14:08 -04:00
Ryan
16ccb66d55 Add folder-strip context menu & combined Create File/Folder dropdown 2025-05-23 08:55:09 -04:00
Ryan
9209f7a582 Center folder strip name, fix file share url, keep fileList wrapping tight (closes #38) 2025-05-22 07:32:38 -04:00
Ryan
4a736b0224 Enable drag-and-drop to folder strip & fix restore toast messaging 2025-05-21 00:54:20 -04:00
Ryan
f162a7d0d7 updateFileActionButtons to hide or show depending on action 2025-05-20 09:55:40 -04:00
Ryan
3fc526df7f Add folder strip and “Create File” functionality (closes #36) 2025-05-19 00:39:10 -04:00
Ryan
20422cf5a7 Drag‐and‐Drop Upload extended to File List 2025-05-15 02:24:26 -04:00
Ryan
492bab36ca Fix duplicated Upload & Folder cards if they were added to header and page was refreshed 2025-05-14 08:08:18 -04:00
Ryan
f2f7697994 Link updated in readme 2025-05-14 07:09:55 -04:00
Ryan
13aa011632 #nosec to silence false positive 2025-05-14 07:05:35 -04:00
Ryan
1add160f5d setAttribute + encodeURI to avoid “DOM text reinterpreted as HTML” alerts 2025-05-14 07:00:04 -04:00
Ryan
87368143b5 Fixed new issues with Undefined username in header on profile pic change & TOTP Enabled not checked 2025-05-14 06:51:16 -04:00
Ryan
939aa032f0 ui: polish header and user panel with dropdown + profile pic support & file list adjustments 2025-05-14 05:20:22 -04:00
Ryan
fbd21a035b Ensure /var/www/config exists and is owned by www-data so that start.sh sed -i updates work reliably 2025-05-08 17:20:36 -04:00
Ryan
2f391d11db fix(admin-api): omit clientSecret from getConfig response for security & add OIDC scope. 2025-05-08 11:39:44 -04:00
Ryan
8c70783d5a fix(upload): relax filename validation regex to allow broader Unicode and special chars (closes #29) 2025-05-08 04:58:57 -04:00
Ryan
b4d6f01432 feat(admin): add proxy-only auth bypass and configurable auth header (closes #28) 2025-05-08 04:43:33 -04:00
Ryan
d48b15a5f4 screenshots updated 2025-05-05 08:49:27 -04:00
Ryan
d1726f0160 Refactor auth flow: add loading overlay, separate login, extract initializeApp 2025-05-05 07:28:28 -04:00
Ryan
bd1841b788 Unify modals: shared close button, truncate long filenames, fix sizing & overflow 2025-05-04 15:44:43 -04:00
Ryan
bde35d1d31 Extend clean up expired shared entries 2025-05-04 02:28:33 -04:00
Ryan
8d6a1be777 Fix FolderController readOnly create folder permission 2025-05-04 01:22:43 -04:00
Ryan
56f34ba362 Admin Panel Refactor & Enhancements 2025-05-04 00:23:46 -04:00
Ryan
4d329e046f Remove old controllers 2025-05-04 00:02:38 -04:00
Ryan
f3977153fb Refactor AdminPanel: extract module, add collapsible sections & shared-links management, enforce PascalCase controllers 2025-05-03 23:41:02 -04:00
Ryan
274bedd186 Improve PDF preview and input focus behaviors 2025-04-30 00:53:44 -04:00
Ryan
2e4dbe7f7f support custom expiration durations for file and folder shares (closes #26) 2025-04-28 20:02:11 -04:00
Ryan
0334e443eb fix(shared-folder): sanitize gallery rendering to avoid innerHTML and resolve CodeQL warning (fixes #27) 2025-04-27 18:28:39 -04:00
Ryan
76f5ed5c96 shared-folder: externalize gallery view JS & enforce CSP compliance 2025-04-27 18:18:00 -04:00
Ryan
18f588dc24 Update Manual Installation 2025-04-27 17:23:43 -04:00
Ryan
491c686762 fix: advancedSearchToggle in renderFileTable & renderGalleryView 2025-04-27 17:08:49 -04:00
Ryan
25303df677 fixed: Pagination controls & Items-per-page dropdown 2025-04-27 16:50:22 -04:00
Ryan
ae0d63b86f fix: checkbox in toolbar does not select all files (Fixes #25) 2025-04-27 15:34:41 -04:00
Ryan
41ade2e205 refactor/fix: api redoc 2025-04-26 17:31:51 -04:00
173 changed files with 22475 additions and 12827 deletions

View File

@@ -12,3 +12,9 @@ tmp/
.env
.vscode/
.DS_Store
data/
uploads/
users/
metadata/
sessions/
vendor/

44
.gitattributes vendored
View File

@@ -1,4 +1,40 @@
public/api.html linguist-documentation
public/openapi.json linguist-documentation
resources/ export-ignore
.github/ export-ignore
# --- Docs that shouldn't count toward code stats
public/api.php linguist-documentation
public/openapi.json linguist-documentation
openapi.json.dist linguist-documentation
SECURITY.md linguist-documentation
CHANGELOG.md linguist-documentation
CONTRIBUTING.md linguist-documentation
CODE_OF_CONDUCT.md linguist-documentation
LICENSE linguist-documentation
README.md linguist-documentation
# --- Vendored/minified stuff: exclude from Linguist
public/vendor/** linguist-vendored
public/css/vendor/** linguist-vendored
public/fonts/** linguist-vendored
public/js/**/*.min.js linguist-vendored
public/**/*.min.css linguist-vendored
public/**/*.map linguist-generated
# --- Treat assets as binary (nicer diffs)
*.png -diff
*.jpg -diff
*.jpeg -diff
*.gif -diff
*.webp -diff
*.svg -diff
*.ico -diff
*.woff -diff
*.woff2 -diff
*.ttf -diff
*.otf -diff
*.zip -diff
# --- Keep these out of auto-generated source archives (OK to ignore)
# Only ignore things you *never* need in release tarballs
.github/ export-ignore
resources/ export-ignore
# --- Normalize text files
* text=auto

3
.github/FUNDING.yml vendored Normal file
View File

@@ -0,0 +1,3 @@
---
github: [error311]
ko_fi: error311

12
.github/codeql/codeql-config.yml vendored Normal file
View File

@@ -0,0 +1,12 @@
---
name: "FileRise CodeQL config"
paths:
- "public/js"
- "api"
paths-ignore:
- "public/vendor/**"
- "public/css/vendor/**"
- "public/fonts/**"
- "public/**/*.min.js"
- "public/**/*.min.css"
- "public/**/*.map"

92
.github/workflows/ci.yml vendored Normal file
View File

@@ -0,0 +1,92 @@
---
name: CI
"on":
push:
branches: [master, main]
pull_request:
workflow_dispatch:
permissions:
contents: read
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
jobs:
php-lint:
runs-on: ubuntu-latest
strategy:
matrix:
php: ['8.1', '8.2', '8.3']
steps:
- uses: actions/checkout@v4
- uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
coverage: none
- name: Validate composer.json (if present)
run: |
if [ -f composer.json ]; then composer validate --no-check-publish; fi
- name: Composer audit (if lock present)
run: |
if [ -f composer.lock ]; then composer audit || true; fi
- name: PHP syntax check
run: |
set -e
mapfile -t files < <(git ls-files '*.php')
if [ "${#files[@]}" -gt 0 ]; then
for f in "${files[@]}"; do php -l "$f"; done
else
echo "No PHP files found."
fi
shellcheck:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: sudo apt-get update && sudo apt-get install -y shellcheck
- name: ShellCheck all scripts
run: |
set -e
mapfile -t sh < <(git ls-files '*.sh')
if [ "${#sh[@]}" -gt 0 ]; then
shellcheck "${sh[@]}"
else
echo "No shell scripts found."
fi
dockerfile-lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Lint Dockerfile with hadolint
uses: hadolint/hadolint-action@v3.1.0
with:
dockerfile: Dockerfile
failure-threshold: error
ignore: DL3008,DL3059
sanity:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: sudo apt-get update && sudo apt-get install -y jq yamllint
- name: Lint JSON
run: |
set -e
mapfile -t jsons < <(git ls-files '*.json' ':!:vendor/**')
if [ "${#jsons[@]}" -gt 0 ]; then
for j in "${jsons[@]}"; do jq -e . "$j" >/dev/null; done
else
echo "No JSON files."
fi
- name: Lint YAML
run: |
set -e
mapfile -t yamls < <(git ls-files '*.yml' '*.yaml')
if [ "${#yamls[@]}" -gt 0 ]; then
yamllint -d "{extends: default, rules: {line-length: disable, truthy: {check-keys: false}}}" "${yamls[@]}"
else
echo "No YAML files."
fi

110
.github/workflows/release-on-version.yml vendored Normal file
View File

@@ -0,0 +1,110 @@
---
name: Release on version.js update
on:
push:
branches:
- master
paths:
- public/js/version.js
workflow_run:
workflows: "Bump version and sync Changelog to Docker Repo"
types: completed
permissions:
contents: write
jobs:
release:
runs-on: ubuntu-latest
concurrency:
group: release-${{ github.ref }}-${{ github.sha }}
cancel-in-progress: false
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Read version from version.js
id: ver
shell: bash
run: |
set -euo pipefail
VER=$(grep -Eo "APP_VERSION\s*=\s*['\"]v[^'\"]+['\"]" public/js/version.js | sed -E "s/.*['\"](v[^'\"]+)['\"].*/\1/")
if [[ -z "$VER" ]]; then
echo "Could not parse APP_VERSION from version.js" >&2
exit 1
fi
echo "version=$VER" >> "$GITHUB_OUTPUT"
echo "Parsed version: $VER"
- name: Skip if tag already exists
id: tagcheck
shell: bash
run: |
set -euo pipefail
git fetch --tags --quiet
if git rev-parse -q --verify "refs/tags/${{ steps.ver.outputs.version }}" >/dev/null; then
echo "exists=true" >> "$GITHUB_OUTPUT"
echo "Tag ${{ steps.ver.outputs.version }} already exists. Skipping release."
else
echo "exists=false" >> "$GITHUB_OUTPUT"
fi
- name: Prepare release notes from CHANGELOG.md (optional)
if: steps.tagcheck.outputs.exists == 'false'
id: notes
shell: bash
run: |
set -euo pipefail
NOTES_PATH=""
if [[ -f CHANGELOG.md ]]; then
awk '
BEGIN{found=0}
/^## / && !found {found=1}
found && /^---$/ {exit}
found {print}
' CHANGELOG.md > RELEASE_BODY.md || true
# Trim trailing blank lines
sed -i -e :a -e '/^\n*$/{$d;N;ba' -e '}' RELEASE_BODY.md || true
if [[ -s RELEASE_BODY.md ]]; then
NOTES_PATH="RELEASE_BODY.md"
fi
fi
echo "path=$NOTES_PATH" >> "$GITHUB_OUTPUT"
- name: (optional) Build archive to attach
if: steps.tagcheck.outputs.exists == 'false'
shell: bash
run: |
set -euo pipefail
zip -r "FileRise-${{ steps.ver.outputs.version }}.zip" public/ README.md LICENSE >/dev/null || true
# Path A: we have extracted notes -> use body_path
- name: Create GitHub Release (with CHANGELOG snippet)
if: steps.tagcheck.outputs.exists == 'false' && steps.notes.outputs.path != ''
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ steps.ver.outputs.version }}
target_commitish: ${{ github.sha }}
name: ${{ steps.ver.outputs.version }}
body_path: ${{ steps.notes.outputs.path }}
generate_release_notes: false
files: |
FileRise-${{ steps.ver.outputs.version }}.zip
# Path B: no notes -> let GitHub auto-generate from commits
- name: Create GitHub Release (auto notes)
if: steps.tagcheck.outputs.exists == 'false' && steps.notes.outputs.path == ''
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ steps.ver.outputs.version }}
target_commitish: ${{ github.sha }}
name: ${{ steps.ver.outputs.version }}
generate_release_notes: true
files: |
FileRise-${{ steps.ver.outputs.version }}.zip

View File

@@ -1,43 +1,115 @@
name: Sync Changelog to Docker Repo
---
name: Bump version and sync Changelog to Docker Repo
on:
push:
paths:
- 'CHANGELOG.md'
- "CHANGELOG.md"
permissions:
contents: write
jobs:
sync:
bump_and_sync:
runs-on: ubuntu-latest
steps:
- name: Checkout FileRise
uses: actions/checkout@v4
- uses: actions/checkout@v4
with:
path: file-rise
fetch-depth: 0
- name: Extract version from commit message
id: ver
shell: bash
run: |
set -euo pipefail
MSG="${{ github.event.head_commit.message }}"
if [[ "$MSG" =~ release\((v[0-9]+\.[0-9]+\.[0-9]+)\) ]]; then
echo "version=${BASH_REMATCH[1]}" >> "$GITHUB_OUTPUT"
echo "Found version: ${BASH_REMATCH[1]}"
else
echo "version=" >> "$GITHUB_OUTPUT"
echo "No release(vX.Y.Z) tag in commit message; skipping bump."
fi
- name: Update public/js/version.js
if: steps.ver.outputs.version != ''
shell: bash
run: |
set -euo pipefail
cat > public/js/version.js <<'EOF'
// generated by CI
window.APP_VERSION = '${{ steps.ver.outputs.version }}';
EOF
- name: Stamp asset cache-busters (?v=...) in HTML/CSS and {{APP_VER}} everywhere
if: steps.ver.outputs.version != ''
shell: bash
run: |
set -euo pipefail
VER="${{ steps.ver.outputs.version }}" # e.g. v1.6.9
QVER="${VER#v}" # e.g. 1.6.9
echo "Stamping ?v=${QVER} and {{APP_VER}}=${VER}"
# 1) Only stamp ?v= in HTML/CSS (avoid JS concatenation issues)
mapfile -t html_css < <(git ls-files -- 'public/*.html' 'public/**/*.html' 'public/*.css' 'public/**/*.css')
for f in "${html_css[@]}"; do
sed -E -i "s/(\?v=)[^\"'&<>\s]*/\1${QVER}/g" "$f"
sed -E -i "s/\{\{APP_VER\}\}/${VER}/g" "$f"
done
# 2) For JS, only replace the {{APP_VER}} placeholder (do NOT touch ?v=)
mapfile -t jsfiles < <(git ls-files -- 'public/*.js' 'public/**/*.js')
for f in "${jsfiles[@]}"; do
sed -E -i "s/\{\{APP_VER\}\}/${VER}/g" "$f"
done
echo "Changed files:"
git status --porcelain | awk '{print $2}' | sed 's/^/ - /'
- name: Commit version bump + stamped assets
if: steps.ver.outputs.version != ''
shell: bash
run: |
set -euo pipefail
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git add public/js/version.js public
if git diff --cached --quiet; then
echo "No changes to commit"
else
git commit -m "chore(release): set APP_VERSION and stamp assets to ${{ steps.ver.outputs.version }} [skip ci]"
git push
fi
- name: Checkout filerise-docker
if: steps.ver.outputs.version != ''
uses: actions/checkout@v4
with:
repository: error311/filerise-docker
token: ${{ secrets.PAT_TOKEN }}
path: docker-repo
- name: Copy CHANGELOG.md
- name: Copy CHANGELOG.md and write VERSION
if: steps.ver.outputs.version != ''
shell: bash
run: |
cp file-rise/CHANGELOG.md docker-repo/CHANGELOG.md
set -euo pipefail
cp CHANGELOG.md docker-repo/CHANGELOG.md
echo "${{ steps.ver.outputs.version }}" > docker-repo/VERSION
- name: Commit & push
- name: Commit & push to docker repo
if: steps.ver.outputs.version != ''
working-directory: docker-repo
shell: bash
run: |
set -euo pipefail
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git add CHANGELOG.md
git add CHANGELOG.md VERSION
if git diff --cached --quiet; then
echo "No changes to commit"
else
git commit -m "chore: sync CHANGELOG.md from FileRise"
git commit -m "chore: sync CHANGELOG.md and VERSION (${{ steps.ver.outputs.version }}) from FileRise"
git push origin main
fi
fi

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
/data/

File diff suppressed because it is too large Load Diff

View File

@@ -51,6 +51,11 @@ COPY custom-php.ini /etc/php/8.3/apache2/conf.d/99-app-tuning.ini
COPY --from=appsource /var/www /var/www
COPY --from=composer /app/vendor /var/www/vendor
# ── ensure config/ is writable by www-data so sed -i can work ──
RUN mkdir -p /var/www/config \
&& chown -R www-data:www-data /var/www/config \
&& chmod 750 /var/www/config
# Secure permissions: code read-only, only data dirs writable
RUN chown -R root:www-data /var/www && \
find /var/www -type d -exec chmod 755 {} \; && \
@@ -120,6 +125,10 @@ RUN cat <<'EOF' > /etc/apache2/sites-available/000-default.conf
<FilesMatch "^\.">
Require all denied
</FilesMatch>
<Files "api.php">
Header always set Content-Security-Policy "default-src 'self'; script-src 'self' https://cdn.redoc.ly; style-src 'self' 'unsafe-inline'; worker-src 'self' https://cdn.redoc.ly blob:; connect-src 'self'; img-src 'self' data: blob:; frame-ancestors 'self'; base-uri 'self'; form-action 'self';"
</Files>
ErrorLog /var/www/metadata/log/error.log
CustomLog /var/www/metadata/log/access.log combined
@@ -127,7 +136,7 @@ RUN cat <<'EOF' > /etc/apache2/sites-available/000-default.conf
EOF
# Enable required modules
RUN a2enmod rewrite headers proxy proxy_fcgi expires deflate
RUN a2enmod rewrite headers proxy proxy_fcgi expires deflate ssl
EXPOSE 80 443
COPY start.sh /usr/local/bin/start.sh

365
README.md
View File

@@ -1,11 +1,31 @@
# FileRise
**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.
[![GitHub stars](https://img.shields.io/github/stars/error311/FileRise?style=social)](https://github.com/error311/FileRise)
[![Docker pulls](https://img.shields.io/docker/pulls/error311/filerise-docker)](https://hub.docker.com/r/error311/filerise-docker)
[![Docker CI](https://img.shields.io/github/actions/workflow/status/error311/filerise-docker/main.yml?branch=main&label=Docker%20CI)](https://github.com/error311/filerise-docker/actions/workflows/main.yml)
[![CI](https://img.shields.io/github/actions/workflow/status/error311/FileRise/ci.yml?branch=master&label=CI)](https://github.com/error311/FileRise/actions/workflows/ci.yml)
[![Demo](https://img.shields.io/badge/demo-live-brightgreen)](https://demo.filerise.net)
[![Release](https://img.shields.io/github/v/release/error311/FileRise?include_prereleases&sort=semver)](https://github.com/error311/FileRise/releases)
[![License](https://img.shields.io/github/license/error311/FileRise)](LICENSE)
[![Sponsor on GitHub](https://img.shields.io/badge/Sponsor-❤-red)](https://github.com/sponsors/error311)
[![Support on Ko-fi](https://img.shields.io/badge/Ko--fi-Buy%20me%20a%20coffee-orange)](https://ko-fi.com/error311)
**4/3/2025 Video demo:**
**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)
<https://github.com/user-attachments/assets/221f6a53-85f5-48d4-9abe-89445e0af90e>
**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 youre on ≤1.4.x, please upgrade.
**10/25/2025 Video demo:**
<https://github.com/user-attachments/assets/a2240300-6348-4de7-b72f-1b85b7da3a08>
**Dark mode:**
![Dark Header](https://raw.githubusercontent.com/error311/FileRise/refs/heads/master/resources/dark-header.png)
@@ -14,152 +34,282 @@ 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. No more failed transfers 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 even 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:** Easily 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 per page) with navigation controls, and file sizes are displayed in MB for clarity. Share files with others using one-time or expiring public links (with password protection if desired) convenient for sending individual files without exposing the whole app.
- 🗃️ **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.
- 🔌 **WebDAV Support:** Mount FileRise as a network drive **or use it headless from the CLI**. Standard WebDAV operations (upload / download / rename / delete) work in Cyberduck, WinSCP, GNOME Files, Finder, etc., and you can also script against it with `curl` see the [WebDAV](https://github.com/error311/FileRise/wiki/WebDAV) + [curl](https://github.com/error311/FileRise/wiki/Accessing-FileRise-via-curl%C2%A0(WebDAV)) quickstart for examples. FolderOnly users are restricted to their personal directory, while admins and unrestricted users have full access.
- 🔐 **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:
- 📚 **API Documentation:** Fully autogenerated OpenAPI spec (`openapi.json`) and interactive HTML docs (`api.html`) powered by Redoc.
| 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). |
- 📝 **Built-in Editor & Preview:** View images, videos, audio, and PDFs inline with a preview modal no need to download just to see them. Edit text/code files right in your browser with a CodeMirror-based editor featuring syntax highlighting and line numbers. Great for config files or notes tweak and save changes without leaving FileRise.
- **Automatic Propagation:** Enabling **Manage** on a folder applies to all subfolders; deselecting subfolder permissions overrides inheritance in the UI.
- 🏷️ **Tags & Search:** Categorize your files with color-coded tags and locate them instantly using our indexed real-time search. Easily switch to Advanced Search mode to enable fuzzy matching not only across file names, tags, and uploader fields but also within the content of text files—helping you find that “important” document even if you make a typo or need to search deep within the file.
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.
- 🔒 **User Authentication & User Permissions:** Secure your portal with username/password login. Supports multiple users create user accounts (admin UI provided) for family or team members. User permissions such as User “Folder Only” feature assigns each user a dedicated folder within the root directory, named after their username, restricting them from viewing or modifying other directories. User Read Only and Disable Upload are additional permissions. FileRise also integrates with Single Sign-On (OIDC) providers (e.g., OAuth2/OIDC for Google/Authentik/Keycloak) and offers optional TOTP two-factor auth for extra security.
- 🔌 **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.
- 🎨 **Responsive UI (Dark/Light Mode):** FileRise is mobile-friendly out of the box manage files from your phone or tablet with a responsive layout. Choose between Dark mode or Light theme, or let it follow your system preference. The interface remembers your preferences (layout, items per page, last visited folder, etc.) for a personalized experience each time.
- 📚 **API Documentation:** Auto-generated OpenAPI spec (`openapi.json`) with interactive HTML docs (`api.html`) via Redoc.
- 🌐 **Internationalization & Localization:** FileRise supports multiple languages via an integrated i18n system. Users can switch languages through a user panel dropdown, and their choice is saved in local storage for a consistent experience across sessions. Currently available in English, Spanish, French & German—please report any translation issues you encounter.
- 📝 **Built-in Editor & Preview:** Inline preview for images, video, audio, and PDFs. CodeMirror-based editor for text/code with syntax highlighting and line numbers.
- 🗑 **Trash & File Recovery:** Mistakenly deleted files? No worries deleted items go to the Trash instead of immediate removal. Admins can restore files from Trash or empty it to free space. FileRise auto-purges old trash entries (default 3 days) to keep your storage tidy.
- 🏷 **Tags & Search:** Add color-coded tags and search by name, tag, uploader, or content. Advanced fuzzy search indexes metadata and file contents.
- ⚙️ **Lightweight & SelfContained:** FileRise runs on PHP 8.1+ with no external database required data is stored in files (users, metadata) for simplicity. Its a singlefolder web app you can drop into any Apache/PHP server or run as a container. Docker & Unraid ready: use our prebuilt image for a hasslefree setup. Memory and CPU footprint is minimal, yet the app scales to thousands of files with pagination and sorting features.
- 🔒 **Authentication & SSO:** Username/password, optional TOTP 2FA, and OIDC (Google, Authentik, Keycloak).
(For a full list of features and detailed changelogs, see the [Wiki](https://github.com/error311/FileRise/wiki), [changelog](https://github.com/error311/FileRise/blob/master/CHANGELOG.md) or the [releases](https://github.com/error311/FileRise/releases) pages.)
- 🗑️ **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, German & Simplified Chinese 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).)
---
## Live Demo
Curious about the UI? **Check out the live demo:** <https://demo.filerise.net> (login with username “demo” and password “demo”). *The demo is read-only for security*. Explore the interface, switch themes, preview files, and see FileRise in action!
[![Demo](https://img.shields.io/badge/demo-live-brightgreen)](https://demo.filerise.net)
**Demo credentials:** `demo` / `demo`
Curious about the UI? **Check out the live demo:** <https://demo.filerise.net> (login with username “demo” and password “demo”). **The demo is read-only for security.** Explore the interface, switch themes, preview files, and see FileRise in action!
---
## Installation & Setup
You can deploy FileRise either by running the **Docker container** (quickest way) or by a **manual installation** on a PHP web server. Both methods are outlined below.
Deploy FileRise using the **Docker image** (quickest) or a **manual install** on a PHP web server.
### 1. Running with Docker (Recommended)
---
If you have Docker installed, you can get FileRise up and running in minutes:
### Environment variables
- **Pull the image from Docker Hub:**
| Variable | Default | Purpose |
|---|---|---|
| `TIMEZONE` | `UTC` | PHP/app timezone. |
| `DATE_TIME_FORMAT` | `m/d/y h:iA` | Display format used in UI. |
| `TOTAL_UPLOAD_SIZE` | `5G` | Max combined upload per request (resumable). |
| `SECURE` | `false` | Set `true` if served behind HTTPS proxy (affects link generation). |
| `PERSISTENT_TOKENS_KEY` | *(required)* | Secret for “Remember Me” tokens. Change from the example! |
| `PUID` / `PGID` | `1000` / `1000` | Map `www-data` to host uid:gid (Unraid: often `99:100`). |
| `CHOWN_ON_START` | `true` | First run: try to chown mounted dirs to PUID:PGID. |
| `SCAN_ON_START` | `true` | Reindex files added outside UI at boot. |
| `SHARE_URL` | *(blank)* | Override base URL for share links; blank = auto-detect. |
``` bash
---
### 1) Running with Docker (Recommended)
#### Pull the image
```bash
docker pull error311/filerise-docker:latest
```
- **Run a container:**
#### Run a container
``` bash
```bash
docker run -d \
--name filerise \
-p 8080:80 \
-e TIMEZONE="America/New_York" \
-e DATE_TIME_FORMAT="m/d/y h:iA" \
-e TOTAL_UPLOAD_SIZE="5G" \
-e SECURE="false" \
-e PERSISTENT_TOKENS_KEY="please_change_this_@@" \
-e PUID="1000" \
-e PGID="1000" \
-e CHOWN_ON_START="true" \
-e SCAN_ON_START="true" \
-e SHARE_URL="" \
-v ~/filerise/uploads:/var/www/uploads \
-v ~/filerise/users:/var/www/users \
-v ~/filerise/metadata:/var/www/metadata \
--name filerise \
error311/filerise-docker:latest
```
```
This will start FileRise on port 8080. Visit `http://your-server-ip:8080` to access it. Environment variables shown above are optional for instance, set `SECURE="true"` to enforce HTTPS (assuming you have SSL at proxy level) and adjust `TIMEZONE` as needed. The volume mounts ensure your files and user data persist outside the container.
The app runs as www-data mapped to PUID/PGID. Ensure your mounted uploads/, users/, metadata/ are owned by PUID:PGID (e.g., chown -R 1000:1000 …), or set PUID/PGID to match existing host ownership (e.g., 99:100 on Unraid). On NAS/NFS, apply the ownership change on the host/NAS.
- **Using Docker Compose:**
Alternatively, use **docker-compose**. Save the snippet below as docker-compose.yml and run `docker-compose up -d`:
This starts FileRise on port **8080** → visit `http://your-server-ip:8080`.
``` yaml
version: '3'
**Notes**
- **Do not use** Docker `--user`. Use **PUID/PGID** to map on-disk ownership (e.g., `1000:1000`; on Unraid typically `99:100`).
- `CHOWN_ON_START=true` is recommended on **first run**. Set to **false** later for faster restarts.
- `SCAN_ON_START=true` indexes files added outside the UI so their metadata appears.
- `SHARE_URL` optional; leave blank to auto-detect host/scheme. Set to site root (e.g., `https://files.example.com`) if needed.
- Set `SECURE="true"` if you serve via HTTPS at your proxy layer.
**Verify ownership mapping (optional)**
```bash
docker exec -it filerise id www-data
# expect: uid=1000 gid=1000 (or 99/100 on Unraid)
```
#### Using Docker Compose
Save as `docker-compose.yml`, then `docker-compose up -d`:
```yaml
services:
filerise:
image: error311/filerise-docker:latest
container_name: filerise
ports:
- "8080:80"
environment:
TIMEZONE: "UTC"
DATE_TIME_FORMAT: "m/d/y h:iA"
TOTAL_UPLOAD_SIZE: "10G"
SECURE: "false"
PERSISTENT_TOKENS_KEY: "please_change_this_@@"
# Ownership & indexing
PUID: "1000" # Unraid users often use 99
PGID: "1000" # Unraid users often use 100
CHOWN_ON_START: "true" # first run; set to "false" afterwards
SCAN_ON_START: "true" # index files added outside the UI at boot
# Sharing URL (optional): leave blank to auto-detect from host/scheme
SHARE_URL: ""
volumes:
- ./uploads:/var/www/uploads
- ./users:/var/www/users
- ./metadata:/var/www/metadata
restart: unless-stopped
```
FileRise will be accessible at `http://localhost:8080` (or your servers IP). The above example also sets a custom `PERSISTENT_TOKENS_KEY` (used to encrypt “remember me” tokens) be sure to change it to a random string for security.
Access at `http://localhost:8080` (or your servers IP).
The example sets a custom `PERSISTENT_TOKENS_KEY`—change it to a strong random string.
**First-time Setup:** On first launch, FileRise will detect no users and prompt you to create an **Admin account**. Choose your admin username & password, and youre in! You can then head to the **User Management** section to add additional users if needed.
-`CHOWN_ON_START=true` attempts to align ownership **inside the container**; if the host/NAS disallows changes, set the correct UID/GID on the host.”
### 2. Manual Installation (PHP/Apache)
If you prefer to run FileRise on a traditional web server (LAMP stack or similar):
- **Requirements:** PHP 8.1 or higher, Apache (with mod_php) or another web server configured for PHP. Ensure PHP extensions json, curl, and zip are enabled. No database needed.
- **Download Files:** Clone this repo or download the [latest release archive](https://github.com/error311/FileRise/releases).
``` bash
git clone https://github.com/error311/FileRise.git
```
Place the files into your web servers directory (e.g., `/var/www/public`). It can be in a subfolder (just adjust the `BASE_URL` in config as below).
- **Composer Dependencies:** If you plan to use OIDC (SSO login), install Composer and run `composer install` in the FileRise directory. (This pulls in a couple of PHP libraries like jumbojett/openid-connect for OAuth support.)
- **Folder Permissions:** Ensure the server can write to the following directories (create them if they dont exist):
``` bash
mkdir -p uploads users metadata
chown -R www-data:www-data uploads users metadata # www-data is Apache user; use appropriate user
chmod -R 775 uploads users metadata
```
The uploads/ folder is where files go, users/ stores the user credentials file, and metadata/ holds metadata like tags and share links.
- **Configuration:** Open the `config.php` file in a text editor. You may want to adjust:
- `BASE_URL` the URL where you will access FileRise (e.g., `“https://files.mydomain.com/”`). This is used for generating share links.
- `TIMEZONE` and `DATE_TIME_FORMAT` match your locale (for correct timestamps).
- `TOTAL_UPLOAD_SIZE` max aggregate upload size (default 5G). Also adjust PHPs `upload_max_filesize` and `post_max_size` to at least this value (the Docker start script auto-adjusts PHP limits).
- `PERSISTENT_TOKENS_KEY` set a unique secret if you use “Remember Me” logins, to encrypt the tokens.
- Other settings like `UPLOAD_DIR`, `USERS_FILE` etc. generally dont need changes unless you move those folders. Defaults are set for the directories mentioned above.
- **Web Server Config:** If using Apache, ensure `.htaccess` files are allowed or manually add the rules from `.htaccess` to your Apache config these disable directory listings and prevent access to certain files. For Nginx or others, youll need to replicate those protections (see Wiki: [Nginx Setup for examples](https://github.com/error311/FileRise/wiki/Nginx-Setup)). Also enable mod_rewrite if not already, as FileRise may use pretty URLs for share links.
Now navigate to the FileRise URL in your browser. On first load, youll be prompted to create the Admin user (same as Docker setup). After that, the application is ready to use!
**First-time Setup**
On first launch, if no users exist, youll be prompted to create an **Admin account**. Then use **User Management** to add more users.
---
## Quickstart: Mount via WebDAV
### 2) Manual Installation (PHP/Apache)
Once FileRise is running, you must enable WebDAV in admin panel to access it.
If you prefer a traditional web server (LAMP stack or similar):
**Requirements**
- PHP **8.3+**
- Apache (mod_php) or another web server configured for PHP
- PHP extensions: `json`, `curl`, `zip` (and typical defaults). No database required.
**Download Files**
```bash
git clone https://github.com/error311/FileRise.git
```
Place the files in your web root (e.g., `/var/www/`). Subfolder installs are fine.
**Composer (if applicable)**
```bash
composer install
```
**Folders & Permissions**
```bash
mkdir -p uploads users metadata
chown -R www-data:www-data uploads users metadata # use your web user
chmod -R 775 uploads users metadata
```
- `uploads/`: actual files
- `users/`: credentials & token storage
- `metadata/`: file metadata (tags, share links, etc.)
**Configuration**
Edit `config.php`:
- `TIMEZONE`, `DATE_TIME_FORMAT` for your locale.
- `TOTAL_UPLOAD_SIZE` (ensure PHP `upload_max_filesize` and `post_max_size` meet/exceed this).
- `PERSISTENT_TOKENS_KEY` for “Remember Me” tokens.
**Share link base URL**
- Set **`SHARE_URL`** via web-server env vars (preferred),
**or** keep using `BASE_URL` in `config.php` as a fallback.
- If neither is set, FileRise auto-detects from the current host/scheme.
**Web server config**
- Apache: allow `.htaccess` or merge its rules; ensure `mod_rewrite` is enabled.
- Nginx/other: replicate basic protections (no directory listing, deny sensitive files). See Wiki for examples.
Browse to your FileRise URL; youll be prompted to create the Admin user on first load.
---
### 3) Admins
> **Admins in ACL UI**
> Admin accounts appear in the Folder Access and User Permissions modals as **read-only** with full access implied. This is by design—admins always have full control and are excluded from save payloads.
---
## Unraid
- Install from **Community Apps** → search **FileRise**.
- Default **bridge**: access at `http://SERVER_IP:8080/`.
- **Custom br0** (own IP): map host ports to **80/443** if you want bare `http://CONTAINER_IP/` without a port.
- See the [support thread](https://forums.unraid.net/topic/187337-support-filerise/) for Unraid-specific help.
---
## Upgrade
```bash
docker pull error311/filerise-docker:latest
docker stop filerise && docker rm filerise
# re-run with the same -v and -e flags you used originally
```
---
## Quick-start: Mount via WebDAV
Once FileRise is running, enable WebDAV in the admin panel.
```bash
# Linux (GVFS/GIO)
gio mount dav://demo@your-host/webdav.php/
# macOS (Finder → Go → Connect to Server…)
dav://demo@your-host/webdav.php/
https://your-host/webdav.php/
```
> Finder typically uses `https://` (or `http://`) URLs for WebDAV, while GNOME/KDE use `dav://` / `davs://`.
### Windows (File Explorer)
- Open **File Explorer** → Right-click **This PC****Map network drive…**
@@ -170,8 +320,8 @@ dav://demo@your-host/webdav.php/
https://your-host/webdav.php/
```
- Check **Connect using different credentials**, and enter your FileRise username and password.
- Click **Finish**. The drive will now appear under **This PC**.
- Check **Connect using different credentials**, then enter your FileRise username/password.
- Click **Finish**.
> **Important:**
> Windows requires HTTPS (SSL) for WebDAV connections by default.
@@ -186,41 +336,64 @@ dav://demo@your-host/webdav.php/
>
> 3. Find or create a `DWORD` value named **BasicAuthLevel**.
> 4. Set its value to `2`.
> 5. Restart the **WebClient** service or reboot your computer.
> 5. Restart the **WebClient** service or reboot.
📖 For a full guide (including SSL setup, HTTP workaround, and troubleshooting), see the [WebDAV Usage Wiki](https://github.com/error311/FileRise/wiki/WebDAV).
📖 See the full [WebDAV Usage Wiki](https://github.com/error311/FileRise/wiki/WebDAV) for SSL setup, HTTP workaround, and troubleshooting.
---
## FAQ / Troubleshooting
- **“Upload failed” or large files not uploading:** Make sure `TOTAL_UPLOAD_SIZE` in config and PHPs `post_max_size` / `upload_max_filesize` are all set high enough. For extremely large files, you might also need to increase max_execution_time in PHP or rely on the resumable upload feature in smaller chunks.
- **“Upload failed” or large files not uploading:** Ensure `TOTAL_UPLOAD_SIZE` in config and PHPs `post_max_size` / `upload_max_filesize` are set high enough. For extremely large files, you might need to increase `max_execution_time` or rely on resumable uploads in smaller chunks.
- **How to enable HTTPS?** FileRise itself doesnt handle TLS. Run it behind a reverse proxy like Nginx, Caddy, or Apache with SSL, or use Docker with a companion like nginx-proxy or Caddy. Set `SECURE="true"` env var in Docker so FileRise knows to generate https links.
- **How to enable HTTPS?** FileRise doesnt terminate TLS itself. Run it behind a reverse proxy (Nginx, Caddy, Apache with SSL) or use a companion like nginx-proxy or Caddy in Docker. Set `SECURE="true"` in Docker so FileRise generates HTTPS links.
- **Changing Admin or resetting password:** Admin can change any users password via the UI (User Management section). If you lose admin access, you can edit the `users/users.txt` file on the server passwords are hashed (bcrypt), but you can delete the admin line and then restart the app to trigger the setup flow again.
- **Changing Admin or resetting password:** Admin can change any users password via **User Management**. If you lose admin access, edit the `users/users.txt` file on the server passwords are hashed (bcrypt), but you can delete the admin line and restart the app to trigger the setup flow again.
- **Where are my files stored?** In the `uploads/` directory (or the path you set for `UPLOAD_DIR`). Within it, files are organized in the folder structure you see in the app. Deleted files move to `uploads/trash/`. Tag information is in `metadata/file_metadata`.json and trash metadata in `metadata/trash.json`, etc. Regular backups of these folders is recommended if the data is important.
- **Where are my files stored?** In the `uploads/` directory (or the path you set). Deleted files move to `uploads/trash/`. Tag information is in `metadata/file_metadata.json` and trash metadata in `metadata/trash.json`, etc. Backups are recommended.
- **Updating FileRise:** If using Docker, pull the new image and recreate the container. For manual installs, download the latest release and replace the files (preserve your `config.php` and the uploads/users/metadata folders). Clear your browser cache if you have issues after an update (in case CSS/JS changed).
- **Updating FileRise:** For Docker, pull the new image and recreate the container. For manual installs, download the latest release and replace files (keep your `config.php` and `uploads/users/metadata`). Clear your browser cache if UI assets changed.
For more Q&A or to ask for help, please check the Discussions or open an issue.
For more Q&A or to ask for help, open a Discussion or Issue.
---
## Security posture
We practice responsible disclosure. All known security issues are fixed in **v1.5.0** (ACL hardening).
Advisories: [GHSA-6p87-q9rh-95wh](https://github.com/error311/FileRise/security/advisories/GHSA-6p87-q9rh-95wh) (≤ 1.3.15), [GHSA-jm96-2w52-5qjj](https://github.com/error311/FileRise/security/advisories/GHSA-jm96-2w52-5qjj) (v1.4.0). Fixed in **v1.5.0**. Thanks to [@kiwi865](https://github.com/kiwi865) for reporting.
If youre running ≤1.4.x, please upgrade.
See also: [SECURITY.md](./SECURITY.md) for how to report vulnerabilities.
---
## Contributing
Contributions are welcome! If you have ideas for new features or have found a bug, feel free to open an issue. Check out the [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines. You can also join the conversation in GitHub Discussions or on Reddit (see links below) to share feedback and suggestions.
Contributions are welcome! See [CONTRIBUTING.md](CONTRIBUTING.md).
Areas to help: translations, bug fixes, UI polish, integrations.
If you like FileRise, a ⭐ star on GitHub is much appreciated!
Areas where you can help: translations, bug fixes, UI improvements, or building integration with other services. If you like FileRise, giving the project a ⭐ star ⭐ on GitHub is also a much-appreciated contribution!
---
## 💖 Sponsor FileRise
If FileRise saves you time (or sparks joy 😄), please consider supporting ongoing development:
- ❤️ [**GitHub Sponsors:**](https://github.com/sponsors/error311) recurring or one-time - helps fund new features and docs.
- ☕ [**Ko-fi:**](https://ko-fi.com/error311) buy me a coffee.
Every bit helps me keep FileRise fast, polished, and well-maintained. Thank you!
---
## Community and Support
- **Reddit:** [r/selfhosted: FileRise Discussion](https://www.reddit.com/r/selfhosted/comments/1jl01pi/introducing_filerise_a_modern_selfhosted_file/) (Announcement and user feedback thread).
- **Reddit:** [r/selfhosted: FileRise Discussion](https://www.reddit.com/r/selfhosted/comments/1kfxo9y/filerise_v131_major_updates_sneak_peek_at_whats/) (Announcement and user feedback thread).
- **Unraid Forums:** [FileRise Support Thread](https://forums.unraid.net/topic/187337-support-filerise/) for Unraid-specific support or issues.
- **GitHub Discussions:** Use the Q&A category for any setup questions, and the Ideas category to suggest enhancements.
- **GitHub Discussions:** Use Q&A for setup questions, Ideas for enhancements.
[![Star History Chart](https://api.star-history.com/svg?repos=error311/FileRise&type=Date)](https://star-history.com/#error311/FileRise&Date)
---
@@ -251,6 +424,10 @@ Areas where you can help: translations, bug fixes, UI improvements, or building
---
## License
## License & Credits
This project is open-source under the MIT License. That means youre free to use, modify, and distribute **FileRise**, with attribution. We hope you find it useful and contribute back!
MIT License see [LICENSE](LICENSE).
This project bundles third-party assets such as Bootstrap, CodeMirror, DOMPurify, Fuse.js, Resumable.js, and Google Fonts (Roboto, Material Icons).
All third-party code and fonts remain under their original open-source licenses (MIT or Apache 2.0).
See THIRD_PARTY.md and the /licenses directory for full license texts and attributions.

View File

@@ -2,32 +2,60 @@
## Supported Versions
FileRise is actively maintained. Only supported versions will receive security updates. For details on which versions are currently supported, please see the [Release Notes](https://github.com/error311/FileRise/releases).
We provide security fixes for the latest minor release line.
| Version | Supported |
|----------|-----------|
| v1.5.x | ✅ |
| ≤ v1.4.x | ❌ |
> Known issues in ≤ v1.4.x are fixed in **v1.5.0** and later.
## Reporting a Vulnerability
If you discover a security vulnerability, please do not open a public issue. Instead, follow these steps:
**Please do not open a public issue.** Use one of the private channels below:
1. **Email Us Privately:**
Send an email to [security@filerise.net](mailto:security@filerise.net) with the subject line “[FileRise] Security Vulnerability Report”.
1) **GitHub Security Advisory (preferred)**
Open a private report here: <https://github.com/error311/FileRise/security/advisories/new>
2. **Include Details:**
Provide a detailed description of the vulnerability, steps to reproduce it, and any other relevant information (e.g., affected versions, screenshots, logs).
2) **Email**
Send details to **<security@filerise.net>** with subject: `[FileRise] Security Vulnerability Report`.
3. **Secure Communication (Optional):**
If you wish to discuss the vulnerability securely, you can use our PGP key. You can obtain our PGP key by emailing us, and we will send it upon request.
### What to include
## Disclosure Policy
- Affected versions (e.g., v1.4.0), component/endpoint, and impact
- Reproduction steps / PoC
- Any logs, screenshots, or crash traces
- Safe test scope used (see below)
- **Acknowledgement:**
We will acknowledge receipt of your report within 48 hours.
- **Resolution Timeline:**
We aim to fix confirmed vulnerabilities within 30 days. In cases where a delay is necessary, we will communicate updates to you directly.
If youd like encrypted comms, ask for our PGP key in your first email.
- **Public Disclosure:**
After a fix is available, details of the vulnerability will be disclosed publicly in a way that does not compromise user security.
## Coordinated Disclosure
## Additional Information
- **Acknowledgement:** within **48 hours**
- **Triage & initial assessment:** within **7 days**
- **Fix target:** within **30 days** for high-severity issues (may vary by complexity)
- **CVE & advisory:** we publish a GitHub Security Advisory and request a CVE when appropriate.
We notify the reporter before public disclosure and credit them (unless they prefer to remain anonymous).
We appreciate responsible disclosure of vulnerabilities and thank all researchers who help keep FileRise secure. For any questions related to this policy, please contact us at [admin@filerise.net](mailto:admin@filerise.net).
## Safe-Harbor / Rules of Engagement
We support good-faith research. Please:
- Avoid privacy violations, data exfiltration, and service disruption (no DoS, spam, or brute-forcing)
- Dont access other users data beyond whats necessary to demonstrate the issue
- Dont run automated scans against production installs you dont own
- Follow applicable laws and make a good-faith effort to respect data and availability
If you follow these guidelines, we wont pursue or support legal action.
## Published Advisories
- **GHSA-6p87-q9rh-95wh** — ≤ **1.3.15**: Improper ownership/permission validation allowed cross-tenant file operations.
- **GHSA-jm96-2w52-5qjj** — **v1.4.0**: Insecure folder visibility via name-based mapping and incomplete ACL checks.
Both are fixed in **v1.5.0** (ACL hardening). Thanks to **[@kiwi865](https://github.com/kiwi865)** for responsible disclosure.
## Questions
General security questions: **<admin@filerise.net>**

View File

@@ -28,13 +28,20 @@ define('TRASH_DIR', UPLOAD_DIR . 'trash/');
define('TIMEZONE', 'America/New_York');
define('DATE_TIME_FORMAT','m/d/y h:iA');
define('TOTAL_UPLOAD_SIZE','5G');
define('REGEX_FOLDER_NAME', '/^[\p{L}\p{N}_\-\s\/\\\\]+$/u');
define('REGEX_FOLDER_NAME','/^(?!^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$)(?!.*[. ]$)(?:[^<>:"\/\\\\|?*\x00-\x1F]{1,255})(?:[\/\\\\][^<>:"\/\\\\|?*\x00-\x1F]{1,255})*$/xu');
define('PATTERN_FOLDER_NAME','[\p{L}\p{N}_\-\s\/\\\\]+');
define('REGEX_FILE_NAME', '/^[\p{L}\p{N}\p{M}%\-\.\(\) _]+$/u');
define('REGEX_FILE_NAME', '/^[^\x00-\x1F\/\\\\]{1,255}$/u');
define('REGEX_USER', '/^[\p{L}\p{N}_\- ]+$/u');
date_default_timezone_set(TIMEZONE);
if (!defined('DEFAULT_BYPASS_OWNERSHIP')) define('DEFAULT_BYPASS_OWNERSHIP', false);
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)
{
@@ -69,16 +76,27 @@ function loadUserPermissions($username)
{
global $encryptionKey;
$permissionsFile = USERS_DIR . 'userPermissions.json';
if (file_exists($permissionsFile)) {
$content = file_get_contents($permissionsFile);
$decrypted = decryptData($content, $encryptionKey);
$json = ($decrypted !== false) ? $decrypted : $content;
$perms = json_decode($json, true);
if (is_array($perms) && isset($perms[$username])) {
return !empty($perms[$username]) ? $perms[$username] : false;
}
if (!file_exists($permissionsFile)) {
return false;
}
return false;
$content = file_get_contents($permissionsFile);
$decrypted = decryptData($content, $encryptionKey);
$json = ($decrypted !== false) ? $decrypted : $content;
$permsAll = json_decode($json, true);
if (!is_array($permsAll)) {
return false;
}
// Try exact match first, then lowercase (since we store keys lowercase elsewhere)
$uExact = (string)$username;
$uLower = strtolower($uExact);
$row = $permsAll[$uExact] ?? $permsAll[$uLower] ?? null;
// Normalize: always return an array when found, else false (to preserve current callers behavior)
return is_array($row) ? $row : false;
}
// Determine HTTPS usage
@@ -88,25 +106,39 @@ $secure = ($envSecure !== false)
: (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');
// Choose session lifetime based on "remember me" cookie
$defaultSession = 7200; // 2 hours
$persistentDays = 30 * 24 * 60 * 60; // 30 days
$sessionLifetime = isset($_COOKIE['remember_me_token'])
? $persistentDays
: $defaultSession;
// Configure PHP session cookie and GC
session_set_cookie_params([
'lifetime' => $sessionLifetime,
'path' => '/',
'domain' => '', // adjust if you need a specific domain
'secure' => $secure,
'httponly' => true,
'samesite' => 'Lax'
]);
ini_set('session.gc_maxlifetime', (string)$sessionLifetime);
$defaultSession = 7200; // 2 hours
$persistentDays = 30 * 24 * 60 * 60; // 30 days
$sessionLifetime = isset($_COOKIE['remember_me_token']) ? $persistentDays : $defaultSession;
/**
* Start session idempotently:
* - If no session: set cookie params + gc_maxlifetime, then session_start().
* - If session already active: DO NOT change ini/cookie params; optionally refresh cookie expiry.
*/
if (session_status() === PHP_SESSION_NONE) {
session_set_cookie_params([
'lifetime' => $sessionLifetime,
'path' => '/',
'domain' => '', // adjust if you need a specific domain
'secure' => $secure,
'httponly' => true,
'samesite' => 'Lax'
]);
ini_set('session.gc_maxlifetime', (string)$sessionLifetime);
session_start();
} else {
// Optionally refresh the session cookie expiry to keep the user alive
$params = session_get_cookie_params();
if ($sessionLifetime > 0) {
setcookie(session_name(), session_id(), [
'expires' => time() + $sessionLifetime,
'path' => $params['path'] ?: '/',
'domain' => $params['domain'] ?? '',
'secure' => $secure,
'httponly' => true,
'samesite' => $params['samesite'] ?? 'Lax',
]);
}
}
// CSRF token
@@ -114,7 +146,7 @@ if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
// Autologin via persistent token
// Auto-login via persistent token
if (empty($_SESSION["authenticated"]) && !empty($_COOKIE['remember_me_token'])) {
$tokFile = USERS_DIR . 'persistent_tokens.json';
$tokens = [];
@@ -140,13 +172,75 @@ if (empty($_SESSION["authenticated"]) && !empty($_COOKIE['remember_me_token']))
}
}
// Share URL fallback
$adminConfigFile = USERS_DIR . 'adminConfig.json';
// sane defaults:
$cfgAuthBypass = false;
$cfgAuthHeader = 'X_REMOTE_USER';
if (file_exists($adminConfigFile)) {
$encrypted = file_get_contents($adminConfigFile);
$decrypted = decryptData($encrypted, $encryptionKey);
$adminCfg = json_decode($decrypted, true) ?: [];
$loginOpts = $adminCfg['loginOptions'] ?? [];
// proxy-only bypass flag
$cfgAuthBypass = ! empty($loginOpts['authBypass']);
// header name (e.g. “X-Remote-User” → HTTP_X_REMOTE_USER)
$hdr = trim($loginOpts['authHeaderName'] ?? '');
if ($hdr === '') {
$hdr = 'X-Remote-User';
}
// normalize to PHPs $_SERVER key format:
$cfgAuthHeader = 'HTTP_' . strtoupper(str_replace('-', '_', $hdr));
}
define('AUTH_BYPASS', $cfgAuthBypass);
define('AUTH_HEADER', $cfgAuthHeader);
// ─────────────────────────────────────────────────────────────────────────────
// PROXY-ONLY AUTOLOGIN now uses those constants:
if (AUTH_BYPASS) {
$hdrKey = AUTH_HEADER; // e.g. "HTTP_X_REMOTE_USER"
if (!empty($_SERVER[$hdrKey])) {
// regenerate once per session
if (empty($_SESSION['authenticated'])) {
session_regenerate_id(true);
}
$username = $_SERVER[$hdrKey];
$_SESSION['authenticated'] = true;
$_SESSION['username'] = $username;
// ◾ lookup actual role instead of forcing admin
require_once PROJECT_ROOT . '/src/models/AuthModel.php';
$role = AuthModel::getUserRole($username);
$_SESSION['isAdmin'] = ($role === '1');
// carry over any folder/read/upload perms
$perms = loadUserPermissions($username) ?: [];
$_SESSION['folderOnly'] = $perms['folderOnly'] ?? false;
$_SESSION['readOnly'] = $perms['readOnly'] ?? false;
$_SESSION['disableUpload'] = $perms['disableUpload'] ?? false;
}
}
// Share URL fallback (keep BASE_URL behavior)
define('BASE_URL', 'http://yourwebsite/uploads/');
// Detect scheme correctly (works behind proxies too)
$proto = $_SERVER['HTTP_X_FORWARDED_PROTO'] ?? (
(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http'
);
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
if (strpos(BASE_URL, 'yourwebsite') !== false) {
$defaultShare = isset($_SERVER['HTTP_HOST'])
? "http://{$_SERVER['HTTP_HOST']}/api/file/share.php"
: "http://localhost/api/file/share.php";
$defaultShare = "{$proto}://{$host}/api/file/share.php";
} else {
$defaultShare = rtrim(BASE_URL, '/') . "/api/file/share.php";
}
// Final: env var wins, else fallback
define('SHARE_URL', getenv('SHARE_URL') ?: $defaultShare);

43
docker-compose.yml Normal file
View File

@@ -0,0 +1,43 @@
---
version: "3.9"
services:
filerise:
# Use the published image (does NOT build in CI by default)
image: error311/filerise-docker:latest
container_name: filerise
restart: unless-stopped
# If someone wants to build locally instead, they can uncomment:
# build:
# context: .
# dockerfile: Dockerfile
ports:
- "${HOST_HTTP_PORT:-8080}:80"
# Uncomment if you really terminate TLS inside the container:
# - "${HOST_HTTPS_PORT:-8443}:443"
environment:
TIMEZONE: "${TIMEZONE:-UTC}"
DATE_TIME_FORMAT: "${DATE_TIME_FORMAT:-m/d/y h:iA}"
TOTAL_UPLOAD_SIZE: "${TOTAL_UPLOAD_SIZE:-5G}"
SECURE: "${SECURE:-false}"
PERSISTENT_TOKENS_KEY: "${PERSISTENT_TOKENS_KEY:-please_change_this_@@}"
PUID: "${PUID:-1000}"
PGID: "${PGID:-1000}"
CHOWN_ON_START: "${CHOWN_ON_START:-true}"
SCAN_ON_START: "${SCAN_ON_START:-true}"
SHARE_URL: "${SHARE_URL:-}"
volumes:
- ./data/uploads:/var/www/uploads
- ./data/users:/var/www/users
- ./data/metadata:/var/www/metadata
healthcheck:
test: ["CMD-SHELL", "curl -fsS http://localhost/ || exit 1"]
interval: 30s
timeout: 5s
retries: 3
start_period: 20s

View File

@@ -0,0 +1,5 @@
Google Fonts & Icons NOTICE
This product bundles font files from Google Fonts (Roboto, Material Icons, and/or Material Symbols).
Copyright 2012present Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (see ../apache-2.0.txt).

202
licenses/apache-2.0.txt Normal file
View File

@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

19
licenses/mit.txt Normal file
View File

@@ -0,0 +1,19 @@
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

File diff suppressed because it is too large Load Diff

View File

@@ -1,75 +1,76 @@
# -----------------------------
# 1) Prevent directory listings
# -----------------------------
# --------------------------------
# Base: safe in most environments
# --------------------------------
Options -Indexes
# -----------------------------
# Default index files
# -----------------------------
DirectoryIndex index.html
# -----------------------------
# Deny access to hidden files
# -----------------------------
<FilesMatch "^\.">
Require all denied
</FilesMatch>
<IfModule mod_authz_core.c>
<FilesMatch "^\.">
Require all denied
</FilesMatch>
</IfModule>
# -----------------------------
# Enforce HTTPS (optional)
# -----------------------------
RewriteEngine On
#RewriteCond %{HTTPS} off
#RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
<IfModule mod_headers.c>
# Allow requests from a specific origin
#Header set Access-Control-Allow-Origin "https://demo.filerise.net"
Header set Access-Control-Allow-Methods "GET, POST, OPTIONS"
Header set Access-Control-Allow-Headers "Content-Type, Authorization, X-Requested-With, X-CSRF-Token"
Header set Access-Control-Allow-Credentials "true"
# MIME types for fonts/SVG
<IfModule mod_mime.c>
AddType font/woff2 .woff2
AddType font/woff .woff
AddType image/svg+xml .svg
</IfModule>
# Security headers
<IfModule mod_headers.c>
# Prevent clickjacking
Header always set X-Frame-Options "SAMEORIGIN"
# Block XSS
Header always set X-XSS-Protection "1; mode=block"
# No MIME sniffing
Header always set X-Content-Type-Options "nosniff"
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
Header always set Referrer-Policy "strict-origin-when-cross-origin"
Header always set Permissions-Policy "geolocation=(), microphone=(), camera=()"
Header always set X-Download-Options "noopen"
Header always set Expect-CT "max-age=86400, enforce"
Header set Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self'; connect-src 'self'; media-src 'self' blob:; worker-src 'self' blob:; frame-ancestors 'self'; object-src 'none'; base-uri 'self'; form-action 'self'"
</IfModule>
# Caching
SetEnvIfNoCase QUERY_STRING "(^|&)v=" has_version_param=1
<IfModule mod_headers.c>
# HTML: always revalidate
<FilesMatch "\.(html|htm)$">
<FilesMatch "\.(html?|php)$">
Header set Cache-Control "no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires "0"
</FilesMatch>
# JS/CSS: shortterm cache, revalidate regularly
<FilesMatch "^js/version\.js$">
Header set Cache-Control "no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires "0"
</FilesMatch>
<FilesMatch "\.(js|css)$">
Header set Cache-Control "public, max-age=3600, must-revalidate"
Header set Cache-Control "public, max-age=3600, must-revalidate" env=!has_version_param
</FilesMatch>
<FilesMatch "\.(png|jpe?g|gif|webp|svg|ico|woff2?|ttf|otf)$">
Header set Cache-Control "public, max-age=604800" env=!has_version_param
</FilesMatch>
<FilesMatch "\.(js|css|png|jpe?g|gif|webp|svg|ico|woff2?|ttf|otf)$">
Header set Cache-Control "public, max-age=31536000, immutable" env=has_version_param
</FilesMatch>
</IfModule>
# -----------------------------
# Additional Security Headers
# -----------------------------
<IfModule mod_headers.c>
# Enforce HTTPS for a year with subdomains and preload option.
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
# Set a Referrer Policy.
Header always set Referrer-Policy "strict-origin-when-cross-origin"
# Permissions Policy: disable features you don't need.
Header always set Permissions-Policy "geolocation=(), microphone=(), camera=()"
# IE-specific header to prevent downloads from opening in IE.
Header always set X-Download-Options "noopen"
# Expect-CT header for Certificate Transparency (optional).
Header always set Expect-CT "max-age=86400, enforce"
# Compression (only if module exists)
<IfModule mod_brotli.c>
BrotliCompressionQuality 5
AddOutputFilterByType BROTLI_COMPRESS text/html text/css application/javascript application/json image/svg+xml
</IfModule>
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css application/javascript application/json image/svg+xml
</IfModule>
# -----------------------------
# Disable TRACE method
# -----------------------------
# Disable TRACE
RewriteCond %{REQUEST_METHOD} ^TRACE
RewriteRule .* - [F]

43
public/THIRD_PARTY.md Normal file
View File

@@ -0,0 +1,43 @@
# Third-Party Notices
FileRise bundles the following thirdparty assets. Each item lists the project, version, typical on-disk location in this repo, and its license.
If you believe any attribution is missing or incorrect, please open an issue.
---
## Fonts
- **Roboto (wght 400/500)** — Google Fonts
**License:** Apache License 2.0
**Files:** `public/css/vendor/roboto.css`, `public/fonts/roboto/*.woff2`
- **Material Icons (ligature font)** — Google Fonts
**License:** Apache License 2.0
**Files:** `public/css/vendor/material-icons.css`, `public/fonts/material-icons/*.woff2`
> Google fonts/icons © Google. Licensed under Apache 2.0. See `licenses/apache-2.0.txt`.
---
## CSS / JS Libraries (vendored)
- **Bootstrap 4.5.2** — MIT License
**Files:** `public/vendor/bootstrap/4.5.2/bootstrap.min.css`
- **CodeMirror 5.65.5** — MIT License
**Files:** `public/vendor/codemirror/5.65.5/*`
- **DOMPurify 2.4.0** — Apache License 2.0
**Files:** `public/vendor/dompurify/2.4.0/purify.min.js`
- **Fuse.js 6.6.2** — Apache License 2.0
**Files:** `public/vendor/fuse/6.6.2/fuse.min.js`
- **Resumable.js 1.1.0** — MIT License
**Files:** `public/vendor/resumable/1.1.0/resumable.min.js`
> MIT-licensed code: see `licenses/mit.txt`.
> Apache-2.0licensed code: see `licenses/apache-2.0.txt`.
---

View File

@@ -19,17 +19,13 @@ if (isset($_GET['spec'])) {
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>FileRise API Docs</title>
<script src="https://cdn.redoc.ly/redoc/latest/bundles/redoc.standalone.js"
integrity="sha384-4vOjrBu7SuDWXcAw1qFznVLA/sKL+0l4nn+J1HY8w7cpa6twQEYuh4b0Cwuo7CyX"
<script defer src="https://cdn.redoc.ly/redoc/latest/bundles/redoc.standalone.js"
integrity="sha384-70P5pmIdaQdVbxvjhrcTDv1uKcKqalZ3OHi7S2J+uzDl0PW8dO6L+pHOpm9EEjGJ"
crossorigin="anonymous"></script>
<script defer src="/js/redoc-init.js"></script>
</head>
<body>
<redoc spec-url="api.php?spec=1"></redoc>
<div id="redoc-container"></div>
<script>
if (!customElements.get('redoc')) {
Redoc.init('api.php?spec=1', {}, document.getElementById('redoc-container'));
}
</script>
</body>
</html>

View File

@@ -1,8 +1,42 @@
<?php
// public/api/addUser.php
/**
* @OA\Post(
* path="/api/addUser.php",
* summary="Add a new user",
* description="Adds a new user to the system. In setup mode, the new user is automatically made admin.",
* operationId="addUser",
* tags={"Users"},
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* required={"username", "password"},
* @OA\Property(property="username", type="string", example="johndoe"),
* @OA\Property(property="password", type="string", example="securepassword"),
* @OA\Property(property="isAdmin", type="boolean", example=true)
* )
* ),
* @OA\Response(
* response=200,
* description="User added successfully",
* @OA\JsonContent(
* @OA\Property(property="success", type="string", example="User added successfully")
* )
* ),
* @OA\Response(
* response=400,
* description="Bad Request"
* ),
* @OA\Response(
* response=401,
* description="Unauthorized"
* )
* )
*/
require_once __DIR__ . '/../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/userController.php';
require_once PROJECT_ROOT . '/src/controllers/UserController.php';
$userController = new UserController();
$userController->addUser();

View File

@@ -0,0 +1,85 @@
<?php
// public/api/admin/acl/getGrants.php
declare(strict_types=1);
require_once __DIR__ . '/../../../../config/config.php';
require_once PROJECT_ROOT . '/src/lib/ACL.php';
require_once PROJECT_ROOT . '/src/models/FolderModel.php';
if (session_status() !== PHP_SESSION_ACTIVE) session_start();
header('Content-Type: application/json');
if (empty($_SESSION['authenticated']) || empty($_SESSION['isAdmin'])) {
http_response_code(401); echo json_encode(['error'=>'Unauthorized']); exit;
}
$user = trim((string)($_GET['user'] ?? ''));
if ($user === '' || !preg_match(REGEX_USER, $user)) {
http_response_code(400); echo json_encode(['error'=>'Invalid user']); exit;
}
// Build the folder list (admin sees all)
$folders = [];
try {
$rows = FolderModel::getFolderList();
if (is_array($rows)) {
foreach ($rows as $r) {
$f = is_array($r) ? ($r['folder'] ?? '') : (string)$r;
if ($f !== '') $folders[$f] = true;
}
}
} catch (Throwable $e) { /* ignore */ }
if (empty($folders)) {
$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)) {
foreach ($data['folders'] as $name => $_) $folders[$name] = true;
}
}
}
$folderList = array_keys($folders);
if (!in_array('root', $folderList, true)) array_unshift($folderList, 'root');
$has = function(array $arr, string $u): bool {
foreach ($arr as $x) if (strcasecmp((string)$x, $u) === 0) return true;
return false;
};
$out = [];
foreach ($folderList as $f) {
$rec = ACL::explicitAll($f); // legacy + granular
$isOwner = $has($rec['owners'], $user);
$canViewAll = $isOwner || $has($rec['read'], $user);
$canViewOwn = $has($rec['read_own'], $user);
$canShare = $isOwner || $has($rec['share'], $user);
$canUpload = $isOwner || $has($rec['write'], $user) || $has($rec['upload'], $user);
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,
'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);

View File

@@ -0,0 +1,121 @@
<?php
// public/api/admin/acl/saveGrants.php
declare(strict_types=1);
require_once __DIR__ . '/../../../../config/config.php';
require_once PROJECT_ROOT . '/src/lib/ACL.php';
if (session_status() !== PHP_SESSION_ACTIVE) session_start();
header('Content-Type: application/json');
// ---- Auth + CSRF -----------------------------------------------------------
if (empty($_SESSION['authenticated']) || empty($_SESSION['isAdmin'])) {
http_response_code(401);
echo json_encode(['error' => 'Unauthorized']);
exit;
}
$headers = function_exists('getallheaders') ? array_change_key_case(getallheaders(), CASE_LOWER) : [];
$csrf = trim($headers['x-csrf-token'] ?? ($_POST['csrfToken'] ?? ''));
if (empty($_SESSION['csrf_token']) || $csrf !== $_SESSION['csrf_token']) {
http_response_code(403);
echo json_encode(['error' => 'Invalid CSRF token']);
exit;
}
// ---- Helpers ---------------------------------------------------------------
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 {
$out = [];
foreach ($grants as $folder => $caps) {
if (!is_string($folder)) $folder = (string)$folder;
if (!is_array($caps)) $caps = [];
$out[$folder] = normalize_caps($caps);
}
return $out;
}
function valid_user(string $u): bool {
return ($u !== '' && preg_match(REGEX_USER, $u));
}
// ---- Read JSON body --------------------------------------------------------
$raw = file_get_contents('php://input');
$in = json_decode((string)$raw, true);
if (!is_array($in)) {
http_response_code(400);
echo json_encode(['error' => 'Invalid JSON']);
exit;
}
// ---- Single user mode: { user, grants } ------------------------------------
if (isset($in['user']) && isset($in['grants']) && is_array($in['grants'])) {
$user = trim((string)$in['user']);
if (!valid_user($user)) {
http_response_code(400);
echo json_encode(['error' => 'Invalid user']);
exit;
}
$grants = sanitize_grants_map($in['grants']);
try {
$res = ACL::applyUserGrantsAtomic($user, $grants);
echo json_encode($res, JSON_UNESCAPED_SLASHES);
exit;
} catch (Throwable $e) {
http_response_code(500);
echo json_encode(['error' => 'Failed to save grants', 'detail' => $e->getMessage()]);
exit;
}
}
// ---- Batch mode: { changes: [ { user, grants }, ... ] } --------------------
if (isset($in['changes']) && is_array($in['changes'])) {
$updated = [];
foreach ($in['changes'] as $chg) {
if (!is_array($chg)) continue;
$user = trim((string)($chg['user'] ?? ''));
$gr = $chg['grants'] ?? null;
if (!valid_user($user) || !is_array($gr)) continue;
try {
$res = ACL::applyUserGrantsAtomic($user, sanitize_grants_map($gr));
$updated[$user] = $res['updated'] ?? [];
} catch (Throwable $e) {
$updated[$user] = ['error' => $e->getMessage()];
}
}
echo json_encode(['ok' => true, 'updated' => $updated], JSON_UNESCAPED_SLASHES);
exit;
}
// ---- Fallback --------------------------------------------------------------
http_response_code(400);
echo json_encode(['error' => 'Invalid payload: expected {user,grants} or {changes:[{user,grants}]}']);

View File

@@ -1,8 +1,32 @@
<?php
// public/api/admin/getConfig.php
/**
* @OA\Get(
* path="/api/admin/getConfig.php",
* tags={"Admin"},
* summary="Get UI configuration",
* description="Returns a public subset for everyone; authenticated admins receive additional loginOptions fields.",
* operationId="getAdminConfig",
* @OA\Response(
* response=200,
* description="Configuration loaded",
* @OA\JsonContent(
* oneOf={
* @OA\Schema(ref="#/components/schemas/AdminGetConfigPublic"),
* @OA\Schema(ref="#/components/schemas/AdminGetConfigAdmin")
* }
* )
* ),
* @OA\Response(response=500, description="Server error")
* )
*
* Retrieves the admin configuration settings and outputs JSON.
* @return void
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/adminController.php';
require_once PROJECT_ROOT . '/src/controllers/AdminController.php';
$adminController = new AdminController();
$adminController->getConfig();

View File

@@ -0,0 +1,92 @@
<?php
// public/api/admin/readMetadata.php
/**
* @OA\Get(
* path="/api/admin/readMetadata.php",
* summary="Read share metadata JSON",
* description="Admin-only: returns the cleaned metadata for file or folder share links.",
* tags={"Admin"},
* operationId="readMetadata",
* security={{"cookieAuth":{}}},
* @OA\Parameter(
* name="file",
* in="query",
* required=true,
* description="Which metadata file to read",
* @OA\Schema(type="string", enum={"share_links.json","share_folder_links.json"})
* ),
* @OA\Response(
* response=200,
* description="OK",
* @OA\JsonContent(oneOf={
* @OA\Schema(ref="#/components/schemas/ShareLinksMap"),
* @OA\Schema(ref="#/components/schemas/ShareFolderLinksMap")
* })
* ),
* @OA\Response(response=400, description="Missing or invalid file param"),
* @OA\Response(response=403, description="Forbidden (admin only)"),
* @OA\Response(response=500, description="Corrupted JSON")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
// Only admins may read these
if (empty($_SESSION['isAdmin']) || $_SESSION['isAdmin'] !== true) {
http_response_code(403);
echo json_encode(['error' => 'Forbidden']);
exit;
}
// Must supply ?file=share_links.json or share_folder_links.json
if (empty($_GET['file'])) {
http_response_code(400);
echo json_encode(['error' => 'Missing `file` parameter']);
exit;
}
$file = basename($_GET['file']);
$allowed = ['share_links.json', 'share_folder_links.json'];
if (!in_array($file, $allowed, true)) {
http_response_code(403);
echo json_encode(['error' => 'Invalid file requested']);
exit;
}
$path = META_DIR . $file;
if (!file_exists($path)) {
// Return empty object so JS sees `{}` not an error
http_response_code(200);
header('Content-Type: application/json');
echo json_encode((object)[]);
exit;
}
$jsonData = file_get_contents($path);
$data = json_decode($jsonData, true);
if (json_last_error() !== JSON_ERROR_NONE || !is_array($data)) {
http_response_code(500);
echo json_encode(['error' => 'Corrupted JSON']);
exit;
}
// ——— Clean up expired entries ———
$now = time();
$changed = false;
foreach ($data as $token => $entry) {
if (!empty($entry['expires']) && $entry['expires'] < $now) {
unset($data[$token]);
$changed = true;
}
}
if ($changed) {
// overwrite file with cleaned data
file_put_contents($path, json_encode($data, JSON_PRETTY_PRINT));
}
// ——— Send cleaned data back ———
http_response_code(200);
header('Content-Type: application/json');
echo json_encode($data);
exit;

View File

@@ -1,8 +1,47 @@
<?php
// public/api/admin/updateConfig.php
/**
* @OA\Put(
* path="/api/admin/updateConfig.php",
* summary="Update admin configuration",
* description="Merges the provided settings into the on-disk configuration and persists them. Requires an authenticated admin session and a valid CSRF token. When OIDC is enabled (disableOIDCLogin=false), `providerUrl`, `redirectUri`, and `clientId` are required and must be HTTPS (HTTP allowed only for localhost).",
* operationId="updateAdminConfig",
* tags={"Admin"},
* security={ {{"cookieAuth": {}, "CsrfHeader": {}}} },
*
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(ref="#/components/schemas/AdminUpdateConfigRequest")
* ),
*
* @OA\Response(
* response=200,
* description="Configuration updated",
* @OA\JsonContent(ref="#/components/schemas/SimpleSuccess")
* ),
* @OA\Response(
* response=400,
* description="Validation error (e.g., bad authHeaderName, missing OIDC fields when enabled, or negative upload limit)",
* @OA\JsonContent(ref="#/components/schemas/SimpleError")
* ),
* @OA\Response(
* response=403,
* description="Unauthorized access or invalid CSRF token",
* @OA\JsonContent(ref="#/components/schemas/SimpleError")
* // or: ref to the reusable response
* // ref="#/components/responses/Forbidden"
* ),
* @OA\Response(
* response=500,
* description="Server error while loading or saving configuration",
* @OA\JsonContent(ref="#/components/schemas/SimpleError")
* )
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/adminController.php';
require_once PROJECT_ROOT . '/src/controllers/AdminController.php';
$adminController = new AdminController();
$adminController->updateConfig();

View File

@@ -1,9 +1,55 @@
<?php
// public/api/auth/auth.php
/**
* @OA\Post(
* path="/api/auth/auth.php",
* summary="Authenticate user",
* description="Handles user authentication via OIDC or form-based credentials. For OIDC flows, processes callbacks; otherwise, performs standard authentication with optional TOTP verification.",
* operationId="authUser",
* tags={"Auth"},
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* required={"username", "password"},
* @OA\Property(property="username", type="string", example="johndoe"),
* @OA\Property(property="password", type="string", example="secretpassword"),
* @OA\Property(property="remember_me", type="boolean", example=true),
* @OA\Property(property="totp_code", type="string", example="123456")
* )
* ),
* @OA\Response(
* response=200,
* description="Login successful; returns user info and status",
* @OA\JsonContent(
* @OA\Property(property="status", type="string", example="ok"),
* @OA\Property(property="success", type="string", example="Login successful"),
* @OA\Property(property="username", type="string", example="johndoe"),
* @OA\Property(property="isAdmin", type="boolean", example=true)
* )
* ),
* @OA\Response(
* response=400,
* description="Bad Request (e.g., missing credentials)"
* ),
* @OA\Response(
* response=401,
* description="Unauthorized (e.g., invalid credentials, too many attempts)"
* ),
* @OA\Response(
* response=429,
* description="Too many failed login attempts"
* )
* )
*
* Handles user authentication via OIDC or form-based login.
*
* @return void Redirects on success or outputs JSON error.
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/vendor/autoload.php';
require_once PROJECT_ROOT . '/src/controllers/authController.php';
require_once PROJECT_ROOT . '/src/controllers/AuthController.php';
$authController = new AuthController();
$authController->auth();

View File

@@ -1,8 +1,37 @@
<?php
// public/api/auth/checkAuth.php
/**
* @OA\Get(
* path="/api/auth/checkAuth.php",
* summary="Check authentication status",
* operationId="checkAuth",
* tags={"Auth"},
* @OA\Response(
* response=200,
* description="Authenticated status or setup flag",
* @OA\JsonContent(
* oneOf={
* @OA\Schema(
* type="object",
* @OA\Property(property="authenticated", type="boolean", example=true),
* @OA\Property(property="isAdmin", type="boolean", example=true),
* @OA\Property(property="totp_enabled", type="boolean", example=false),
* @OA\Property(property="username", type="string", example="johndoe"),
* @OA\Property(property="folderOnly", type="boolean", example=false)
* ),
* @OA\Schema(
* type="object",
* @OA\Property(property="setup", type="boolean", example=true)
* )
* }
* )
* )
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/authController.php';
require_once PROJECT_ROOT . '/src/controllers/AuthController.php';
$authController = new AuthController();
$authController->checkAuth();

View File

@@ -1,8 +1,34 @@
<?php
// public/api/auth/login_basic.php
/**
* @OA\Get(
* path="/api/auth/login_basic.php",
* summary="Authenticate using HTTP Basic Authentication",
* description="Performs HTTP Basic authentication. If credentials are missing, sends a 401 response prompting for Basic auth. On valid credentials, optionally handles TOTP verification and finalizes session login.",
* operationId="loginBasic",
* tags={"Auth"},
* @OA\Response(
* response=200,
* description="Login successful; redirects to index.html",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="success", type="string", example="Login successful")
* )
* ),
* @OA\Response(
* response=401,
* description="Unauthorized due to missing credentials or invalid credentials."
* )
* )
*
* Handles HTTP Basic authentication (with optional TOTP) and logs the user in.
*
* @return void Redirects on success or sends a 401 header.
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/authController.php';
require_once PROJECT_ROOT . '/src/controllers/AuthController.php';
$authController = new AuthController();
$authController->loginBasic();

View File

@@ -1,8 +1,30 @@
<?php
// public/api/auth/logout.php
/**
* @OA\Post(
* path="/api/auth/logout.php",
* summary="Logout user",
* description="Clears the session, removes persistent login tokens, and redirects the user to the login page.",
* operationId="logoutUser",
* tags={"Auth"},
* @OA\Response(
* response=302,
* description="Redirects to the login page with a logout flag."
* ),
* @OA\Response(
* response=401,
* description="Unauthorized"
* )
* )
*
* Logs the user out by clearing session data, removing persistent tokens, and destroying the session.
*
* @return void Redirects to index.html with a logout flag.
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/authController.php';
require_once PROJECT_ROOT . '/src/controllers/AuthController.php';
$authController = new AuthController();
$authController->logout();

View File

@@ -1,8 +1,31 @@
<?php
// public/api/auth/token.php
/**
* @OA\Get(
* path="/api/auth/token.php",
* summary="Retrieve CSRF token and share URL",
* description="Returns the current CSRF token along with the configured share URL.",
* operationId="getToken",
* tags={"Auth"},
* @OA\Response(
* response=200,
* description="CSRF token and share URL",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="csrf_token", type="string", example="0123456789abcdef..."),
* @OA\Property(property="share_url", type="string", example="https://yourdomain.com/share.php")
* )
* )
* )
*
* Returns the CSRF token and share URL.
*
* @return void Outputs the JSON response.
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/authController.php';
require_once PROJECT_ROOT . '/src/controllers/AuthController.php';
$authController = new AuthController();
$authController->getToken();

View File

@@ -1,8 +1,46 @@
<?php
// public/api/changePassword.php
/**
* @OA\Post(
* path="/api/changePassword.php",
* summary="Change user password",
* description="Allows an authenticated user to change their password by verifying the old password and updating to a new one.",
* operationId="changePassword",
* tags={"Users"},
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* required={"oldPassword", "newPassword", "confirmPassword"},
* @OA\Property(property="oldPassword", type="string", example="oldpass123"),
* @OA\Property(property="newPassword", type="string", example="newpass456"),
* @OA\Property(property="confirmPassword", type="string", example="newpass456")
* )
* ),
* @OA\Response(
* response=200,
* description="Password updated successfully",
* @OA\JsonContent(
* @OA\Property(property="success", type="string", example="Password updated successfully.")
* )
* ),
* @OA\Response(
* response=400,
* description="Bad Request"
* ),
* @OA\Response(
* response=401,
* description="Unauthorized"
* ),
* @OA\Response(
* response=403,
* description="Invalid CSRF token"
* )
* )
*/
require_once __DIR__ . '/../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/userController.php';
require_once PROJECT_ROOT . '/src/controllers/UserController.php';
$userController = new UserController();
$userController->changePassword();

View File

@@ -1,8 +1,38 @@
<?php
// public/api/file/copyFiles.php
/**
* @OA\Post(
* path="/api/file/copyFiles.php",
* summary="Copy files between folders",
* description="Requires read access on source and write access on destination. Enforces folder scope and ownership.",
* operationId="copyFiles",
* tags={"Files"},
* security={{"cookieAuth": {}}},
* @OA\Parameter(
* name="X-CSRF-Token", in="header", required=true,
* description="CSRF token from the current session",
* @OA\Schema(type="string")
* ),
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* required={"source","destination","files"},
* @OA\Property(property="source", type="string", example="root"),
* @OA\Property(property="destination", type="string", example="userA/projects"),
* @OA\Property(property="files", type="array", @OA\Items(type="string"), example={"report.pdf","notes.txt"})
* )
* ),
* @OA\Response(response=200, description="Copy result (model-defined)"),
* @OA\Response(response=400, description="Invalid request or folder name"),
* @OA\Response(response=401, description="Unauthorized"),
* @OA\Response(response=403, description="Forbidden"),
* @OA\Response(response=500, description="Internal error")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/fileController.php';
require_once PROJECT_ROOT . '/src/controllers/FileController.php';
$fileController = new FileController();
$fileController->copyFiles();

View File

@@ -0,0 +1,39 @@
<?php
// public/api/file/createFile.php
/**
* @OA\Post(
* path="/api/file/createFile.php",
* summary="Create an empty file",
* description="Requires write access on the target folder. Enforces folder-only scope.",
* operationId="createFile",
* tags={"Files"},
* security={{"cookieAuth": {}}},
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* required={"folder","name"},
* @OA\Property(property="folder", type="string", example="root"),
* @OA\Property(property="name", type="string", example="new.txt")
* )
* ),
* @OA\Response(response=200, description="Creation result (model-defined)"),
* @OA\Response(response=400, description="Invalid input"),
* @OA\Response(response=401, description="Unauthorized"),
* @OA\Response(response=403, description="Forbidden"),
* @OA\Response(response=500, description="Internal error")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/FileController.php';
header('Content-Type: application/json');
if (empty($_SESSION['authenticated'])) {
http_response_code(401);
echo json_encode(['success'=>false,'error'=>'Unauthorized']);
exit;
}
$fc = new FileController();
$fc->createFile();

View File

@@ -1,8 +1,44 @@
<?php
// public/api/file/createShareLink.php
/**
* @OA\Post(
* path="/api/file/createShareLink.php",
* summary="Create a share link for a file",
* description="Requires share permission on the folder. Non-admins must own the file unless bypassOwnership.",
* operationId="createShareLink",
* tags={"Shares"},
* security={{"cookieAuth": {}}},
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* required={"folder","file"},
* @OA\Property(property="folder", type="string", example="root"),
* @OA\Property(property="file", type="string", example="invoice.pdf"),
* @OA\Property(property="expirationValue", type="integer", example=60),
* @OA\Property(property="expirationUnit", type="string", enum={"seconds","minutes","hours","days"}, example="minutes"),
* @OA\Property(property="password", type="string", example="")
* )
* ),
* @OA\Response(
* response=200,
* description="Share link created",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="token", type="string", example="abc123"),
* @OA\Property(property="url", type="string", example="/api/file/share.php?token=abc123"),
* @OA\Property(property="expires", type="integer", example=1700000000)
* )
* ),
* @OA\Response(response=400, description="Invalid input"),
* @OA\Response(response=401, description="Unauthorized"),
* @OA\Response(response=403, description="Forbidden"),
* @OA\Response(response=500, description="Internal error")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/fileController.php';
require_once PROJECT_ROOT . '/src/controllers/FileController.php';
$fileController = new FileController();
$fileController->createShareLink();

View File

@@ -1,8 +1,36 @@
<?php
// public/api/file/deleteFiles.php
/**
* @OA\Post(
* path="/api/file/deleteFiles.php",
* summary="Delete files to Trash",
* description="Requires write access on the folder and (for non-admins) ownership of the files.",
* operationId="deleteFiles",
* tags={"Files"},
* security={{"cookieAuth": {}}},
* @OA\Parameter(
* name="X-CSRF-Token", in="header", required=true,
* @OA\Schema(type="string")
* ),
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* required={"folder","files"},
* @OA\Property(property="folder", type="string", example="root"),
* @OA\Property(property="files", type="array", @OA\Items(type="string"), example={"old.docx","draft.md"})
* )
* ),
* @OA\Response(response=200, description="Delete result (model-defined)"),
* @OA\Response(response=400, description="Invalid input"),
* @OA\Response(response=401, description="Unauthorized"),
* @OA\Response(response=403, description="Forbidden"),
* @OA\Response(response=500, description="Internal error")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/fileController.php';
require_once PROJECT_ROOT . '/src/controllers/FileController.php';
$fileController = new FileController();
$fileController->deleteFiles();

View File

@@ -0,0 +1,27 @@
<?php
/**
* @OA\Post(
* path="/api/file/deleteShareLink.php",
* summary="Delete a share link by token",
* description="Deletes a share token. NOTE: Current implementation does not require authentication.",
* operationId="deleteShareLink",
* tags={"Shares"},
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* required={"token"},
* @OA\Property(property="token", type="string", example="abc123")
* )
* ),
* @OA\Response(response=200, description="Deletion result (success or not found)")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/FileController.php';
$fileController = new FileController();
$fileController->deleteShareLink();

View File

@@ -1,8 +1,38 @@
<?php
// public/api/file/deleteTrashFiles.php
/**
* @OA\Post(
* path="/api/file/deleteTrashFiles.php",
* summary="Permanently delete Trash items (admin only)",
* operationId="deleteTrashFiles",
* tags={"Trash"},
* security={{"cookieAuth": {}}},
* @OA\Parameter(name="X-CSRF-Token", in="header", required=true, @OA\Schema(type="string")),
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* oneOf={
* @OA\Schema(
* required={"deleteAll"},
* @OA\Property(property="deleteAll", type="boolean", example=true)
* ),
* @OA\Schema(
* required={"files"},
* @OA\Property(property="files", type="array", @OA\Items(type="string"), example={"trash/abc","trash/def"})
* )
* }
* )
* ),
* @OA\Response(response=200, description="Deletion result (model-defined)"),
* @OA\Response(response=401, description="Unauthorized"),
* @OA\Response(response=403, description="Admin only"),
* @OA\Response(response=500, description="Internal error")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/fileController.php';
require_once PROJECT_ROOT . '/src/controllers/FileController.php';
$fileController = new FileController();
$fileController->deleteTrashFiles();

View File

@@ -1,8 +1,36 @@
<?php
// public/api/file/download.php
/**
* @OA\Get(
* path="/api/file/download.php",
* summary="Download a file",
* description="Requires view access (or own-only with ownership). Streams the file with appropriate Content-Type.",
* operationId="downloadFile",
* tags={"Files"},
* security={{"cookieAuth": {}}},
* @OA\Parameter(name="folder", in="query", required=true, @OA\Schema(type="string"), example="root"),
* @OA\Parameter(name="file", in="query", required=true, @OA\Schema(type="string"), example="photo.jpg"),
* @OA\Response(
* response=200,
* description="Binary file",
* content={
* "application/octet-stream": @OA\MediaType(
* mediaType="application/octet-stream",
* @OA\Schema(type="string", format="binary")
* )
* }
* ),
* @OA\Response(response=400, description="Invalid folder/file"),
* @OA\Response(response=401, description="Unauthorized"),
* @OA\Response(response=403, description="Forbidden"),
* @OA\Response(response=404, description="Not found")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/fileController.php';
require_once PROJECT_ROOT . '/src/controllers/FileController.php';
$fileController = new FileController();
$fileController->downloadFile();

View File

@@ -1,8 +1,43 @@
<?php
// public/api/file/downloadZip.php
/**
* @OA\Post(
* path="/api/file/downloadZip.php",
* summary="Download multiple files as a ZIP",
* description="Requires view access (or own-only with ownership). May be gated by account flag.",
* operationId="downloadZip",
* tags={"Files"},
* security={{"cookieAuth": {}}},
* @OA\Parameter(name="X-CSRF-Token", in="header", required=true, @OA\Schema(type="string")),
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* required={"folder","files"},
* @OA\Property(property="folder", type="string", example="root"),
* @OA\Property(property="files", type="array", @OA\Items(type="string"), example={"a.jpg","b.png"})
* )
* ),
* @OA\Response(
* response=200,
* description="ZIP archive",
* content={
* "application/zip": @OA\MediaType(
* mediaType="application/zip",
* @OA\Schema(type="string", format="binary")
* )
* }
* ),
* @OA\Response(response=400, description="Invalid input"),
* @OA\Response(response=401, description="Unauthorized"),
* @OA\Response(response=403, description="Forbidden"),
* @OA\Response(response=500, description="Internal error")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/fileController.php';
require_once PROJECT_ROOT . '/src/controllers/FileController.php';
$fileController = new FileController();
$fileController->downloadZip();

View File

@@ -1,8 +1,33 @@
<?php
// public/api/file/extractZip.php
/**
* @OA\Post(
* path="/api/file/extractZip.php",
* summary="Extract ZIP file(s) into a folder",
* description="Requires write access on the target folder.",
* operationId="extractZip",
* tags={"Files"},
* security={{"cookieAuth": {}}},
* @OA\Parameter(name="X-CSRF-Token", in="header", required=true, @OA\Schema(type="string")),
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* required={"folder","files"},
* @OA\Property(property="folder", type="string", example="root"),
* @OA\Property(property="files", type="array", @OA\Items(type="string"), example={"archive.zip"})
* )
* ),
* @OA\Response(response=200, description="Extraction result (model-defined)"),
* @OA\Response(response=400, description="Invalid input"),
* @OA\Response(response=401, description="Unauthorized"),
* @OA\Response(response=403, description="Forbidden"),
* @OA\Response(response=500, description="Internal error")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/fileController.php';
require_once PROJECT_ROOT . '/src/controllers/FileController.php';
$fileController = new FileController();
$fileController->extractZip();

View File

@@ -1,8 +1,25 @@
<?php
// public/api/file/getFileList.php
/**
* @OA\Get(
* path="/api/file/getFileList.php",
* summary="List files in a folder",
* description="Requires view access (full) or read_own (own-only results).",
* operationId="getFileList",
* tags={"Files"},
* security={{"cookieAuth": {}}},
* @OA\Parameter(name="folder", in="query", required=true, @OA\Schema(type="string"), example="root"),
* @OA\Response(response=200, description="Listing result (model-defined JSON)"),
* @OA\Response(response=400, description="Invalid folder"),
* @OA\Response(response=401, description="Unauthorized"),
* @OA\Response(response=403, description="Forbidden"),
* @OA\Response(response=500, description="Internal error")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/fileController.php';
require_once PROJECT_ROOT . '/src/controllers/FileController.php';
$fileController = new FileController();
$fileController->getFileList();

View File

@@ -1,8 +1,19 @@
<?php
// public/api/file/getFileTag.php
/**
* @OA\Get(
* path="/api/file/getFileTags.php",
* summary="Get global file tags",
* description="Returns tag metadata (no auth in current implementation).",
* operationId="getFileTags",
* tags={"Tags"},
* @OA\Response(response=200, description="Tags map (model-defined JSON)")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/fileController.php';
require_once PROJECT_ROOT . '/src/controllers/FileController.php';
$fileController = new FileController();
$fileController->getFileTags();

View File

@@ -0,0 +1,19 @@
<?php
/**
* @OA\Get(
* path="/api/file/getShareLinks.php",
* summary="Get (raw) share links file",
* description="Returns the full share links JSON (no auth in current implementation).",
* operationId="getShareLinks",
* tags={"Shares"},
* @OA\Response(response=200, description="Share links (model-defined JSON)")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/FileController.php';
$fileController = new FileController();
$fileController->getShareLinks();

View File

@@ -1,8 +1,22 @@
<?php
// public/api/file/getTrashItems.php
/**
* @OA\Get(
* path="/api/file/getTrashItems.php",
* summary="List items in Trash (admin only)",
* operationId="getTrashItems",
* tags={"Trash"},
* security={{"cookieAuth": {}}},
* @OA\Response(response=200, description="Trash contents (model-defined JSON)"),
* @OA\Response(response=401, description="Unauthorized"),
* @OA\Response(response=403, description="Admin only"),
* @OA\Response(response=500, description="Internal error")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/fileController.php';
require_once PROJECT_ROOT . '/src/controllers/FileController.php';
$fileController = new FileController();
$fileController->getTrashItems();

View File

@@ -1,8 +1,22 @@
<?php
// public/api/file/moveFiles.php
/**
* @OA\Post(
* path="/api/file/moveFiles.php",
* operationId="moveFiles",
* tags={"Files"},
* security={{"cookieAuth":{}}},
* @OA\RequestBody(ref="#/components/requestBodies/MoveFilesRequest"),
* @OA\Response(response=200, description="Moved"),
* @OA\Response(response=400, description="Bad Request"),
* @OA\Response(response=401, ref="#/components/responses/Unauthorized"),
* @OA\Response(response=403, ref="#/components/responses/Forbidden")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/fileController.php';
require_once PROJECT_ROOT . '/src/controllers/FileController.php';
$fileController = new FileController();
$fileController->moveFiles();

View File

@@ -1,8 +1,34 @@
<?php
// public/api/file/renameFile.php
/**
* @OA\Put(
* path="/api/file/renameFile.php",
* summary="Rename a file",
* description="Requires write access; non-admins must own the file.",
* operationId="renameFile",
* tags={"Files"},
* security={{"cookieAuth": {}}},
* @OA\Parameter(name="X-CSRF-Token", in="header", required=true, @OA\Schema(type="string")),
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* required={"folder","oldName","newName"},
* @OA\Property(property="folder", type="string", example="root"),
* @OA\Property(property="oldName", type="string", example="old.pdf"),
* @OA\Property(property="newName", type="string", example="new.pdf")
* )
* ),
* @OA\Response(response=200, description="Rename result (model-defined)"),
* @OA\Response(response=400, description="Invalid input"),
* @OA\Response(response=401, description="Unauthorized"),
* @OA\Response(response=403, description="Forbidden"),
* @OA\Response(response=500, description="Internal error")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/fileController.php';
require_once PROJECT_ROOT . '/src/controllers/FileController.php';
$fileController = new FileController();
$fileController->renameFile();

View File

@@ -1,8 +1,30 @@
<?php
// public/api/file/restoreFiles.php
/**
* @OA\Post(
* path="/api/file/restoreFiles.php",
* summary="Restore files from Trash (admin only)",
* operationId="restoreFiles",
* tags={"Trash"},
* security={{"cookieAuth": {}}},
* @OA\Parameter(name="X-CSRF-Token", in="header", required=true, @OA\Schema(type="string")),
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* required={"files"},
* @OA\Property(property="files", type="array", @OA\Items(type="string"), example={"trash/12345.json"})
* )
* ),
* @OA\Response(response=200, description="Restore result (model-defined)"),
* @OA\Response(response=401, description="Unauthorized"),
* @OA\Response(response=403, description="Admin only"),
* @OA\Response(response=500, description="Internal error")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/fileController.php';
require_once PROJECT_ROOT . '/src/controllers/FileController.php';
$fileController = new FileController();
$fileController->restoreFiles();

View File

@@ -1,8 +1,34 @@
<?php
// public/api/file/saveFile.php
/**
* @OA\Put(
* path="/api/file/saveFile.php",
* summary="Create or overwrite a files content",
* description="Requires write access. Overwrite enforces ownership for non-admins. Certain executable extensions are denied.",
* operationId="saveFile",
* tags={"Files"},
* security={{"cookieAuth": {}}},
* @OA\Parameter(name="X-CSRF-Token", in="header", required=true, @OA\Schema(type="string")),
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* required={"folder","fileName","content"},
* @OA\Property(property="folder", type="string", example="root"),
* @OA\Property(property="fileName", type="string", example="readme.txt"),
* @OA\Property(property="content", type="string", example="Hello world")
* )
* ),
* @OA\Response(response=200, description="Save result (model-defined)"),
* @OA\Response(response=400, description="Invalid input or disallowed extension"),
* @OA\Response(response=401, description="Unauthorized"),
* @OA\Response(response=403, description="Forbidden"),
* @OA\Response(response=500, description="Internal error")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/fileController.php';
require_once PROJECT_ROOT . '/src/controllers/FileController.php';
$fileController = new FileController();
$fileController->saveFile();

View File

@@ -1,8 +1,36 @@
<?php
// public/api/file/saveFileTag.php
/**
* @OA\Post(
* path="/api/file/saveFileTag.php",
* summary="Save tags for a file (or delete one)",
* description="Requires write access and (for non-admins) ownership when modifying.",
* operationId="saveFileTag",
* tags={"Tags"},
* security={{"cookieAuth": {}}},
* @OA\Parameter(name="X-CSRF-Token", in="header", required=true, @OA\Schema(type="string")),
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* required={"folder","file"},
* @OA\Property(property="folder", type="string", example="root"),
* @OA\Property(property="file", type="string", example="doc.md"),
* @OA\Property(property="tags", type="array", @OA\Items(type="string"), example={"work","urgent"}),
* @OA\Property(property="deleteGlobal", type="boolean", example=false),
* @OA\Property(property="tagToDelete", type="string", nullable=true, example=null)
* )
* ),
* @OA\Response(response=200, description="Save result (model-defined)"),
* @OA\Response(response=400, description="Invalid input"),
* @OA\Response(response=401, description="Unauthorized"),
* @OA\Response(response=403, description="Forbidden"),
* @OA\Response(response=500, description="Internal error")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/fileController.php';
require_once PROJECT_ROOT . '/src/controllers/FileController.php';
$fileController = new FileController();
$fileController->saveFileTag();

View File

@@ -1,8 +1,34 @@
<?php
// public/api/file/share.php
/**
* @OA\Get(
* path="/api/file/share.php",
* summary="Open a shared file by token",
* description="If the link is password-protected and no password is supplied, an HTML password form is returned. Otherwise the file is streamed.",
* operationId="shareFile",
* tags={"Shares"},
* @OA\Parameter(name="token", in="query", required=true, @OA\Schema(type="string")),
* @OA\Parameter(name="pass", in="query", required=false, @OA\Schema(type="string")),
* @OA\Response(
* response=200,
* description="Binary file (or HTML password form when missing password)",
* content={
* "application/octet-stream": @OA\MediaType(
* mediaType="application/octet-stream",
* @OA\Schema(type="string", format="binary")
* ),
* "text/html": @OA\MediaType(mediaType="text/html")
* }
* ),
* @OA\Response(response=400, description="Missing token / invalid input"),
* @OA\Response(response=403, description="Expired or invalid password"),
* @OA\Response(response=404, description="Not found")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/fileController.php';
require_once PROJECT_ROOT . '/src/controllers/FileController.php';
$fileController = new FileController();
$fileController->shareFile();

View File

@@ -1,2 +0,0 @@
cd /var/www/public
ln -s ../uploads uploads

View File

@@ -0,0 +1,245 @@
<?php
// public/api/folder/capabilities.php
/**
* @OA\Get(
* path="/api/folder/capabilities.php",
* summary="Get effective capabilities for the current user in a folder",
* description="Computes the caller's capabilities for a given folder by combining account flags (readOnly/disableUpload), ACL grants (read/write/share), and the user-folder-only scope. Returns booleans indicating what the user can do.",
* operationId="getFolderCapabilities",
* tags={"Folders"},
* security={{"cookieAuth": {}}},
*
* @OA\Parameter(
* name="folder",
* in="query",
* required=false,
* description="Target folder path. Defaults to 'root'. Supports nested paths like 'team/reports'.",
* @OA\Schema(type="string"),
* example="projects/acme"
* ),
*
* @OA\Response(
* response=200,
* description="Capabilities computed successfully.",
* @OA\JsonContent(
* type="object",
* required={"user","folder","isAdmin","flags","canView","canUpload","canCreate","canRename","canDelete","canMoveIn","canShare"},
* @OA\Property(property="user", type="string", example="alice"),
* @OA\Property(property="folder", type="string", example="projects/acme"),
* @OA\Property(property="isAdmin", type="boolean", example=false),
* @OA\Property(
* property="flags",
* type="object",
* required={"folderOnly","readOnly","disableUpload"},
* @OA\Property(property="folderOnly", type="boolean", example=false),
* @OA\Property(property="readOnly", type="boolean", example=false),
* @OA\Property(property="disableUpload", type="boolean", example=false)
* ),
* @OA\Property(property="owner", type="string", nullable=true, example="alice"),
* @OA\Property(property="canView", type="boolean", example=true, description="User can view items in this folder."),
* @OA\Property(property="canUpload", type="boolean", example=true, description="User can upload/edit/rename/move/delete items (i.e., WRITE)."),
* @OA\Property(property="canCreate", type="boolean", example=true, description="User can create subfolders here."),
* @OA\Property(property="canRename", type="boolean", example=true, description="User can rename items here."),
* @OA\Property(property="canDelete", type="boolean", example=true, description="User can delete items here."),
* @OA\Property(property="canMoveIn", type="boolean", example=true, description="User can move items into this folder."),
* @OA\Property(property="canShare", type="boolean", example=false, description="User can create share links for this folder.")
* )
* ),
* @OA\Response(response=400, description="Invalid folder name."),
* @OA\Response(response=401, ref="#/components/responses/Unauthorized")
* )
*/
declare(strict_types=1);
if (session_status() !== PHP_SESSION_ACTIVE) session_start();
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/lib/ACL.php';
require_once PROJECT_ROOT . '/src/models/UserModel.php';
require_once PROJECT_ROOT . '/src/models/FolderModel.php';
header('Content-Type: application/json');
// --- auth ---
$username = $_SESSION['username'] ?? '';
if ($username === '') {
http_response_code(401);
echo json_encode(['error' => 'Unauthorized']);
exit;
}
// --- helpers ---
function loadPermsFor(string $u): array {
try {
if (function_exists('loadUserPermissions')) {
$p = loadUserPermissions($u);
return is_array($p) ? $p : [];
}
if (class_exists('userModel') && method_exists('userModel', 'getUserPermissions')) {
$all = userModel::getUserPermissions();
if (is_array($all)) {
if (isset($all[$u])) return (array)$all[$u];
$lk = strtolower($u);
if (isset($all[$lk])) return (array)$all[$lk];
}
}
} catch (Throwable $e) {}
return [];
}
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 = 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
if ($folder !== 'root') {
$parts = array_filter(explode('/', trim($folder, "/\\ ")));
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;
}
}
$folder = implode('/', $parts);
}
// --- user + flags ---
$perms = loadPermsFor($username);
$isAdmin = ACL::isAdmin($perms);
$readOnly = !empty($perms['readOnly']);
$inScope = inUserFolderScope($folder, $username, $perms, $isAdmin);
// --- 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);
$canManageBase = $isAdmin || ACL::canManage($username, $perms, $folder);
// 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);
// --- Apply scope + flags to effective UI actions ---
$canView = $canViewBase && $inScope; // keep scope for folder-only
$canUpload = $gUploadBase && !$readOnly && $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;
$canMoveAlias = $canMoveIn;
$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;
$canMoveFolder = false;
}
if (!$isRoot) {
$canMoveFolder = (ACL::canManage($username, $perms, $folder) || ACL::isOwner($username, $perms, $folder))
&& !$readOnly;
}
$owner = null;
try { $owner = FolderModel::getOwnerFor($folder); } catch (Throwable $e) {}
echo json_encode([
'user' => $username,
'folder' => $folder,
'isAdmin' => $isAdmin,
'flags' => [
//'folderOnly' => !empty($perms['folderOnly']) || !empty($perms['userFolderOnly']) || !empty($perms['UserFolderOnly']),
'readOnly' => $readOnly,
],
'owner' => $owner,
// viewing
'canView' => $canView,
'canViewOwn' => $canViewOwn,
// write-ish
'canUpload' => $canUpload,
'canCreate' => $canCreate,
'canRename' => $canRename,
'canDelete' => $canDelete,
'canMoveIn' => $canMoveIn,
'canMove' => $canMoveAlias,
'canMoveFolder'=> $canMoveFolder,
'canEdit' => $canEdit,
'canCopy' => $canCopy,
'canExtract' => $canExtract,
// sharing
'canShare' => $canShare, // legacy
'canShareFile' => $canShareFileEff,
'canShareFolder' => $canShareFoldEff,
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

View File

@@ -1,8 +1,38 @@
<?php
// public/api/folder/createFolder.php
/**
* @OA\Post(
* path="/api/folder/createFolder.php",
* summary="Create a new folder",
* description="Requires authentication, CSRF token, and write access to the parent folder. Seeds ACL owner.",
* operationId="createFolder",
* tags={"Folders"},
* security={{"cookieAuth": {}}},
* @OA\Parameter(
* name="X-CSRF-Token", in="header", required=true,
* description="CSRF token from the current session",
* @OA\Schema(type="string")
* ),
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* required={"folderName"},
* @OA\Property(property="folderName", type="string", example="reports"),
* @OA\Property(property="parent", type="string", nullable=true, example="root",
* description="Parent folder (default root)")
* )
* ),
* @OA\Response(response=200, description="Creation result (model-defined JSON)"),
* @OA\Response(response=400, description="Invalid input"),
* @OA\Response(response=401, description="Unauthorized"),
* @OA\Response(response=403, description="Forbidden"),
* @OA\Response(response=405, description="Method not allowed")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/folderController.php';
require_once PROJECT_ROOT . '/src/controllers/FolderController.php';
$folderController = new FolderController();
$folderController->createFolder();

View File

@@ -1,8 +1,44 @@
<?php
// public/api/folder/createShareFolderLink.php
/**
* @OA\Post(
* path="/api/folder/createShareFolderLink.php",
* summary="Create a share link for a folder",
* description="Requires authentication, CSRF token, and share permission. Non-admins must own the folder (unless bypass) and cannot share root.",
* operationId="createShareFolderLink",
* tags={"Shared Folders"},
* security={{"cookieAuth": {}}},
* @OA\Parameter(name="X-CSRF-Token", in="header", required=true, @OA\Schema(type="string")),
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* required={"folder"},
* @OA\Property(property="folder", type="string", example="team/reports"),
* @OA\Property(property="expirationValue", type="integer", example=60),
* @OA\Property(property="expirationUnit", type="string", enum={"seconds","minutes","hours","days"}, example="minutes"),
* @OA\Property(property="password", type="string", example=""),
* @OA\Property(property="allowUpload", type="integer", enum={0,1}, example=0)
* )
* ),
* @OA\Response(
* response=200,
* description="Share folder link created",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="token", type="string", example="sf_abc123"),
* @OA\Property(property="url", type="string", example="/api/folder/shareFolder.php?token=sf_abc123"),
* @OA\Property(property="expires", type="integer", example=1700000000)
* )
* ),
* @OA\Response(response=400, description="Invalid input"),
* @OA\Response(response=401, description="Unauthorized"),
* @OA\Response(response=403, description="Forbidden")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/folderController.php';
require_once PROJECT_ROOT . '/src/controllers/FolderController.php';
$folderController = new FolderController();
$folderController->createShareFolderLink();

View File

@@ -1,8 +1,32 @@
<?php
// public/api/folder/deleteFolder.php
/**
* @OA\Post(
* path="/api/folder/deleteFolder.php",
* summary="Delete a folder",
* description="Requires authentication, CSRF token, write scope, and (for non-admins) folder ownership.",
* operationId="deleteFolder",
* tags={"Folders"},
* security={{"cookieAuth": {}}},
* @OA\Parameter(name="X-CSRF-Token", in="header", required=true, @OA\Schema(type="string")),
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* required={"folder"},
* @OA\Property(property="folder", type="string", example="userA/reports")
* )
* ),
* @OA\Response(response=200, description="Deletion result (model-defined JSON)"),
* @OA\Response(response=400, description="Invalid input"),
* @OA\Response(response=401, description="Unauthorized"),
* @OA\Response(response=403, description="Forbidden"),
* @OA\Response(response=405, description="Method not allowed")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/folderController.php';
require_once PROJECT_ROOT . '/src/controllers/FolderController.php';
$folderController = new FolderController();
$folderController->deleteFolder();

View File

@@ -0,0 +1,30 @@
<?php
/**
* @OA\Post(
* path="/api/folder/deleteShareFolderLink.php",
* summary="Delete a shared-folder link by token (admin only)",
* description="Requires authentication, CSRF token, and admin privileges.",
* operationId="deleteShareFolderLink",
* tags={"Shared Folders","Admin"},
* security={{"cookieAuth": {}}},
* @OA\Parameter(name="X-CSRF-Token", in="header", required=true, @OA\Schema(type="string")),
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* required={"token"},
* @OA\Property(property="token", type="string", example="sf_abc123")
* )
* ),
* @OA\Response(response=200, description="Deleted"),
* @OA\Response(response=400, description="No token provided"),
* @OA\Response(response=401, description="Unauthorized"),
* @OA\Response(response=403, description="Admin only"),
* @OA\Response(response=404, description="Not found")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/FolderController.php';
$folderController = new FolderController();
$folderController->deleteShareFolderLink();

View File

@@ -1,8 +1,32 @@
<?php
// public/api/folder/downloadSharedFile.php
/**
* @OA\Get(
* path="/api/folder/downloadSharedFile.php",
* summary="Download a file from a shared folder (by token)",
* description="Public endpoint; validates token and file name, then streams the file.",
* operationId="downloadSharedFile",
* tags={"Shared Folders"},
* @OA\Parameter(name="token", in="query", required=true, @OA\Schema(type="string")),
* @OA\Parameter(name="file", in="query", required=true, @OA\Schema(type="string"), example="report.pdf"),
* @OA\Response(
* response=200,
* description="Binary file",
* content={
* "application/octet-stream": @OA\MediaType(
* mediaType="application/octet-stream",
* @OA\Schema(type="string", format="binary")
* )
* }
* ),
* @OA\Response(response=400, description="Invalid input"),
* @OA\Response(response=404, description="Not found")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/folderController.php';
require_once PROJECT_ROOT . '/src/controllers/FolderController.php';
$folderController = new FolderController();
$folderController->downloadSharedFile();

View File

@@ -1,8 +1,40 @@
<?php
// public/api/folder/getFolderList.php
/**
* @OA\Get(
* path="/api/folder/getFolderList.php",
* summary="List folders (optionally under a parent)",
* description="Requires authentication. Non-admins see folders for which they have full view or own-only access.",
* operationId="getFolderList",
* tags={"Folders"},
* security={{"cookieAuth": {}}},
* @OA\Parameter(
* name="folder", in="query", required=false,
* description="Parent folder to include and descend (default all); use 'root' for top-level",
* @OA\Schema(type="string"), example="root"
* ),
* @OA\Response(
* response=200,
* description="List of folders",
* @OA\JsonContent(
* type="array",
* @OA\Items(
* type="object",
* @OA\Property(property="folder", type="string", example="team/reports"),
* @OA\Property(property="fileCount", type="integer", example=12),
* @OA\Property(property="metadataFile", type="string", example="/path/to/meta.json")
* )
* )
* ),
* @OA\Response(response=400, description="Invalid folder"),
* @OA\Response(response=401, description="Unauthorized")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/folderController.php';
require_once PROJECT_ROOT . '/src/controllers/FolderController.php';
$folderController = new FolderController();
$folderController->getFolderList();

View File

@@ -0,0 +1,21 @@
<?php
/**
* @OA\Get(
* path="/api/folder/getShareFolderLinks.php",
* summary="List active shared-folder links (admin only)",
* description="Returns all non-expired shared-folder links. Admin-only.",
* operationId="getShareFolderLinks",
* tags={"Shared Folders","Admin"},
* security={{"cookieAuth": {}}},
* @OA\Response(response=200, description="Active share-folder links (model-defined JSON)"),
* @OA\Response(response=401, description="Unauthorized"),
* @OA\Response(response=403, description="Admin only")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/FolderController.php';
$folderController = new FolderController();
$folderController->getShareFolderLinks();

View File

@@ -0,0 +1,9 @@
<?php
// public/api/folder/moveFolder.php
declare(strict_types=1);
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/FolderController.php';
$controller = new FolderController();
$controller->moveFolder();

View File

@@ -1,8 +1,33 @@
<?php
// public/api/folder/renameFolder.php
/**
* @OA\Post(
* path="/api/folder/renameFolder.php",
* summary="Rename or move a folder",
* description="Requires authentication, CSRF token, scope checks on old and new paths, and (for non-admins) ownership of the source folder.",
* operationId="renameFolder",
* tags={"Folders"},
* security={{"cookieAuth": {}}},
* @OA\Parameter(name="X-CSRF-Token", in="header", required=true, @OA\Schema(type="string")),
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* required={"oldFolder","newFolder"},
* @OA\Property(property="oldFolder", type="string", example="team/q1"),
* @OA\Property(property="newFolder", type="string", example="team/quarter-1")
* )
* ),
* @OA\Response(response=200, description="Rename result (model-defined JSON)"),
* @OA\Response(response=400, description="Invalid input"),
* @OA\Response(response=401, description="Unauthorized"),
* @OA\Response(response=403, description="Forbidden"),
* @OA\Response(response=405, description="Method not allowed")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/folderController.php';
require_once PROJECT_ROOT . '/src/controllers/FolderController.php';
$folderController = new FolderController();
$folderController->renameFolder();

View File

@@ -1,8 +1,28 @@
<?php
// public/api/folder/shareFolder.php
/**
* @OA\Get(
* path="/api/folder/shareFolder.php",
* summary="Open a shared folder by token (HTML UI)",
* description="If the share is password-protected and no password is supplied, an HTML password form is returned. Otherwise renders an HTML listing with optional upload form.",
* operationId="shareFolder",
* tags={"Shared Folders"},
* @OA\Parameter(name="token", in="query", required=true, @OA\Schema(type="string")),
* @OA\Parameter(name="pass", in="query", required=false, @OA\Schema(type="string")),
* @OA\Parameter(name="page", in="query", required=false, @OA\Schema(type="integer", minimum=1), example=1),
* @OA\Response(
* response=200,
* description="HTML page (password form or folder listing)",
* content={"text/html": @OA\MediaType(mediaType="text/html")}
* ),
* @OA\Response(response=400, description="Missing/invalid token"),
* @OA\Response(response=403, description="Forbidden or wrong password")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/folderController.php';
require_once PROJECT_ROOT . '/src/controllers/FolderController.php';
$folderController = new FolderController();
$folderController->shareFolder();

View File

@@ -1,8 +1,35 @@
<?php
// public/api/folder/uploadToSharedFolder.php
/**
* @OA\Post(
* path="/api/folder/uploadToSharedFolder.php",
* summary="Upload a file into a shared folder (by token)",
* description="Public form-upload endpoint. Only allowed when the share link has uploads enabled. On success responds with a redirect to the share page.",
* operationId="uploadToSharedFolder",
* tags={"Shared Folders"},
* @OA\RequestBody(
* required=true,
* content={
* "multipart/form-data": @OA\MediaType(
* mediaType="multipart/form-data",
* @OA\Schema(
* type="object",
* required={"token","fileToUpload"},
* @OA\Property(property="token", type="string", description="Share token"),
* @OA\Property(property="fileToUpload", type="string", format="binary", description="File to upload")
* )
* )
* }
* ),
* @OA\Response(response=302, description="Redirect to /api/folder/shareFolder.php?token=..."),
* @OA\Response(response=400, description="Upload error or invalid input"),
* @OA\Response(response=405, description="Method not allowed")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/folderController.php';
require_once PROJECT_ROOT . '/src/controllers/FolderController.php';
$folderController = new FolderController();
$folderController->uploadToSharedFolder();

View File

@@ -1,8 +1,27 @@
<?php
// public/api/getUserPermissions.php
/**
* @OA\Get(
* path="/api/getUserPermissions.php",
* summary="Retrieve user permissions",
* description="Returns the permissions for the current user, or all permissions if the user is an admin.",
* operationId="getUserPermissions",
* tags={"Users"},
* @OA\Response(
* response=200,
* description="Successful response with user permissions",
* @OA\JsonContent(type="object")
* ),
* @OA\Response(
* response=401,
* description="Unauthorized"
* )
* )
*/
require_once __DIR__ . '/../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/userController.php';
require_once PROJECT_ROOT . '/src/controllers/UserController.php';
$userController = new UserController();
$userController->getUserPermissions();

View File

@@ -1,8 +1,34 @@
<?php
// public/api/getUsers.php
/**
* @OA\Get(
* path="/api/getUsers.php",
* summary="Retrieve a list of users",
* description="Returns a JSON array of users. Only available to authenticated admin users.",
* operationId="getUsers",
* tags={"Users"},
* @OA\Response(
* response=200,
* description="Successful response with an array of users",
* @OA\JsonContent(
* type="array",
* @OA\Items(
* type="object",
* @OA\Property(property="username", type="string", example="johndoe"),
* @OA\Property(property="role", type="string", example="admin")
* )
* )
* ),
* @OA\Response(
* response=401,
* description="Unauthorized: the user is not authenticated or is not an admin"
* )
* )
*/
require_once __DIR__ . '/../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/userController.php';
require_once PROJECT_ROOT . '/src/controllers/UserController.php';
$userController = new UserController();
$userController->getUsers(); // This will output the JSON response

View File

@@ -0,0 +1,40 @@
<?php
/**
* @OA\Get(
* path="/api/profile/getCurrentUser.php",
* operationId="getCurrentUser",
* tags={"Users"},
* security={{"cookieAuth":{}}},
* @OA\Response(
* response=200,
* description="Current user",
* @OA\JsonContent(
* type="object",
* required={"username","isAdmin","totp_enabled","profile_picture"},
* @OA\Property(property="username", type="string", example="ryan"),
* @OA\Property(property="isAdmin", type="boolean"),
* @OA\Property(property="totp_enabled", type="boolean"),
* @OA\Property(property="profile_picture", type="string", example="/uploads/profile_pics/ryan.png")
* // If you had an array: @OA\Property(property="roles", type="array", @OA\Items(type="string"))
* )
* ),
* @OA\Response(response=401, ref="#/components/responses/Unauthorized")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/models/UserModel.php';
header('Content-Type: application/json');
if (empty($_SESSION['authenticated'])) {
http_response_code(401);
echo json_encode(['error'=>'Unauthorized']);
exit;
}
$user = $_SESSION['username'];
$data = UserModel::getUser($user);
echo json_encode($data);

View File

@@ -0,0 +1,68 @@
<?php
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/UserController.php';
/**
* @OA\Post(
* path="/api/profile/uploadPicture.php",
* summary="Upload or replace the current user's profile picture",
* description="Accepts a single image file (JPEG, PNG, or GIF) up to 2&nbsp;MB. Requires a valid session cookie and CSRF token.",
* operationId="uploadProfilePicture",
* tags={"Users"},
* security={{"cookieAuth": {}}},
*
* @OA\Parameter(
* name="X-CSRF-Token",
* in="header",
* required=true,
* description="Anti-CSRF token associated with the current session.",
* @OA\Schema(type="string")
* ),
*
* @OA\RequestBody(
* required=true,
* @OA\MediaType(
* mediaType="multipart/form-data",
* @OA\Schema(
* required={"profile_picture"},
* @OA\Property(
* property="profile_picture",
* type="string",
* format="binary",
* description="JPEG, PNG, or GIF image. Max size: 2 MB."
* )
* )
* )
* ),
*
* @OA\Response(
* response=200,
* description="Profile picture updated.",
* @OA\JsonContent(
* type="object",
* required={"success","url"},
* @OA\Property(property="success", type="boolean", example=true),
* @OA\Property(property="url", type="string", example="/uploads/profile_pics/alice_9f3c2e1a8bcd.png")
* )
* ),
* @OA\Response(response=400, description="No file uploaded, invalid file type, or file too large."),
* @OA\Response(response=401, ref="#/components/responses/Unauthorized"),
* @OA\Response(response=403, ref="#/components/responses/Forbidden"),
* @OA\Response(response=500, description="Server error while saving the picture.")
* )
*/
// Always JSON, even on PHP notices
header('Content-Type: application/json');
try {
$userController = new UserController();
$userController->uploadPicture();
} catch (\Throwable $e) {
http_response_code(500);
echo json_encode([
'success' => false,
'error' => 'Exception: ' . $e->getMessage()
]);
}

View File

@@ -1,8 +1,44 @@
<?php
// public/api/removeUser.php
/**
* @OA\Delete(
* path="/api/removeUser.php",
* summary="Remove a user",
* description="Removes the specified user from the system. Cannot remove the currently logged-in user.",
* operationId="removeUser",
* tags={"Users"},
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* required={"username"},
* @OA\Property(property="username", type="string", example="johndoe")
* )
* ),
* @OA\Response(
* response=200,
* description="User removed successfully",
* @OA\JsonContent(
* @OA\Property(property="success", type="string", example="User removed successfully")
* )
* ),
* @OA\Response(
* response=400,
* description="Bad Request"
* ),
* @OA\Response(
* response=401,
* description="Unauthorized"
* ),
* @OA\Response(
* response=403,
* description="Invalid CSRF token"
* )
* )
*/
require_once __DIR__ . '/../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/userController.php';
require_once PROJECT_ROOT . '/src/controllers/UserController.php';
$userController = new UserController();
$userController->removeUser();

View File

@@ -1,9 +1,35 @@
<?php
// public/api/totp_disable.php
/**
* @OA\Put(
* path="/api/totp_disable.php",
* summary="Disable TOTP for the authenticated user",
* description="Clears the TOTP secret from the users file for the current user.",
* operationId="disableTOTP",
* tags={"TOTP"},
* @OA\Response(
* response=200,
* description="TOTP disabled successfully",
* @OA\JsonContent(
* @OA\Property(property="success", type="boolean", example=true),
* @OA\Property(property="message", type="string", example="TOTP disabled successfully.")
* )
* ),
* @OA\Response(
* response=403,
* description="Not authenticated or invalid CSRF token"
* ),
* @OA\Response(
* response=500,
* description="Failed to disable TOTP"
* )
* )
*/
require_once __DIR__ . '/../../config/config.php';
require_once PROJECT_ROOT . '/vendor/autoload.php';
require_once PROJECT_ROOT . '/src/controllers/userController.php';
require_once PROJECT_ROOT . '/src/controllers/UserController.php';
$userController = new UserController();
$userController->disableTOTP();

View File

@@ -1,8 +1,48 @@
<?php
// public/api/totp_recover.php
/**
* @OA\Post(
* path="/api/totp_recover.php",
* summary="Recover TOTP",
* description="Verifies a recovery code to disable TOTP and finalize login.",
* operationId="recoverTOTP",
* tags={"TOTP"},
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* required={"recovery_code"},
* @OA\Property(property="recovery_code", type="string", example="ABC123DEF456")
* )
* ),
* @OA\Response(
* response=200,
* description="Recovery successful",
* @OA\JsonContent(
* @OA\Property(property="status", type="string", example="ok")
* )
* ),
* @OA\Response(
* response=400,
* description="Invalid input or recovery code"
* ),
* @OA\Response(
* response=403,
* description="Invalid CSRF token"
* ),
* @OA\Response(
* response=405,
* description="Method not allowed"
* ),
* @OA\Response(
* response=429,
* description="Too many attempts"
* )
* )
*/
require_once __DIR__ . '/../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/userController.php';
require_once PROJECT_ROOT . '/src/controllers/UserController.php';
$userController = new UserController();
$userController->recoverTOTP();

View File

@@ -1,8 +1,38 @@
<?php
// public/api/totp_saveCode.php
/**
* @OA\Post(
* path="/api/totp_saveCode.php",
* summary="Generate and save a new TOTP recovery code",
* description="Generates a new TOTP recovery code for the authenticated user, stores its hash, and returns the plain text recovery code.",
* operationId="totpSaveCode",
* tags={"TOTP"},
* @OA\Response(
* response=200,
* description="Recovery code generated successfully",
* @OA\JsonContent(
* @OA\Property(property="status", type="string", example="ok"),
* @OA\Property(property="recoveryCode", type="string", example="ABC123DEF456")
* )
* ),
* @OA\Response(
* response=400,
* description="Bad Request"
* ),
* @OA\Response(
* response=403,
* description="Invalid CSRF token or unauthorized"
* ),
* @OA\Response(
* response=405,
* description="Method not allowed"
* )
* )
*/
require_once __DIR__ . '/../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/userController.php';
require_once PROJECT_ROOT . '/src/controllers/UserController.php';
$userController = new UserController();
$userController->saveTOTPRecoveryCode();

View File

@@ -1,9 +1,34 @@
<?php
// public/api/totp_setup.php
/**
* @OA\Get(
* path="/api/totp_setup.php",
* summary="Set up TOTP and generate a QR code",
* description="Generates (or retrieves) the TOTP secret for the user and builds a QR code image for scanning.",
* operationId="setupTOTP",
* tags={"TOTP"},
* @OA\Response(
* response=200,
* description="QR code image for TOTP setup",
* @OA\MediaType(
* mediaType="image/png"
* )
* ),
* @OA\Response(
* response=403,
* description="Unauthorized or invalid CSRF token"
* ),
* @OA\Response(
* response=500,
* description="Server error"
* )
* )
*/
require_once __DIR__ . '/../../config/config.php';
require_once PROJECT_ROOT . '/vendor/autoload.php';
require_once PROJECT_ROOT . '/src/controllers/userController.php';
require_once PROJECT_ROOT . '/src/controllers/UserController.php';
$userController = new UserController();
$userController->setupTOTP();

View File

@@ -1,9 +1,46 @@
<?php
// public/api/totp_verify.php
/**
* @OA\Post(
* path="/api/totp_verify.php",
* summary="Verify TOTP code",
* description="Verifies a TOTP code and completes login for pending users or validates TOTP for setup verification.",
* operationId="verifyTOTP",
* tags={"TOTP"},
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* required={"totp_code"},
* @OA\Property(property="totp_code", type="string", example="123456")
* )
* ),
* @OA\Response(
* response=200,
* description="TOTP successfully verified",
* @OA\JsonContent(
* @OA\Property(property="status", type="string", example="ok"),
* @OA\Property(property="message", type="string", example="Login successful")
* )
* ),
* @OA\Response(
* response=400,
* description="Bad Request (e.g., invalid input)"
* ),
* @OA\Response(
* response=403,
* description="Not authenticated or invalid CSRF token"
* ),
* @OA\Response(
* response=429,
* description="Too many attempts. Try again later."
* )
* )
*/
require_once __DIR__ . '/../../config/config.php';
require_once PROJECT_ROOT . '/vendor/autoload.php';
require_once PROJECT_ROOT . '/src/controllers/userController.php';
require_once PROJECT_ROOT . '/src/controllers/UserController.php';
$userController = new UserController();
$userController->verifyTOTP();

View File

@@ -1,8 +1,44 @@
<?php
// public/api/updateUserPanel.php
/**
* @OA\Put(
* path="/api/updateUserPanel.php",
* summary="Update user panel settings",
* description="Updates user panel settings by disabling TOTP when not enabled. Accessible to authenticated users.",
* operationId="updateUserPanel",
* tags={"Users"},
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* required={"totp_enabled"},
* @OA\Property(property="totp_enabled", type="boolean", example=false)
* )
* ),
* @OA\Response(
* response=200,
* description="User panel updated successfully",
* @OA\JsonContent(
* @OA\Property(property="success", type="string", example="User panel updated: TOTP disabled")
* )
* ),
* @OA\Response(
* response=401,
* description="Unauthorized"
* ),
* @OA\Response(
* response=403,
* description="Invalid CSRF token"
* ),
* @OA\Response(
* response=400,
* description="Bad Request"
* )
* )
*/
require_once __DIR__ . '/../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/userController.php';
require_once PROJECT_ROOT . '/src/controllers/UserController.php';
$userController = new UserController();
$userController->updateUserPanel();

View File

@@ -1,8 +1,54 @@
<?php
// public/api/updateUserPermissions.php
/**
* @OA\Put(
* path="/api/updateUserPermissions.php",
* summary="Update user permissions",
* description="Updates permissions for users. Only available to authenticated admin users.",
* operationId="updateUserPermissions",
* tags={"Users"},
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* required={"permissions"},
* @OA\Property(
* property="permissions",
* type="array",
* @OA\Items(
* type="object",
* @OA\Property(property="username", type="string", example="johndoe"),
* @OA\Property(property="folderOnly", type="boolean", example=true),
* @OA\Property(property="readOnly", type="boolean", example=false),
* @OA\Property(property="disableUpload", type="boolean", example=false)
* )
* )
* )
* ),
* @OA\Response(
* response=200,
* description="User permissions updated successfully",
* @OA\JsonContent(
* @OA\Property(property="success", type="string", example="User permissions updated successfully.")
* )
* ),
* @OA\Response(
* response=401,
* description="Unauthorized"
* ),
* @OA\Response(
* response=403,
* description="Invalid CSRF token"
* ),
* @OA\Response(
* response=400,
* description="Bad Request"
* )
* )
*/
require_once __DIR__ . '/../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/userController.php';
require_once PROJECT_ROOT . '/src/controllers/UserController.php';
$userController = new UserController();
$userController->updateUserPermissions();

View File

@@ -1,8 +1,37 @@
<?php
// public/api/upload/removeChunks.php
/**
* @OA\Post(
* path="/api/upload/removeChunks.php",
* summary="Remove temporary chunk directory",
* description="Deletes the temporary directory used for a chunked upload. Requires a valid CSRF token in the form field.",
* operationId="removeChunks",
* tags={"Uploads"},
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* required={"folder"},
* @OA\Property(property="folder", type="string", example="resumable_myupload123"),
* @OA\Property(property="csrf_token", type="string", description="CSRF token for this session")
* )
* ),
* @OA\Response(
* response=200,
* description="Removal result",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="success", type="boolean", example=true),
* @OA\Property(property="message", type="string", example="Temporary folder removed.")
* )
* ),
* @OA\Response(response=400, description="Invalid input"),
* @OA\Response(response=403, description="Invalid CSRF token")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/uploadController.php';
require_once PROJECT_ROOT . '/src/controllers/UploadController.php';
$uploadController = new UploadController();
$uploadController->removeChunks();

View File

@@ -1,7 +1,86 @@
<?php
// public/api/upload/upload.php
/**
* @OA\Post(
* path="/api/upload/upload.php",
* summary="Upload a file (supports chunked + full uploads)",
* description="Requires a session (cookie) and a CSRF token (header preferred; falls back to form field). Checks user/account flags and folder-level WRITE ACL, then delegates to the model. Returns JSON for chunked uploads; full uploads may redirect after success.",
* operationId="handleUpload",
* tags={"Uploads"},
* security={{"cookieAuth": {}}},
* @OA\Parameter(
* name="X-CSRF-Token", in="header", required=false,
* description="CSRF token for this session (preferred). If omitted, send as form field `csrf_token`.",
* @OA\Schema(type="string")
* ),
* @OA\RequestBody(
* required=true,
* content={
* "multipart/form-data": @OA\MediaType(
* mediaType="multipart/form-data",
* @OA\Schema(
* type="object",
* required={"fileToUpload"},
* @OA\Property(
* property="fileToUpload", type="string", format="binary",
* description="File or chunk payload."
* ),
* @OA\Property(
* property="folder", type="string", example="root",
* description="Target folder (defaults to 'root' if omitted)."
* ),
* @OA\Property(property="csrf_token", type="string", description="CSRF token (form fallback)."),
* @OA\Property(property="upload_token", type="string", description="Legacy alias for CSRF token (accepted by server)."),
* @OA\Property(property="resumableChunkNumber", type="integer"),
* @OA\Property(property="resumableTotalChunks", type="integer"),
* @OA\Property(property="resumableChunkSize", type="integer"),
* @OA\Property(property="resumableCurrentChunkSize", type="integer"),
* @OA\Property(property="resumableTotalSize", type="integer"),
* @OA\Property(property="resumableType", type="string"),
* @OA\Property(property="resumableIdentifier", type="string"),
* @OA\Property(property="resumableFilename", type="string"),
* @OA\Property(property="resumableRelativePath", type="string")
* )
* )
* }
* ),
* @OA\Response(
* response=200,
* description="JSON result (success, chunk status, or CSRF refresh).",
* @OA\JsonContent(
* oneOf={
* @OA\Schema( ; Success (full or model-returned)
* type="object",
* @OA\Property(property="success", type="string", example="File uploaded successfully"),
* @OA\Property(property="newFilename", type="string", example="5f2d7c123a_example.png")
* ),
* @OA\Schema( ; Chunk flow
* type="object",
* @OA\Property(property="status", type="string", example="chunk uploaded")
* ),
* @OA\Schema( ; CSRF soft-refresh path
* type="object",
* @OA\Property(property="csrf_expired", type="boolean", example=true),
* @OA\Property(property="csrf_token", type="string", example="b1c2...f9")
* )
* }
* )
* ),
* @OA\Response(
* response=302,
* description="Redirect after a successful full upload.",
* @OA\Header(header="Location", description="Where the client is redirected", @OA\Schema(type="string"))
* ),
* @OA\Response(response=400, description="Bad request (missing/invalid fields, model error)"),
* @OA\Response(response=401, description="Unauthorized (no session)"),
* @OA\Response(response=403, description="Forbidden (upload disabled or no WRITE to folder)"),
* @OA\Response(response=500, description="Server error while processing upload")
* )
*/
require_once __DIR__ . '/../../../config/config.php';
require_once PROJECT_ROOT . '/src/controllers/uploadController.php';
require_once PROJECT_ROOT . '/src/controllers/UploadController.php';
$uploadController = new UploadController();
$uploadController->handleUpload();

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

File diff suppressed because it is too large Load Diff

24
public/css/vendor/material-icons.css vendored Normal file
View File

@@ -0,0 +1,24 @@
/* fallback */
@font-face {
font-family: 'Material Icons';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(/fonts/material-icons/flUhRq6tzZclQEJ-Vdg-IuiaDsNcIhQ8tQ.woff2) format('woff2');
}
.material-icons {
font-family: 'Material Icons';
font-weight: normal;
font-style: normal;
font-size: 24px;
line-height: 1;
letter-spacing: normal;
text-transform: none;
display: inline-block;
white-space: nowrap;
word-wrap: normal;
direction: ltr;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
}

44
public/css/vendor/roboto.css vendored Normal file
View File

@@ -0,0 +1,44 @@
/* Roboto Regular 400 — latin-ext */
@font-face{
font-family:'Roboto';
font-style:normal;
font-weight:400;
font-display:swap;
src:url('/fonts/roboto/KFO7CnqEu92Fr1ME7kSn66aGLdTylUAMa3KUBHMdazTgWw.woff2') format('woff2');
unicode-range:U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
}
/* Roboto Regular 400 — latin */
@font-face{
font-family:'Roboto';
font-style:normal;
font-weight:400;
font-display:swap;
src:url('/fonts/roboto/KFO7CnqEu92Fr1ME7kSn66aGLdTylUAMa3yUBHMdazQ.woff2') format('woff2');
unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
}
/* Roboto Medium 500 — latin-ext */
@font-face{
font-family:'Roboto';
font-style:normal;
font-weight:500;
font-display:swap;
src:url('/fonts/roboto/KFO7CnqEu92Fr1ME7kSn66aGLdTylUAMa3KUBHMdazTgWw.woff2') format('woff2');
unicode-range:U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
}
/* Roboto Medium 500 — latin */
@font-face{
font-family:'Roboto';
font-style:normal;
font-weight:500;
font-display:swap;
src:url('/fonts/roboto/KFO7CnqEu92Fr1ME7kSn66aGLdTylUAMa3yUBHMdazQ.woff2') format('woff2');
unicode-range:U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD;
}
/* sensible stack so Chinese falls back cleanly */
:root{
--ui-font: Roboto, -apple-system, BlinkMacSystemFont, "Segoe UI",
"PingFang SC","Hiragino Sans GB","Microsoft YaHei","Noto Sans CJK SC",
"Helvetica Neue", Arial, "Noto Sans", sans-serif;
}
body{ font-family: var(--ui-font); }

Binary file not shown.

View File

@@ -4,43 +4,37 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title data-i18n-key="title">FileRise</title>
<title>FileRise</title>
<link rel="icon" type="image/png" href="/assets/logo.png">
<link rel="icon" type="image/svg+xml" href="/assets/logo.svg">
<meta name="csrf-token" content="">
<meta name="share-url" content="">
<!-- Google Fonts and Material Icons -->
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap" rel="stylesheet" />
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.5/codemirror.min.css"
integrity="sha384-zaeBlB/vwYsDRSlFajnDd7OydJ0cWk+c2OWybl3eSUf6hW2EbhlCsQPqKr3gkznT" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.5/theme/material-darker.min.css"
integrity="sha384-eZTPTN0EvJdn23s24UDYJmUM2T7C2ZFa3qFLypeBruJv8mZeTusKUAO/j5zPAQ6l" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.5/codemirror.min.js"
integrity="sha384-UXbkZAbZYZ/KCAslc6UO4d6UHNKsOxZ/sqROSQaPTZCuEIKhfbhmffQ64uXFOcma"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.5/mode/xml/xml.min.js"
integrity="sha384-xPpkMo5nDgD98fIcuRVYhxkZV6/9Y4L8s3p0J5c4MxgJkyKJ8BJr+xfRkq7kn6Tw"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.5/mode/css/css.min.js"
integrity="sha384-to8njsu2GAiXQnY/aLGzz0DIY/SFSeSDodtvSl869n2NmsBdHOTZNNqbEBPYh7Pa"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.5/mode/javascript/javascript.min.js"
integrity="sha384-kmQrbJf09Uo1WRLMDVGoVG3nM6F48frIhcj7f3FDUjeRzsiHwyBWDjMUIttnIeAf"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/resumable.js/1.1.0/resumable.min.js"
integrity="sha384-EXTg7rRfdTPZWoKVCslusAAev2TYw76fm+Wox718iEtFQ+gdAdAc5Z/ndLHSo4mq"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/2.4.0/purify.min.js"
integrity="sha384-Tsl3d5pUAO7a13enIvSsL3O0/95nsthPJiPto5NtLuY8w3+LbZOpr3Fl2MNmrh1E"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/fuse.js@6.6.2/dist/fuse.min.js"
integrity="sha384-zPE55eyESN+FxCWGEnlNxGyAPJud6IZ6TtJmXb56OFRGhxZPN4akj9rjA3gw5Qqa"
crossorigin="anonymous"></script>
<link rel="stylesheet" href="css/styles.css" />
<style>.main-wrapper{display:none}#loadingOverlay{position:fixed;inset:0;background:var(--bg-color,#fff);z-index:9999;display:flex;align-items:center;justify-content:center}</style>
<link rel="stylesheet" href="/css/vendor/roboto.css?v=dev">
<link rel="stylesheet" href="/css/vendor/material-icons.css?v=dev">
<!-- Bootstrap CSS (local) -->
<link rel="stylesheet" href="/vendor/bootstrap/4.5.2/bootstrap.min.css?v=dev">
<!-- CodeMirror CSS (local) -->
<link rel="stylesheet" href="/vendor/codemirror/5.65.5/codemirror.min.css?v=dev">
<link rel="stylesheet" href="/vendor/codemirror/5.65.5/theme/material-darker.min.css?v=dev">
<!-- app CSS -->
<link rel="stylesheet" href="/css/styles.css?v=dev">
<!-- Libraries (JS) -->
<script src="/vendor/dompurify/2.4.0/purify.min.js?v=dev"></script>
<script src="/vendor/fuse/6.6.2/fuse.min.js?v=dev"></script>
<script src="/vendor/resumable/1.1.0/resumable.min.js?v=dev"></script>
<!-- CodeMirror core FIRST, then modes -->
<script src="/vendor/codemirror/5.65.5/codemirror.min.js?v=dev"></script>
<script src="/js/version.js?v=dev"></script>
<script type="module" src="/js/main.js"></script>
</head>
<body>
@@ -120,9 +114,6 @@
<!-- Your header drop zone -->
<div id="headerDropArea" class="header-drop-zone"></div>
<div class="header-buttons">
<button id="logoutBtn" data-i18n-title="logout">
<i class="material-icons">exit_to_app</i>
</button>
<button id="changePasswordBtn" data-i18n-title="change_password" style="display: none;">
<i class="material-icons">vpn_key</i>
</button>
@@ -165,10 +156,42 @@
</div>
</header>
<div id="loadingOverlay"></div>
<!-- Custom Toast Container -->
<div id="customToast"></div>
<div id="hiddenCardsContainer" style="display:none;"></div>
<div class="row mt-4" id="loginForm">
<div class="col-12">
<form id="authForm" method="post">
<div class="form-group">
<label for="loginUsername" data-i18n-key="user">User:</label>
<input type="text" class="form-control" id="loginUsername" name="username" required autofocus />
</div>
<div class="form-group">
<label for="loginPassword" data-i18n-key="password">Password:</label>
<input type="password" class="form-control" id="loginPassword" name="password" required />
</div>
<button type="submit" class="btn btn-primary btn-block btn-login" data-i18n-key="login">Login</button>
<div class="form-group remember-me-container">
<input type="checkbox" id="rememberMeCheckbox" name="remember_me" />
<label for="rememberMeCheckbox" data-i18n-key="remember_me">Remember me</label>
</div>
</form>
<!-- OIDC Login Option -->
<div class="text-center mt-3">
<button id="oidcLoginBtn" class="btn btn-secondary" data-i18n-key="login_oidc">Login with OIDC</button>
</div>
<!-- Basic HTTP Login Option -->
<div class="text-center mt-3">
<a href="/api/auth/login_basic.php" class="btn btn-secondary" data-i18n-key="basic_http_login">Use Basic
HTTP
Login</a>
</div>
</div>
</div>
<!-- Main Wrapper: Hidden by default; remove "display: none;" after login -->
<div class="main-wrapper">
<!-- Sidebar Drop Zone: Hidden until you drag a card (display controlled by JS) -->
@@ -176,37 +199,6 @@
<!-- Main Column -->
<div id="mainColumn" class="main-column">
<div class="container-fluid">
<!-- Login Form (unchanged) -->
<div class="row" id="loginForm">
<div class="col-12">
<form id="authForm" method="post">
<div class="form-group">
<label for="loginUsername" data-i18n-key="user">User:</label>
<input type="text" class="form-control" id="loginUsername" name="username" required />
</div>
<div class="form-group">
<label for="loginPassword" data-i18n-key="password">Password:</label>
<input type="password" class="form-control" id="loginPassword" name="password" required />
</div>
<button type="submit" class="btn btn-primary btn-block btn-login" data-i18n-key="login">Login</button>
<div class="form-group remember-me-container">
<input type="checkbox" id="rememberMeCheckbox" name="remember_me" />
<label for="rememberMeCheckbox" data-i18n-key="remember_me">Remember me</label>
</div>
</form>
<!-- OIDC Login Option -->
<div class="text-center mt-3">
<button id="oidcLoginBtn" class="btn btn-secondary" data-i18n-key="login_oidc">Login with OIDC</button>
</div>
<!-- Basic HTTP Login Option -->
<div class="text-center mt-3">
<a href="/api/auth/login_basic.php" class="btn btn-secondary" data-i18n-key="basic_http_login">Use Basic
HTTP
Login</a>
</div>
</div>
</div>
<!-- Main Operations: Upload and Folder Management -->
<div id="mainOperations">
<div class="container" style="max-width: 1400px; margin: 0 auto;">
@@ -268,9 +260,27 @@
</div>
</div>
</div>
<button id="moveFolderBtn" class="btn btn-warning ml-2" data-i18n-title="move_folder">
<i class="material-icons">drive_file_move</i>
</button>
<!-- MOVE FOLDER MODAL (place near your other folder modals) -->
<div id="moveFolderModal" class="modal" style="display:none;">
<div class="modal-content">
<h4 data-i18n-key="move_folder_title">Move Folder</h4>
<p data-i18n-key="move_folder_message">Select a destination folder to move the current folder
into:</p>
<select id="moveFolderTarget" class="form-control modal-input"></select>
<div class="modal-footer" style="margin-top:15px; text-align:right;">
<button id="cancelMoveFolder" class="btn btn-secondary"
data-i18n-key="cancel">Cancel</button>
<button id="confirmMoveFolder" class="btn btn-primary" data-i18n-key="move">Move</button>
</div>
</div>
</div>
<button id="renameFolderBtn" class="btn btn-warning ml-2" data-i18n-title="rename_folder">
<i class="material-icons">drive_file_rename_outline</i>
</button>
<div id="renameFolderModal" class="modal">
<div class="modal-content">
<h4 data-i18n-key="rename_folder_title">Rename Folder</h4>
@@ -371,8 +381,49 @@
</div>
<button id="downloadZipBtn" class="btn action-btn" style="display: none;" disabled
data-i18n-key="download_zip">Download ZIP</button>
<button id="extractZipBtn" class="btn btn-sm btn-info" data-i18n-title="extract_zip"
<button id="extractZipBtn" class="btn action-btn btn-sm btn-info" style="display: none;" disabled
data-i18n-key="extract_zip_button">Extract Zip</button>
<div id="createDropdown" class="dropdown-container" style="position:relative; display:inline-block;">
<button id="createBtn" class="btn action-btn" style="display: none;" data-i18n-key="create">
${t('create')} <span class="material-icons"
style="font-size:16px;vertical-align:middle;">arrow_drop_down</span>
</button>
<ul id="createMenu" class="dropdown-menu" style="
display: none;
position: absolute;
top: 100%;
left: 0;
margin: 4px 0 0;
padding: 0;
list-style: none;
background: #fff;
border: 1px solid #ccc;
box-shadow: 0 2px 6px rgba(0,0,0,0.2);
z-index: 1000;
min-width: 140px;
">
<li id="createFileOption" class="dropdown-item" data-i18n-key="create_file"
style="padding:8px 12px; cursor:pointer;">
${t('create_file')}
</li>
<li id="createFolderOption" class="dropdown-item" data-i18n-key="create_folder"
style="padding:8px 12px; cursor:pointer;">
${t('create_folder')}
</li>
</ul>
</div>
<!-- Create File Modal -->
<div id="createFileModal" class="modal" style="display:none;">
<div class="modal-content">
<h4 data-i18n-key="create_new_file">Create New File</h4>
<input type="text" id="createFileNameInput" class="form-control" placeholder="Enter filename…"
data-i18n-placeholder="newfile_placeholder" />
<div class="modal-footer" style="margin-top:1rem; text-align:right;">
<button id="cancelCreateFile" class="btn btn-secondary" data-i18n-key="cancel">Cancel</button>
<button id="confirmCreateFile" class="btn btn-primary" data-i18n-key="create">Create</button>
</div>
</div>
</div>
<div id="downloadZipModal" class="modal" style="display:none;">
<div class="modal-content">
<h4 data-i18n-key="download_zip_title">Download Selected Files as Zip</h4>
@@ -427,8 +478,7 @@
<!-- Change Password, Add User, Remove User, Rename File, and Custom Confirm Modals (unchanged) -->
<div id="changePasswordModal" class="modal" style="display:none;">
<div class="modal-content" style="max-width:400px; margin:auto;">
<span id="closeChangePasswordModal"
style="position:absolute; top:10px; right:10px; cursor:pointer; font-size:24px;">&times;</span>
<span id="closeChangePasswordModal" class="editor-close-btn">&times;</span>
<h3 data-i18n-key="change_password_title">Change Password</h3>
<input type="password" id="oldPassword" class="form-control" data-i18n-placeholder="old_password"
placeholder="Old Password" style="width:100%; margin: 5px 0;" />
@@ -439,24 +489,36 @@
<button id="saveNewPasswordBtn" class="btn btn-primary" data-i18n-key="save" style="width:100%;">Save</button>
</div>
</div>
<div id="addUserModal" class="modal">
<div id="addUserModal" class="modal" style="display:none;">
<div class="modal-content">
<h3 data-i18n-key="create_new_user_title">Create New User</h3>
<label for="newUsername" data-i18n-key="username">Username:</label>
<input type="text" id="newUsername" class="form-control" />
<label for="addUserPassword" data-i18n-key="password">Password:</label>
<input type="password" id="addUserPassword" class="form-control" />
<div id="adminCheckboxContainer">
<input type="checkbox" id="isAdmin" />
<label for="isAdmin" data-i18n-key="grant_admin">Grant Admin Access</label>
</div>
<div class="button-container">
<button id="cancelUserBtn" class="btn btn-secondary" data-i18n-key="cancel">Cancel</button>
<button id="saveUserBtn" class="btn btn-primary" data-i18n-key="save_user">Save User</button>
</div>
<!-- 1) Add a form around these fields -->
<form id="addUserForm">
<label for="newUsername" data-i18n-key="username">Username:</label>
<input type="text" id="newUsername" class="form-control" required />
<label for="addUserPassword" data-i18n-key="password">Password:</label>
<input type="password" id="addUserPassword" class="form-control" required />
<div id="adminCheckboxContainer">
<input type="checkbox" id="isAdmin" />
<label for="isAdmin" data-i18n-key="grant_admin">Grant Admin Access</label>
</div>
<div class="button-container">
<!-- Cancel stays type="button" -->
<button type="button" id="cancelUserBtn" class="btn btn-secondary" data-i18n-key="cancel">
Cancel
</button>
<!-- Save becomes type="submit" -->
<button type="submit" id="saveUserBtn" class="btn btn-primary" data-i18n-key="save_user">
Save User
</button>
</div>
</form>
</div>
</div>
<div id="removeUserModal" class="modal">
<div id="removeUserModal" class="modal" style="display:none;">
<div class="modal-content">
<h3 data-i18n-key="remove_user_title">Remove User</h3>
<label for="removeUsernameSelect" data-i18n-key="select_user_remove">Select a user to remove:</label>
@@ -467,7 +529,7 @@
</div>
</div>
</div>
<div id="renameFileModal" class="modal">
<div id="renameFileModal" class="modal" style="display:none;">
<div class="modal-content">
<h4 data-i18n-key="rename_file_title">Rename File</h4>
<input type="text" id="newFileName" class="form-control" data-i18n-placeholder="rename_file_placeholder"
@@ -487,7 +549,7 @@
</div>
</div>
</div>
<script type="module" src="js/main.js"></script>
</body>
</html>

1355
public/js/adminPanel.js Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -15,16 +15,17 @@ import {
openUserPanel,
openTOTPModal,
closeTOTPModal,
openAdminPanel,
closeAdminPanel,
setLastLoginData
setLastLoginData,
openApiModal
} from './authModals.js';
import { openAdminPanel } from './adminPanel.js';
import { initializeApp, triggerLogout } from './main.js';
// Production OIDC configuration (override via API as needed)
const currentOIDCConfig = {
providerUrl: "https://your-oidc-provider.com",
clientId: "YOUR_CLIENT_ID",
clientSecret: "YOUR_CLIENT_SECRET",
clientId: "",
clientSecret: "",
redirectUri: "https://yourdomain.com/api/auth/auth.php?oidc=callback",
globalOtpauthUrl: ""
};
@@ -35,13 +36,33 @@ window.currentOIDCConfig = currentOIDCConfig;
window.pendingTOTP = new URLSearchParams(window.location.search).get('totp_required') === '1';
// override showToast to suppress the "Please log in to continue." toast during TOTP
function showToast(msgKey) {
const msg = t(msgKey);
if (window.pendingTOTP && msgKey === "please_log_in_to_continue") {
function showToast(msgKeyOrText, type) {
const isDemoHost = window.location.hostname.toLowerCase() === "demo.filerise.net";
// If it's the pre-login prompt and we're on the demo site, show demo creds instead.
if (isDemoHost) {
return originalShowToast("Demo site — use: \nUsername: demo\nPassword: demo", 12000);
}
// Dont nag during pending TOTP, as you already had
if (window.pendingTOTP && msgKeyOrText === "please_log_in_to_continue") {
return;
}
originalShowToast(msg);
// Translate if a key; otherwise pass through the raw text
let msg = msgKeyOrText;
try {
const translated = t(msgKeyOrText);
// If t() changed it or it's a key-like string, use the translation
if (typeof translated === "string" && translated !== msgKeyOrText) {
msg = translated;
}
} catch { /* if t() isnt available here, just use the original */ }
return originalShowToast(msg);
}
window.showToast = showToast;
const originalFetch = window.fetch;
@@ -125,10 +146,24 @@ function updateItemsPerPageSelect() {
}
}
function applyProxyBypassUI() {
const bypass = localStorage.getItem("authBypass") === "true";
const loginContainer = document.getElementById("loginForm");
if (loginContainer) {
loginContainer.style.display = bypass ? "none" : "";
}
}
function updateLoginOptionsUI({ disableFormLogin, disableBasicAuth, disableOIDCLogin }) {
const authForm = document.getElementById("authForm");
if (authForm) authForm.style.display = disableFormLogin ? "none" : "block";
if
(authForm) {
authForm.style.display = disableFormLogin ? "none" : "block";
setTimeout(() => {
const loginInput = document.getElementById('loginUsername');
if (loginInput) loginInput.focus();
}, 0);
}
const basicAuthLink = document.querySelector("a[href='/api/auth/login_basic.php']");
if (basicAuthLink) basicAuthLink.style.display = disableBasicAuth ? "none" : "inline-block";
const oidcLoginBtn = document.getElementById("oidcLoginBtn");
@@ -139,31 +174,38 @@ function updateLoginOptionsUIFromStorage() {
updateLoginOptionsUI({
disableFormLogin: localStorage.getItem("disableFormLogin") === "true",
disableBasicAuth: localStorage.getItem("disableBasicAuth") === "true",
disableOIDCLogin: localStorage.getItem("disableOIDCLogin") === "true"
disableOIDCLogin: localStorage.getItem("disableOIDCLogin") === "true",
authBypass: localStorage.getItem("authBypass") === "true"
});
}
export function loadAdminConfigFunc() {
return fetch("/api/admin/getConfig.php", { credentials: "include" })
.then(response => response.json())
.then(config => {
localStorage.setItem("headerTitle", config.header_title || "FileRise");
.then(async (response) => {
// If a proxy or some edge returns 204/empty, handle gracefully
let config = {};
try { config = await response.json(); } catch { config = {}; }
// Update login options using the nested loginOptions object.
localStorage.setItem("disableFormLogin", config.loginOptions.disableFormLogin);
localStorage.setItem("disableBasicAuth", config.loginOptions.disableBasicAuth);
localStorage.setItem("disableOIDCLogin", config.loginOptions.disableOIDCLogin);
localStorage.setItem("globalOtpauthUrl", config.globalOtpauthUrl || "otpauth://totp/{label}?secret={secret}&issuer=FileRise");
const headerTitle = config.header_title || "FileRise";
localStorage.setItem("headerTitle", headerTitle);
document.title = headerTitle;
const lo = config.loginOptions || {};
localStorage.setItem("disableFormLogin", String(!!lo.disableFormLogin));
localStorage.setItem("disableBasicAuth", String(!!lo.disableBasicAuth));
localStorage.setItem("disableOIDCLogin", String(!!lo.disableOIDCLogin));
localStorage.setItem("globalOtpauthUrl", config.globalOtpauthUrl || "otpauth://totp/{label}?secret={secret}&issuer=FileRise");
// These may be absent for non-admins; default them
localStorage.setItem("authBypass", String(!!lo.authBypass));
localStorage.setItem("authHeaderName", lo.authHeaderName || "X-Remote-User");
updateLoginOptionsUIFromStorage();
const headerTitleElem = document.querySelector(".header-title h1");
if (headerTitleElem) {
headerTitleElem.textContent = config.header_title || "FileRise";
}
if (headerTitleElem) headerTitleElem.textContent = headerTitle;
})
.catch(() => {
// Use defaults.
// Fallback defaults if request truly fails
localStorage.setItem("headerTitle", "FileRise");
localStorage.setItem("disableFormLogin", "false");
localStorage.setItem("disableBasicAuth", "false");
@@ -172,9 +214,7 @@ export function loadAdminConfigFunc() {
updateLoginOptionsUIFromStorage();
const headerTitleElem = document.querySelector(".header-title h1");
if (headerTitleElem) {
headerTitleElem.textContent = "FileRise";
}
if (headerTitleElem) headerTitleElem.textContent = "FileRise";
});
}
@@ -182,16 +222,48 @@ function insertAfter(newNode, referenceNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
function updateAuthenticatedUI(data) {
async function fetchProfilePicture() {
try {
const res = await fetch('/api/profile/getCurrentUser.php', {
credentials: 'include'
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const info = await res.json();
let pic = info.profile_picture || '';
// --- take only what's after the *last* colon ---
const parts = pic.split(':');
pic = parts[parts.length - 1] || '';
// strip any stray leading colons
pic = pic.replace(/^:+/, '');
// ensure exactly one leading slash
if (pic && !pic.startsWith('/')) pic = '/' + pic;
return pic;
} catch (e) {
console.warn('fetchProfilePicture failed:', e);
return '';
}
}
export async function updateAuthenticatedUI(data) {
// Save latest auth data for later reuse
window.__lastAuthData = data;
// 1) Remove loading overlay safely
const loading = document.getElementById('loadingOverlay');
if (loading) loading.remove();
// 2) Show main UI
document.querySelector('.main-wrapper').style.display = '';
document.getElementById('loginForm').style.display = 'none';
toggleVisibility("loginForm", false);
toggleVisibility("mainOperations", true);
toggleVisibility("uploadFileForm", true);
toggleVisibility("fileListContainer", true);
attachEnterKeyListener("addUserModal", "saveUserBtn");
attachEnterKeyListener("removeUserModal", "deleteUserBtn");
attachEnterKeyListener("changePasswordModal", "saveNewPasswordBtn");
attachEnterKeyListener("removeUserModal", "deleteUserBtn");
attachEnterKeyListener("changePasswordModal","saveNewPasswordBtn");
document.querySelector(".header-buttons").style.visibility = "visible";
// 3) Persist auth flags (unchanged)
if (typeof data.totp_enabled !== "undefined") {
localStorage.setItem("userTOTPEnabled", data.totp_enabled ? "true" : "false");
}
@@ -199,64 +271,157 @@ function updateAuthenticatedUI(data) {
localStorage.setItem("username", data.username);
}
if (typeof data.folderOnly !== "undefined") {
localStorage.setItem("folderOnly", data.folderOnly ? "true" : "false");
localStorage.setItem("readOnly", data.readOnly ? "true" : "false");
localStorage.setItem("disableUpload", data.disableUpload ? "true" : "false");
localStorage.setItem("folderOnly", data.folderOnly ? "true" : "false");
localStorage.setItem("readOnly", data.readOnly ? "true" : "false");
localStorage.setItem("disableUpload",data.disableUpload? "true" : "false");
}
// 4) Fetch up-to-date profile picture — ALWAYS overwrite localStorage
const profilePicUrl = await fetchProfilePicture();
localStorage.setItem("profilePicUrl", profilePicUrl);
// 5) Build / update header buttons
const headerButtons = document.querySelector(".header-buttons");
const firstButton = headerButtons.firstElementChild;
const firstButton = headerButtons.firstElementChild;
// a) restore-from-trash for admins
if (data.isAdmin) {
let restoreBtn = document.getElementById("restoreFilesBtn");
if (!restoreBtn) {
restoreBtn = document.createElement("button");
restoreBtn.id = "restoreFilesBtn";
restoreBtn.classList.add("btn", "btn-warning");
restoreBtn.setAttribute("data-i18n-title", "trash_restore_delete");
restoreBtn.innerHTML = '<i class="material-icons">restore_from_trash</i>';
if (firstButton) insertAfter(restoreBtn, firstButton);
else headerButtons.appendChild(restoreBtn);
}
restoreBtn.style.display = "block";
let adminPanelBtn = document.getElementById("adminPanelBtn");
if (!adminPanelBtn) {
adminPanelBtn = document.createElement("button");
adminPanelBtn.id = "adminPanelBtn";
adminPanelBtn.classList.add("btn", "btn-info");
adminPanelBtn.setAttribute("data-i18n-title", "admin_panel");
adminPanelBtn.innerHTML = '<i class="material-icons">admin_panel_settings</i>';
insertAfter(adminPanelBtn, restoreBtn);
adminPanelBtn.addEventListener("click", openAdminPanel);
} else {
adminPanelBtn.style.display = "block";
let r = document.getElementById("restoreFilesBtn");
if (!r) {
r = document.createElement("button");
r.id = "restoreFilesBtn";
r.classList.add("btn","btn-warning");
r.setAttribute("data-i18n-title","trash_restore_delete");
r.innerHTML = '<i class="material-icons">restore_from_trash</i>';
if (firstButton) insertAfter(r, firstButton);
else headerButtons.appendChild(r);
}
r.style.display = "block";
} else {
const restoreBtn = document.getElementById("restoreFilesBtn");
if (restoreBtn) restoreBtn.style.display = "none";
const adminPanelBtn = document.getElementById("adminPanelBtn");
if (adminPanelBtn) adminPanelBtn.style.display = "none";
const r = document.getElementById("restoreFilesBtn");
if (r) r.style.display = "none";
}
if (window.location.hostname !== "demo.filerise.net") {
let userPanelBtn = document.getElementById("userPanelBtn");
if (!userPanelBtn) {
userPanelBtn = document.createElement("button");
userPanelBtn.id = "userPanelBtn";
userPanelBtn.classList.add("btn", "btn-user");
userPanelBtn.setAttribute("data-i18n-title", "user_panel");
userPanelBtn.innerHTML = '<i class="material-icons">account_circle</i>';
// b) admin panel button only on demo.filerise.net
if (data.isAdmin && window.location.hostname === "demo.filerise.net") {
let a = document.getElementById("adminPanelBtn");
if (!a) {
a = document.createElement("button");
a.id = "adminPanelBtn";
a.classList.add("btn","btn-info");
a.setAttribute("data-i18n-title","admin_panel");
a.innerHTML = '<i class="material-icons">admin_panel_settings</i>';
insertAfter(a, document.getElementById("restoreFilesBtn"));
a.addEventListener("click", openAdminPanel);
}
a.style.display = "block";
} else {
const a = document.getElementById("adminPanelBtn");
if (a) a.style.display = "none";
}
// c) user dropdown on non-demo
if (window.location.hostname !== "demo.filerise.net") {
let dd = document.getElementById("userDropdown");
// choose icon *or* img
const avatarHTML = profilePicUrl
? `<img src="${profilePicUrl}" style="width:24px;height:24px;border-radius:50%;vertical-align:middle;">`
: `<i class="material-icons">account_circle</i>`;
// fallback username if missing
const usernameText = data.username
|| localStorage.getItem("username")
|| "";
if (!dd) {
dd = document.createElement("div");
dd.id = "userDropdown";
dd.classList.add("user-dropdown");
// toggle button
const toggle = document.createElement("button");
toggle.id = "userDropdownToggle";
toggle.classList.add("btn","btn-user");
toggle.setAttribute("title", t("user_settings"));
toggle.innerHTML = `
${avatarHTML}
<span class="dropdown-username">${usernameText}</span>
<span class="dropdown-caret"></span>
`;
dd.append(toggle);
// menu
const menu = document.createElement("div");
menu.classList.add("user-menu");
menu.innerHTML = `
<div class="item" id="menuUserPanel">
<i class="material-icons folder-icon">person</i> ${t("user_panel")}
</div>
${data.isAdmin ? `
<div class="item" id="menuAdminPanel">
<i class="material-icons folder-icon">admin_panel_settings</i> ${t("admin_panel")}
</div>` : ''}
<div class="item" id="menuApiDocs">
<i class="material-icons folder-icon">description</i> ${t("api_docs")}
</div>
<div class="item" id="menuLogout">
<i class="material-icons folder-icon">logout</i> ${t("logout")}
</div>
`;
dd.append(menu);
// insert
const dm = document.getElementById("darkModeToggle");
if (dm) insertAfter(dd, dm);
else if (firstButton) insertAfter(dd, firstButton);
else headerButtons.appendChild(dd);
// open/close
toggle.addEventListener("click", e => {
e.stopPropagation();
menu.classList.toggle("show");
});
document.addEventListener("click", () => menu.classList.remove("show"));
// actions
document.getElementById("menuUserPanel")
.addEventListener("click", () => {
menu.classList.remove("show");
openUserPanel();
});
if (data.isAdmin) {
document.getElementById("menuAdminPanel")
.addEventListener("click", () => {
menu.classList.remove("show");
openAdminPanel();
});
}
document.getElementById("menuApiDocs")
.addEventListener("click", () => {
menu.classList.remove("show");
openApiModal();
});
document.getElementById("menuLogout")
.addEventListener("click", () => {
menu.classList.remove("show");
triggerLogout();
});
const adminBtn = document.getElementById("adminPanelBtn");
if (adminBtn) insertAfter(userPanelBtn, adminBtn);
else if (firstButton) insertAfter(userPanelBtn, firstButton);
else headerButtons.appendChild(userPanelBtn);
userPanelBtn.addEventListener("click", openUserPanel);
} else {
userPanelBtn.style.display = "block";
// update avatar & username only
const tog = dd.querySelector("#userDropdownToggle");
tog.innerHTML = `
${avatarHTML}
<span class="dropdown-username">${usernameText}</span>
<span class="dropdown-caret"></span>
`;
dd.style.display = "inline-block";
}
}
// 6) Finalize
initializeApp();
applyTranslations();
updateItemsPerPageSelect();
updateLoginOptionsUIFromStorage();
@@ -266,6 +431,12 @@ function checkAuthentication(showLoginToast = true) {
return sendRequest("/api/auth/checkAuth.php")
.then(data => {
if (data.setup) {
const overlay = document.getElementById('loadingOverlay');
if (overlay) overlay.remove();
// show the wrapper (so the login form can be visible)
document.querySelector('.main-wrapper').style.display = '';
document.getElementById('loginForm').style.display = 'none';
window.setupMode = true;
if (showLoginToast) showToast("Setup mode: No users found. Please add an admin user.");
toggleVisibility("loginForm", false);
@@ -277,11 +448,13 @@ function checkAuthentication(showLoginToast = true) {
}
window.setupMode = false;
if (data.authenticated) {
localStorage.setItem('isAdmin', data.isAdmin ? 'true' : 'false');
localStorage.setItem("folderOnly", data.folderOnly);
localStorage.setItem("readOnly", data.readOnly);
localStorage.setItem("disableUpload", data.disableUpload);
updateLoginOptionsUIFromStorage();
applyProxyBypassUI();
if (typeof data.totp_enabled !== "undefined") {
localStorage.setItem("userTOTPEnabled", data.totp_enabled ? "true" : "false");
}
@@ -292,8 +465,14 @@ function checkAuthentication(showLoginToast = true) {
updateAuthenticatedUI(data);
return data;
} else {
const overlay = document.getElementById('loadingOverlay');
if (overlay) overlay.remove();
// show the wrapper (so the login form can be visible)
document.querySelector('.main-wrapper').style.display = '';
document.getElementById('loginForm').style.display = '';
if (showLoginToast) showToast("Please log in to continue.");
toggleVisibility("loginForm", true);
toggleVisibility("loginForm", !(localStorage.getItem("authBypass") === "true"));
toggleVisibility("mainOperations", false);
toggleVisibility("uploadFileForm", false);
toggleVisibility("fileListContainer", false);
@@ -437,39 +616,54 @@ function initAuth() {
submitLogin(formData);
});
}
document.getElementById("addUserBtn").addEventListener("click", function () {
resetUserForm();
toggleVisibility("addUserModal", true);
document.getElementById("newUsername").focus();
});
document.getElementById("saveUserBtn").addEventListener("click", function () {
// remove your old saveUserBtn click-handler…
// instead:
const addUserForm = document.getElementById("addUserForm");
addUserForm.addEventListener("submit", function (e) {
e.preventDefault(); // stop the browser from reloading the page
const newUsername = document.getElementById("newUsername").value.trim();
const newPassword = document.getElementById("addUserPassword").value.trim();
const isAdmin = document.getElementById("isAdmin").checked;
if (!newUsername || !newPassword) {
showToast("Username and password are required!");
return;
}
let url = "/api/addUser.php";
if (window.setupMode) url += "?setup=1";
fetchWithCsrf(url, {
method: "POST",
credentials: "include",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username: newUsername, password: newPassword, isAdmin })
})
.then(response => response.json())
.then(r => r.json())
.then(data => {
if (data.success) {
showToast("User added successfully!");
closeAddUserModal();
checkAuthentication(false);
if (window.setupMode) {
toggleVisibility("loginForm", true);
}
} else {
showToast("Error: " + (data.error || "Could not add user"));
}
})
.catch(() => { });
.catch(() => {
showToast("Error: Could not add user");
});
});
document.getElementById("cancelUserBtn").addEventListener("click", closeAddUserModal);

File diff suppressed because it is too large Load Diff

View File

@@ -25,46 +25,74 @@ export function toggleAllCheckboxes(masterCheckbox) {
const checkboxes = document.querySelectorAll(".file-checkbox");
checkboxes.forEach(chk => {
chk.checked = masterCheckbox.checked;
updateRowHighlight(chk);
});
updateFileActionButtons(); // update buttons based on current selection
updateFileActionButtons();
}
export function updateFileActionButtons() {
const fileCheckboxes = document.querySelectorAll("#fileList .file-checkbox");
const selectedCheckboxes = document.querySelectorAll("#fileList .file-checkbox:checked");
const deleteBtn = document.getElementById("deleteSelectedBtn");
const copyBtn = document.getElementById("copySelectedBtn");
const moveBtn = document.getElementById("moveSelectedBtn");
const deleteBtn = document.getElementById("deleteSelectedBtn");
const zipBtn = document.getElementById("downloadZipBtn");
const extractZipBtn = document.getElementById("extractZipBtn");
const createBtn = document.getElementById("createBtn");
if (fileCheckboxes.length === 0) {
if (copyBtn) copyBtn.style.display = "none";
if (moveBtn) moveBtn.style.display = "none";
if (deleteBtn) deleteBtn.style.display = "none";
if (zipBtn) zipBtn.style.display = "none";
if (extractZipBtn) extractZipBtn.style.display = "none";
} else {
if (copyBtn) copyBtn.style.display = "inline-block";
if (moveBtn) moveBtn.style.display = "inline-block";
if (deleteBtn) deleteBtn.style.display = "inline-block";
if (zipBtn) zipBtn.style.display = "inline-block";
if (extractZipBtn) extractZipBtn.style.display = "inline-block";
const anyFiles = fileCheckboxes.length > 0;
const anySelected = selectedCheckboxes.length > 0;
const anyZip = Array.from(selectedCheckboxes)
.some(cb => cb.value.toLowerCase().endsWith(".zip"));
const anySelected = selectedCheckboxes.length > 0;
if (copyBtn) copyBtn.disabled = !anySelected;
if (moveBtn) moveBtn.disabled = !anySelected;
if (deleteBtn) deleteBtn.disabled = !anySelected;
if (zipBtn) zipBtn.disabled = !anySelected;
if (extractZipBtn) {
// Enable only if at least one selected file ends with .zip (case-insensitive).
const anyZipSelected = Array.from(selectedCheckboxes).some(chk =>
chk.value.toLowerCase().endsWith(".zip")
);
extractZipBtn.disabled = !anyZipSelected;
// — Select All checkbox sync (unchanged) —
const master = document.getElementById("selectAll");
if (master) {
if (selectedCheckboxes.length === fileCheckboxes.length) {
master.checked = true;
master.indeterminate = false;
} else if (selectedCheckboxes.length === 0) {
master.checked = false;
master.indeterminate = false;
} else {
master.checked = false;
master.indeterminate = true;
}
}
// Delete / Copy / Move: only show when something is selected
if (deleteBtn) {
deleteBtn.style.display = anySelected ? "" : "none";
}
if (copyBtn) {
copyBtn.style.display = anySelected ? "" : "none";
}
if (moveBtn) {
moveBtn.style.display = anySelected ? "" : "none";
}
// Download ZIP: only show when something is selected
if (zipBtn) {
zipBtn.style.display = anySelected ? "" : "none";
}
// Extract ZIP: only show when a selected file is a .zip
if (extractZipBtn) {
extractZipBtn.style.display = anyZip ? "" : "none";
}
// Create File: only show when nothing is selected
if (createBtn) {
createBtn.style.display = anySelected ? "none" : "";
}
// Finally disable the ones that are shown but shouldnt be clickable
if (deleteBtn) deleteBtn.disabled = !anySelected;
if (copyBtn) copyBtn.disabled = !anySelected;
if (moveBtn) moveBtn.disabled = !anySelected;
if (zipBtn) zipBtn.disabled = !anySelected;
if (extractZipBtn) extractZipBtn.disabled = !anyZip;
}
export function showToast(message, duration = 3000) {
@@ -162,9 +190,14 @@ export function buildFileTableRow(file, folderPath) {
} else if (/\.(mp3|wav|m4a|ogg|flac|aac|wma|opus)$/i.test(file.name)) {
previewIcon = `<i class="material-icons">audiotrack</i>`;
}
previewButton = `<button class="btn btn-sm btn-info preview-btn" data-preview-url="${folderPath + encodeURIComponent(file.name)}?t=${Date.now()}" data-preview-name="${safeFileName}">
${previewIcon}
</button>`;
previewButton = `<button
type="button"
class="btn btn-sm btn-info preview-btn"
data-preview-url="${folderPath + encodeURIComponent(file.name)}?t=${Date.now()}"
data-preview-name="${safeFileName}"
title="${t('preview')}">
${previewIcon}
</button>`;
}
return `
@@ -178,19 +211,44 @@ export function buildFileTableRow(file, folderPath) {
<td class="hide-small nowrap">${safeSize}</td>
<td class="hide-small hide-medium nowrap">${safeUploader}</td>
<td>
<div class="button-wrap" style="display: flex; justify-content: left; gap: 5px;">
<button type="button" class="btn btn-sm btn-success download-btn" data-download-name="${file.name}" data-download-folder="${file.folder || 'root'}" title="${t('download')}">
<div class="btn-group btn-group-sm" role="group" aria-label="File actions">
<button
type="button"
class="btn btn-sm btn-success download-btn"
data-download-name="${file.name}"
data-download-folder="${file.folder || 'root'}"
title="${t('download')}">
<i class="material-icons">file_download</i>
</button>
${file.editable ? `
<button class="btn btn-sm edit-btn" data-edit-name="${file.name}" data-edit-folder="${file.folder || 'root'}" title="${t('edit')}">
<i class="material-icons">edit</i>
</button>
` : ""}
<button
type="button"
class="btn btn-sm btn-secondary edit-btn"
data-edit-name="${file.name}"
data-edit-folder="${file.folder || 'root'}"
title="${t('edit')}">
<i class="material-icons">edit</i>
</button>` : ""}
${previewButton}
<button class="btn btn-sm btn-warning rename-btn" data-rename-name="${file.name}" data-rename-folder="${file.folder || 'root'}" title="${t('rename')}">
<button
type="button"
class="btn btn-sm btn-warning rename-btn"
data-rename-name="${file.name}"
data-rename-folder="${file.folder || 'root'}"
title="${t('rename')}">
<i class="material-icons">drive_file_rename_outline</i>
</button>
<!-- share -->
<button
type="button"
class="btn btn-secondary btn-sm share-btn ms-1"
data-file="${safeFileName}"
title="${t('share')}">
<i class="material-icons">share</i>
</button>
</div>
</td>
</tr>
@@ -271,8 +329,6 @@ export function toggleRowSelection(event, fileName) {
const start = Math.min(currentIndex, lastIndex);
const end = Math.max(currentIndex, lastIndex);
// If neither CTRL nor Meta is pressed, you might choose
// to clear existing selections. For this example we leave existing selections intact.
for (let i = start; i <= end; i++) {
const cb = allRows[i].querySelector(".file-checkbox");
if (cb) {

File diff suppressed because it is too large Load Diff

View File

@@ -76,6 +76,72 @@ export function handleDownloadZipSelected(e) {
}, 100);
};
export function handleCreateFileSelected(e) {
e.preventDefault(); e.stopImmediatePropagation();
const modal = document.getElementById('createFileModal');
modal.style.display = 'block';
setTimeout(() => {
const inp = document.getElementById('newFileCreateName');
if (inp) inp.focus();
}, 100);
}
/**
* Open the “New File” modal
*/
export function openCreateFileModal() {
const modal = document.getElementById('createFileModal');
const input = document.getElementById('createFileNameInput');
if (!modal || !input) {
console.error('Create-file modal or input not found');
return;
}
input.value = '';
modal.style.display = 'block';
setTimeout(() => input.focus(), 0);
}
export async function handleCreateFile(e) {
e.preventDefault();
const input = document.getElementById('createFileNameInput');
if (!input) return console.error('Create-file input missing');
const name = input.value.trim();
if (!name) {
showToast(t('newfile_placeholder')); // or a more explicit error
return;
}
const folder = window.currentFolder || 'root';
try {
const res = await fetch('/api/file/createFile.php', {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type':'application/json',
'X-CSRF-Token': window.csrfToken
},
// ⚠️ must send `name`, not `filename`
body: JSON.stringify({ folder, name })
});
const js = await res.json();
if (!js.success) throw new Error(js.error);
showToast(t('file_created'));
loadFileList(folder);
} catch (err) {
showToast(err.message || t('error_creating_file'));
} finally {
document.getElementById('createFileModal').style.display = 'none';
}
}
document.addEventListener('DOMContentLoaded', () => {
const cancel = document.getElementById('cancelCreateFile');
const confirm = document.getElementById('confirmCreateFile');
if (cancel) cancel.addEventListener('click', () => document.getElementById('createFileModal').style.display = 'none');
if (confirm) confirm.addEventListener('click', handleCreateFile);
});
export function openDownloadModal(fileName, folder) {
// Store file details globally for the download confirmation function.
window.singleFileToDownload = fileName;
@@ -197,6 +263,49 @@ document.addEventListener("DOMContentLoaded", () => {
const progressModal = document.getElementById("downloadProgressModal");
const cancelZipBtn = document.getElementById("cancelDownloadZip");
const confirmZipBtn = document.getElementById("confirmDownloadZip");
const cancelCreate = document.getElementById('cancelCreateFile');
if (cancelCreate) {
cancelCreate.addEventListener('click', () => {
document.getElementById('createFileModal').style.display = 'none';
});
}
const confirmCreate = document.getElementById('confirmCreateFile');
if (confirmCreate) {
confirmCreate.addEventListener('click', async () => {
const name = document.getElementById('newFileCreateName').value.trim();
if (!name) {
showToast(t('please_enter_filename'));
return;
}
document.getElementById('createFileModal').style.display = 'none';
try {
const res = await fetch('/api/file/createFile.php', {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': window.csrfToken
},
body: JSON.stringify({
folder: window.currentFolder || 'root',
filename: name
})
});
const js = await res.json();
if (!res.ok || !js.success) {
throw new Error(js.error || t('error_creating_file'));
}
showToast(t('file_created_successfully'));
loadFileList(window.currentFolder);
} catch (err) {
console.error(err);
showToast(err.message || t('error_creating_file'));
}
});
attachEnterKeyListener('createFileModal','confirmCreateFile');
}
// 1) Cancel button hides the name modal
if (cancelZipBtn) {
@@ -553,8 +662,14 @@ export function initFileActions() {
extractZipBtn.replaceWith(extractZipBtn.cloneNode(true));
document.getElementById("extractZipBtn").addEventListener("click", handleExtractZipSelected);
}
const createBtn = document.getElementById('createFileBtn');
if (createBtn) {
createBtn.replaceWith(createBtn.cloneNode(true));
document.getElementById('createFileBtn').addEventListener('click', openCreateFileModal);
}
}
// Hook up the singlefile download modal buttons
document.addEventListener("DOMContentLoaded", () => {
const cancelDownloadFileBtn = document.getElementById("cancelDownloadFile");
@@ -573,4 +688,35 @@ document.addEventListener("DOMContentLoaded", () => {
attachEnterKeyListener("downloadFileModal", "confirmSingleDownloadButton");
});
document.addEventListener('DOMContentLoaded', () => {
const btn = document.getElementById('createBtn');
const menu = document.getElementById('createMenu');
const fileOpt = document.getElementById('createFileOption');
const folderOpt= document.getElementById('createFolderOption');
// Toggle dropdown on click
btn.addEventListener('click', (e) => {
e.stopPropagation();
menu.style.display = menu.style.display === 'block' ? 'none' : 'block';
});
// Create File
fileOpt.addEventListener('click', () => {
menu.style.display = 'none';
openCreateFileModal(); // your existing function
});
// Create Folder
folderOpt.addEventListener('click', () => {
menu.style.display = 'none';
document.getElementById('createFolderModal').style.display = 'block';
document.getElementById('newFolderName').focus();
});
// Close if you click anywhere else
document.addEventListener('click', () => {
menu.style.display = 'none';
});
});
window.renameFile = renameFile;

View File

@@ -3,22 +3,146 @@ import { escapeHTML, showToast } from './domUtils.js';
import { loadFileList } from './fileListView.js';
import { t } from './i18n.js';
// thresholds for editor behavior
const EDITOR_PLAIN_THRESHOLD = 5 * 1024 * 1024; // >5 MiB => force plain text, lighter settings
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/";
const CM_LOCAL = "/vendor/codemirror/5.65.5/";
// Which mode file to load for a given name/mime
const MODE_URL = {
// core/common
"xml": "mode/xml/xml.min.js",
"css": "mode/css/css.min.js",
"javascript": "mode/javascript/javascript.min.js",
// meta / combos
"htmlmixed": "mode/htmlmixed/htmlmixed.min.js",
"application/x-httpd-php": "mode/php/php.min.js",
// docs / data
"markdown": "mode/markdown/markdown.min.js",
"yaml": "mode/yaml/yaml.min.js",
"properties": "mode/properties/properties.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_LOAD_TIMEOUT_MS = 2500; // allow closing immediately; don't wait forever
function loadScriptOnce(url) {
return new Promise((resolve, reject) => {
const ver = (window.APP_VERSION ?? 'dev').replace(/^v/, ''); // "v1.6.9" -> "1.6.9"
const withQS = url + '?v=' + ver;
const key = `cm:${withQS}`;
let s = document.querySelector(`script[data-key="${key}"]`);
if (s) {
if (s.dataset.loaded === "1") return resolve();
s.addEventListener("load", resolve);
s.addEventListener("error", () => reject(new Error(`Load failed: ${withQS}`)));
return;
}
s = document.createElement("script");
s.src = withQS;
s.async = true;
s.dataset.key = key;
s.addEventListener("load", () => { s.dataset.loaded = "1"; resolve(); });
s.addEventListener("error", () => reject(new Error(`Load failed: ${withQS}`)));
document.head.appendChild(s);
});
}
async function ensureModeLoaded(modeOption) {
if (!window.CodeMirror) return;
const name = normalizeModeName(modeOption);
if (!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 -> stay in text/plain
// Dependencies
if (name === "htmlmixed") {
await Promise.all([
ensureModeLoaded("xml"),
ensureModeLoaded("css"),
ensureModeLoaded("javascript")
]);
}
if (name === "application/x-httpd-php") {
await ensureModeLoaded("htmlmixed");
}
await loadScriptOnce(CM_LOCAL + url);
}
function getModeForFile(fileName) {
const ext = fileName.slice(fileName.lastIndexOf('.') + 1).toLowerCase();
const dot = fileName.lastIndexOf(".");
const ext = dot >= 0 ? fileName.slice(dot + 1).toLowerCase() : "";
switch (ext) {
case "css":
return "css";
case "json":
return { name: "javascript", json: true };
case "js":
return "javascript";
case "html":
case "htm":
return "text/html";
case "xml":
return "xml";
default:
return "text/plain";
case "htm": return "text/html";
case "xml": return "xml";
case "md":
case "markdown": return "markdown";
case "yml":
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";
case "ini":
case "conf":
case "config":
case "properties": return "properties";
case "c":
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 "kt":
case "kts": return "text/x-kotlin";
default: return "text/plain";
}
}
export { getModeForFile };
@@ -35,18 +159,16 @@ 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"
? "uploads/"
@@ -55,99 +177,162 @@ export function editFile(fileName, folder) {
fetch(fileUrl, { method: "HEAD" })
.then(response => {
const contentLength = response.headers.get("Content-Length");
if (contentLength !== null && parseInt(contentLength) > 10485760) {
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) {
showToast("This file is larger than 10 MB and cannot be edited in the browser.");
throw new Error("File too large.");
}
return fetch(fileUrl);
return response;
})
.then(() => fetch(fileUrl))
.then(response => {
if (!response.ok) {
throw new Error("HTTP error! Status: " + response.status);
}
return response.text();
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 => {
.then(([content, sizeBytes]) => {
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)}</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")}">&times;</button>
</div>
<button id="closeEditorX" class="editor-close-btn">&times;</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 mode = getModeForFile(fileName);
let canceled = false;
const doClose = () => {
canceled = true;
window.currentEditor = null;
modal.remove();
};
// 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);
const editor = CodeMirror.fromTextArea(document.getElementById("fileEditor"), {
lineNumbers: true,
mode: mode,
theme: theme,
viewportMargin: Infinity
});
// 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]);
window.currentEditor = editor;
// Start mode loading (dont block closing)
const modePromise = ensureModeLoaded(desiredMode);
setTimeout(() => {
adjustEditorSize();
}, 50);
// Wait up to MODE_LOAD_TIMEOUT_MS; then proceed with whatever is available
const timeout = new Promise((res) => setTimeout(res, MODE_LOAD_TIMEOUT_MS));
observeModalResize(modal);
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;
}
let currentFontSize = 14;
editor.getWrapperElement().style.fontSize = currentFontSize + "px";
editor.refresh();
const initialMode = (forcePlainText || !isModeRegistered()) ? "text/plain" : desiredMode;
const cmOptions = {
lineNumbers: !forcePlainText,
mode: initialMode,
theme,
viewportMargin: forcePlainText ? 20 : Infinity,
lineWrapping: false
};
document.getElementById("closeEditorX").addEventListener("click", function () {
modal.remove();
});
const editor = window.CodeMirror.fromTextArea(
document.getElementById("fileEditor"),
cmOptions
);
window.currentEditor = editor;
document.getElementById("decreaseFont").addEventListener("click", function () {
currentFontSize = Math.max(8, currentFontSize - 2);
editor.getWrapperElement().style.fontSize = currentFontSize + "px";
setTimeout(adjustEditorSize, 50);
observeModalResize(modal);
// Font controls (now that editor exists)
let currentFontSize = 14;
const wrapper = editor.getWrapperElement();
wrapper.style.fontSize = currentFontSize + "px";
editor.refresh();
decBtn.addEventListener("click", function () {
currentFontSize = Math.max(8, currentFontSize - 2);
wrapper.style.fontSize = currentFontSize + "px";
editor.refresh();
});
incBtn.addEventListener("click", function () {
currentFontSize = Math.min(32, currentFontSize + 2);
wrapper.style.fontSize = currentFontSize + "px";
editor.refresh();
});
// Save
const saveBtn = document.getElementById("saveBtn");
saveBtn.disabled = false;
saveBtn.addEventListener("click", function () {
saveFile(fileName, folderUsed);
});
// 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
});
});
document.getElementById("increaseFont").addEventListener("click", function () {
currentFontSize = Math.min(32, currentFontSize + 2);
editor.getWrapperElement().style.fontSize = currentFontSize + "px";
editor.refresh();
});
document.getElementById("saveBtn").addEventListener("click", function () {
saveFile(fileName, folderUsed);
});
document.getElementById("closeBtn").addEventListener("click", function () {
modal.remove();
});
function updateEditorTheme() {
const isDarkMode = document.body.classList.contains("dark-mode");
editor.setOption("theme", isDarkMode ? "material-darker" : "default");
}
document.getElementById("darkModeToggle").addEventListener("click", updateEditorTheme);
})
.catch(error => console.error("Error loading file:", error));
.catch(error => {
if (error && error.name === "AbortError") return;
console.error("Error loading file:", error);
});
}
export function saveFile(fileName, folder) {
const editor = window.currentEditor;
if (!editor) {

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
// fileMenu.js
import { updateRowHighlight, showToast } from './domUtils.js';
import { handleDeleteSelected, handleCopySelected, handleMoveSelected, handleDownloadZipSelected, handleExtractZipSelected, renameFile } from './fileActions.js';
import { handleDeleteSelected, handleCopySelected, handleMoveSelected, handleDownloadZipSelected, handleExtractZipSelected, renameFile, openCreateFileModal } from './fileActions.js';
import { previewFile } from './filePreview.js';
import { editFile } from './fileEditor.js';
import { canEditFile, fileData } from './fileListView.js';
@@ -75,6 +75,7 @@ export function fileListContextMenuHandler(e) {
const selected = Array.from(document.querySelectorAll("#fileList .file-checkbox:checked")).map(chk => chk.value);
let menuItems = [
{ label: t("create_file"), action: () => openCreateFileModal() },
{ label: t("delete_selected"), action: () => { handleDeleteSelected(new Event("click")); } },
{ label: t("copy_selected"), action: () => { handleCopySelected(new Event("click")); } },
{ label: t("move_selected"), action: () => { handleMoveSelected(new Event("click")); } },

View File

@@ -4,36 +4,68 @@ import { fileData } from './fileListView.js';
import { t } from './i18n.js';
export function openShareModal(file, folder) {
// Remove any existing modal
const existing = document.getElementById("shareModal");
if (existing) existing.remove();
// Build the modal
const modal = document.createElement("div");
modal.id = "shareModal";
modal.classList.add("modal");
modal.innerHTML = `
<div class="modal-content share-modal-content" style="width: 600px; max-width:90vw;">
<div class="modal-content share-modal-content" style="width:600px;max-width:90vw;">
<div class="modal-header">
<h3>${t("share_file")}: ${escapeHTML(file.name)}</h3>
<span class="close-image-modal" id="closeShareModal" title="Close">&times;</span>
<span id="closeShareModal" title="${t("close")}" class="close-image-modal">&times;</span>
</div>
<div class="modal-body">
<p>${t("set_expiration")}</p>
<select id="shareExpiration">
<option value="30">30 minutes</option>
<option value="60" selected>60 minutes</option>
<option value="120">120 minutes</option>
<option value="180">180 minutes</option>
<option value="240">240 minutes</option>
<option value="1440">1 Day</option>
<select id="shareExpiration" style="width:100%;padding:5px;">
<option value="30">30 ${t("minutes")}</option>
<option value="60" selected>60 ${t("minutes")}</option>
<option value="120">120 ${t("minutes")}</option>
<option value="180">180 ${t("minutes")}</option>
<option value="240">240 ${t("minutes")}</option>
<option value="1440">1 ${t("day")}</option>
<option value="custom">${t("custom")}&hellip;</option>
</select>
<p>${t("password_optional")}</p>
<input type="text" id="sharePassword" placeholder=${t("password_optional")} style="width: 100%;"/>
<br>
<button id="generateShareLinkBtn" class="btn btn-primary" style="margin-top:10px;">${t("generate_share_link")}</button>
<div id="shareLinkDisplay" style="margin-top: 10px; display:none;">
<div id="customExpirationContainer" style="display:none;margin-top:10px;">
<label for="customExpirationValue">${t("duration")}:</label>
<input type="number" id="customExpirationValue" min="1" value="1" style="width:60px;margin:0 8px;"/>
<select id="customExpirationUnit">
<option value="seconds">${t("seconds")}</option>
<option value="minutes" selected>${t("minutes")}</option>
<option value="hours">${t("hours")}</option>
<option value="days">${t("days")}</option>
</select>
<p class="share-warning" style="color:#a33;font-size:0.9em;margin-top:5px;">
${t("custom_duration_warning")}
</p>
</div>
<p style="margin-top:15px;">${t("password_optional")}</p>
<input
type="text"
id="sharePassword"
placeholder="${t("password_optional")}"
style="width:100%;padding:5px;"
/>
<button
id="generateShareLinkBtn"
class="btn btn-primary"
style="margin-top:15px;"
>
${t("generate_share_link")}
</button>
<div id="shareLinkDisplay" style="margin-top:15px;display:none;">
<p>${t("shareable_link")}</p>
<input type="text" id="shareLinkInput" readonly style="width:100%;"/>
<button id="copyShareLinkBtn" class="btn btn-primary" style="margin-top:5px;">${t("copy_link")}</button>
<input type="text" id="shareLinkInput" readonly style="width:100%;padding:5px;"/>
<button id="copyShareLinkBtn" class="btn btn-secondary" style="margin-top:5px;">
${t("copy_link")}
</button>
</div>
</div>
</div>
@@ -41,52 +73,72 @@ export function openShareModal(file, folder) {
document.body.appendChild(modal);
modal.style.display = "block";
document.getElementById("closeShareModal").addEventListener("click", () => {
modal.remove();
});
// Close handler
document.getElementById("closeShareModal")
.addEventListener("click", () => modal.remove());
document.getElementById("generateShareLinkBtn").addEventListener("click", () => {
const expiration = document.getElementById("shareExpiration").value;
const password = document.getElementById("sharePassword").value;
fetch("/api/file/createShareLink.php", {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
"X-CSRF-Token": window.csrfToken
},
body: JSON.stringify({
folder: folder,
file: file.name,
expirationMinutes: parseInt(expiration),
password: password
// Show/hide custom-duration inputs
document.getElementById("shareExpiration")
.addEventListener("change", e => {
const container = document.getElementById("customExpirationContainer");
container.style.display = e.target.value === "custom" ? "block" : "none";
});
// Generate share link
document.getElementById("generateShareLinkBtn")
.addEventListener("click", () => {
const sel = document.getElementById("shareExpiration");
let value, unit;
if (sel.value === "custom") {
value = parseInt(document.getElementById("customExpirationValue").value, 10);
unit = document.getElementById("customExpirationUnit").value;
} else {
value = parseInt(sel.value, 10);
unit = "minutes";
}
const password = document.getElementById("sharePassword").value;
fetch("/api/file/createShareLink.php", {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/json",
"X-CSRF-Token": window.csrfToken
},
body: JSON.stringify({
folder,
file: file.name,
expirationValue: value,
expirationUnit: unit,
password
})
})
})
.then(response => response.json())
.then(res => res.json())
.then(data => {
if (data.token) {
const shareEndpoint = `${window.location.origin}/api/file/share.php`;
const shareUrl = `${shareEndpoint}?token=${encodeURIComponent(data.token)}`;
const displayDiv = document.getElementById("shareLinkDisplay");
const inputField = document.getElementById("shareLinkInput");
inputField.value = shareUrl;
displayDiv.style.display = "block";
const url = `${window.location.origin}/api/file/share.php?token=${encodeURIComponent(data.token)}`;
document.getElementById("shareLinkInput").value = url;
document.getElementById("shareLinkDisplay").style.display = "block";
} else {
showToast("Error generating share link: " + (data.error || "Unknown error"));
showToast(t("error_generating_share") + ": " + (data.error||"Unknown"));
}
})
.catch(err => {
console.error("Error generating share link:", err);
showToast("Error generating share link.");
console.error(err);
showToast(t("error_generating_share"));
});
});
});
document.getElementById("copyShareLinkBtn").addEventListener("click", () => {
const input = document.getElementById("shareLinkInput");
input.select();
document.execCommand("copy");
showToast("Link copied to clipboard!");
});
// Copy to clipboard
document.getElementById("copyShareLinkBtn")
.addEventListener("click", () => {
const input = document.getElementById("shareLinkInput");
input.select();
document.execCommand("copy");
showToast(t("link_copied"));
});
}
export function previewFile(fileUrl, fileName) {
@@ -364,16 +416,21 @@ export function previewFile(fileUrl, fileName) {
}
} else {
// Handle non-image file previews.
if (extension === "pdf") {
const embed = document.createElement("embed");
const separator = fileUrl.indexOf('?') === -1 ? '?' : '&';
embed.src = fileUrl + separator + 't=' + new Date().getTime();
embed.type = "application/pdf";
embed.style.width = "80vw";
embed.style.height = "80vh";
embed.style.border = "none";
container.appendChild(embed);
} else if (/\.(mp4|mkv|webm|mov|ogv)$/i.test(fileName)) {
if (extension === "pdf") {
// build a cachebusted URL
const separator = fileUrl.includes('?') ? '&' : '?';
const urlWithTs = fileUrl + separator + 't=' + Date.now();
// open in a new tab (avoids CSP frame-ancestors)
window.open(urlWithTs, "_blank");
// tear down the just-created modal
const modal = document.getElementById("filePreviewModal");
if (modal) modal.remove();
// stop further preview logic
return;
} else if (/\.(mp4|mkv|webm|mov|ogv)$/i.test(fileName)) {
const video = document.createElement("video");
video.src = fileUrl;
video.controls = true;

View File

@@ -13,10 +13,19 @@ export function openTagModal(file) {
modal.id = 'tagModal';
modal.className = 'modal';
modal.innerHTML = `
<div class="modal-content" style="width: 400px; max-width:90vw;">
<div class="modal-content" style="width: 450px; max-width:90vw;">
<div class="modal-header" style="display:flex; justify-content:space-between; align-items:center;">
<h3 style="margin:0;">${t("tag_file")}: ${file.name}</h3>
<span id="closeTagModal" style="cursor:pointer; font-size:24px;">&times;</span>
<h3 style="
margin:0;
display:inline-block;
max-width: calc(100% - 40px);
overflow:hidden;
text-overflow:ellipsis;
white-space:nowrap;
">
${t("tag_file")}: ${escapeHTML(file.name)}
</h3>
<span id="closeTagModal" class="editor-close-btn">&times;</span>
</div>
<div class="modal-body" style="margin-top:10px;">
<label for="tagNameInput">${t("tag_name")}</label>
@@ -83,10 +92,10 @@ export function openMultiTagModal(files) {
modal.id = 'multiTagModal';
modal.className = 'modal';
modal.innerHTML = `
<div class="modal-content" style="width: 400px; max-width:90vw;">
<div class="modal-content" style="width: 450px; max-width:90vw;">
<div class="modal-header" style="display:flex; justify-content:space-between; align-items:center;">
<h3 style="margin:0;">Tag Selected Files (${files.length})</h3>
<span id="closeMultiTagModal" style="cursor:pointer; font-size:24px;">&times;</span>
<span id="closeMultiTagModal" class="editor-close-btn">&times;</span>
</div>
<div class="modal-body" style="margin-top:10px;">
<label for="multiTagNameInput">Tag Name:</label>

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More