# CloudVault Enterprise Platform: Complete Documentation & User Guide

---

## 1. Executive Overview & System Architecture

**CloudVault** is an enterprise-grade, self-hosted document cloud and team collaboration platform built with **PHP 8.2+**, **MySQL 8+ / MariaDB**, **Vanilla JavaScript (ES6+)**, and **CSS3 (Google Material 3 design system)**. It delivers a modern Google Drive-like document management experience with strict zero-trust security, Role-Based and Attribute-Based Access Control (RBAC/ABAC), cryptographic checksum tracking, and resumable chunked file transfers.

### Architecture Highlights
- **Zero External Dependencies**: Pure PHP core with PDO, custom MVC router, and lightweight Vanilla JS frontend.
- **Strict Data/Storage Decoupling**: Database stores file metadata (`sha256`, `mime_type`, `size`, `uuid`, permissions), while physical file contents reside in a protected storage directory outside the public web root (`/storage/files/`).
- **Dynamic Deployment**: Automatic `BASE_URL` detection supporting shared hosting (cPanel/WHM), VPS, Apache, Nginx, and cloud container environments.

---

## 2. Key Advantages & Competitive Features

1. **Pixel-Perfect Google Drive Material 3 Interface**:
   - Elevated `+ New` floating pill button.
   - Pill search bar (`Search in Drive`) with advanced filter popovers.
   - Segmented view toggling between **List View (`≡`)** and **Grid View (`::`)**.
   - Dynamic floating **Selection Action Toolbar** (`✦ Ask Gemini`, Share, Download, Move, Bin, Link).
   - Multi-level context popover submenus (`Open with`, `Share`, `Organise`, `File information`).
   - Right Workspace Dock panel (Calendar, Keep, Tasks, Contacts).

2. **Enterprise Data Security**:
   - Cryptographic SHA-256 file hashing for deduplication and integrity validation.
   - Prepared PDO statements everywhere (zero SQL injection risks).
   - CSRF protection (`X-CSRF-TOKEN`) and HttpOnly SameSite secure session cookies.
   - MIME type verification using server-side `finfo` (ignores browser spoofing).
   - Executable script upload blocking (`.php`, `.exe`, `.sh`, `.bat`, etc.).

3. **High-Performance Resumable Uploads & Streaming**:
   - Chunked upload engine handling large files (1GB up to 20GB+).
   - Seekable HTTP Range video/audio streaming (`206 Partial Content`) with permission enforcement on every chunk.
   - `X-Sendfile` / `X-Accel-Redirect` acceleration support.

4. **Granular Collaboration & Access Control**:
   - Multi-tier permissions (`can_view`, `can_download`, `can_edit`, `can_delete`, `can_share`, `can_upload`).
   - Inherited folder permissions with explicit child file overrides.
   - Public tokenized 128-char share links with optional passwords, expiration dates, and max download counts.

---

## 3. System Directory & File Structure

```
cloudvault/
├── app/
│   ├── Config/
│   │   └── Database.php          # PDO singleton connection manager
│   ├── Controllers/
│   │   ├── AdminController.php   # System metrics, user management, audit logs, CSV exports
│   │   ├── AuthController.php    # Authentication, sessions, 2FA, password management
│   │   ├── FileController.php    # Uploads, downloads, streaming, trash, search, move/copy
│   │   ├── FolderController.php  # Folder hierarchy, zip downloads, permissions
│   │   ├── ShareController.php   # Internal sharing and public link generation
│   │   ├── VersionController.php # Revision history & restoration
│   │   ├── CommentController.php # File commenting system
│   │   ├── GroupController.php   # Team & group management
│   │   └── DepartmentController.php # Department administration
│   ├── Middleware/
│   │   ├── AuthMiddleware.php    # Session/API token authentication verifier
│   │   └── CsrfMiddleware.php    # CSRF token validator
│   ├── Models/
│   │   ├── File.php, Folder.php, User.php, Share.php
│   └── Services/
│       ├── AccessControlService.php # Central ACL engine (RBAC/ABAC)
│       ├── LocalStorage.php         # Physical storage manager
│       ├── ActivityService.php      # Activity & audit log recorder
│       ├── SettingsService.php      # System settings store
│       └── CronService.php          # Scheduled trash cleanup & link expiry
├── database/
│   └── migrations/
│       └── 01_initialize_schema.sql # 28 relational database tables
├── public/
│   ├── index.php                 # Front controller & BASE_URL auto-detection
│   ├── manifest.json             # PWA Web App Manifest
│   ├── sw.js                     # Progressive Web App Service Worker
│   └── assets/
│       ├── css/style.css         # Google Material 3 stylesheet
│       └── js/app.js             # SPA frontend logic & context menus
├── routes/
│   └── api.php                   # REST API routes map
├── views/
│   └── app.php                   # Main Google Drive HTML UI template
└── .env                          # Configuration settings & secrets
```

---

## 4. User Roles & Permission Hierarchy

CloudVault enforces a 6-tier role model:

1. **Super Administrator**:
   - Complete system access across all departments, users, settings, and storage.
   - Can perform system health scans, storage integrity checks, user offboarding, and ownership transfers.

2. **Administrator**:
   - Manages organisation users, storage quotas, groups, and audit logs.

3. **Department Administrator**:
   - Manages assigned department users, department folders, and department storage policies.

4. **Group Administrator**:
   - Manages assigned team/project groups, group members, and group shared drives.

5. **Standard User**:
   - Manages personal "My Drive", uploads files, creates folders, shares items, and collaborates with authorized teams.

6. **Viewer**:
   - Read-only access to view and preview shared items. Download capability is subject to explicit permission grants.

---

## 5. Complete Feature & Functionality Breakdown

### File Management & Storage
- **Upload & Resumable Uploads**: Single file, folder drag-and-drop, and automatic chunking for files >200MB.
- **File Previewer**: Built-in inline player for Images, Videos (with seeking), Audio, PDFs, Text files, and Office documents.
- **File Details Panel**: Inspect metadata, SHA-256 hash, creation/modification dates, file size, owner info, tags, and version history.
- **Trash & Soft-Delete**: Soft-delete items to trash with configurable auto-purge retention policies (default: 30 days).

### Sharing & Collaboration
- **Internal Sharing**: Share files/folders with individual users, groups, or departments with custom permissions (`can_view`, `can_download`, `can_edit`).
- **Public Secure Share Links**: Generate cryptographically secure share URLs (`/share/{token}`) protected by optional passwords, expiration dates, and download limits.
- **Comments & Shortcuts**: Post contextual comments on files and create shortcuts across folder trees without duplicating file contents.

### System Security & Maintenance
- **Storage Integrity Scan**: Automated scan detecting missing files, orphaned physical files, broken references, and checksum mismatches.
- **User Offboarding**: Single-step user offboarding that revokes sessions, revokes API tokens, suspends account access, removes group memberships, and transfers file ownership to a designated administrator.
- **Immutable Audit Logs**: Logs all sensitive administrative actions (e.g., user deletion, settings changes, ownership transfer) with IP addresses and timestamps.

---

## 6. Comprehensive Administrator Manual & Guide

### A. Accessing Admin Controls
1. Log in with an account assigned the **Super Administrator** or **Administrator** role.
2. Click the **Settings (`⚙️`)** icon in the header or navigate to `/api/admin/stats`.

### B. Managing Users & Storage Quotas
1. **Create User**:
   - Endpoint: `POST /api/admin/users`
   - Inputs: Email, Password, First Name, Last Name, Role, Department.
2. **Set User Quota**:
   - Endpoint: `PATCH /api/admin/users/{uuid}`
   - Input: `storage_quota` (bytes, e.g. `10737418240` for 10GB).
3. **Suspend / Activate User**:
   - Click user status toggle or invoke `POST /api/admin/users/{uuid}/suspend`. Instantly revokes active user sessions.

### C. Executing User Offboarding & Ownership Transfer
1. **Transfer Ownership**:
   - Endpoint: `POST /api/admin/users/{uuid}/transfer-ownership`
   - Body: `{"target_user_uuid": "TARGET_USER_UUID"}`
   - Reassigns all file and folder records from Source User to Target User instantly without copying physical files.
2. **Complete User Offboarding**:
   - Endpoint: `POST /api/admin/users/{uuid}/offboard`
   - Body: `{"transfer_to_uuid": "ADMIN_UUID"}`
   - Automatically:
     1. Clears active sessions (`user_sessions`).
     2. Revokes API access tokens (`api_tokens`).
     3. Suspends user status to `suspended`.
     4. Removes user from all assigned groups (`group_members`).
     5. Reassigns file/folder ownership to designated target user.

### D. Running Storage Integrity & CSV Reports
1. **Run Integrity Check ("Scan Storage")**:
   - Endpoint: `GET /api/admin/integrity`
   - Scans physical storage directory against database records and reports missing or orphaned files.
2. **Export CSV Reports**:
   - Endpoint: `GET /api/admin/reports/export?type=users` (Types: `users`, `departments`, `categories`).
   - Downloads an Excel-compatible CSV report.

---

## 7. Department & Group Admin Guide

### Department Management
- Department admins can manage users within their department, review department storage consumption, and create **Department Drives** accessible to all department members.

### Group & Team Management
- Create project or team groups (e.g. "Finance Team", "Media Production").
- Add or remove group members via `POST /api/groups/{uuid}/members`.
- Grant folder permissions to entire groups simultaneously (`folder_permissions` with `group_id`).

---

## 8. Standard User Manual & How-to Guide

### A. Uploading Files & Creating Folders
- **Create Folder**: Click elevated **`+ New`** button $\rightarrow$ Select **New folder** $\rightarrow$ Enter name $\rightarrow$ Click **Create**.
- **Upload File**: Drag files directly into the view area OR click **`+ New`** $\rightarrow$ **File upload**.

### B. Selection & Multi-Item Actions
- Click a file row or card to select it (hold `Ctrl` or `Cmd` for multi-selection).
- The floating **Selection Action Toolbar** will appear at the top:
  - **`✦ Ask Gemini`**: Trigger AI file assistant.
  - **`👤+` Share**: Open share dialog.
  - **`⬇` Download**: Download single file or zip package of selected items.
  - **`📁` Move**: Relocate items to another folder.
  - **`🗑️` Move to bin**: Soft-delete items to Trash.
  - **`🔗` Copy link**: Copy public share URL.

### C. Viewing & Context Submenus
- Right-click any file or folder to trigger the Material 3 context menu:
  - **`Open with`** $\rightarrow$ Select **Preview** (inline viewer) or **Open in new tab**.
  - **`Share`** $\rightarrow$ Select **Share** or **Copy link**.
  - **`Organise`** $\rightarrow$ Select **Move**, **Add shortcut**, or **Add to starred**.
  - **`File information`** $\rightarrow$ Select **Details** or **Version history**.

---

## 9. Google Drive Material 3 UI Navigation Guide

| UI Element | Location | Description & Functionality |
| :--- | :--- | :--- |
| **Elevated `+ New` Pill** | Top Left Sidebar | Floating white pill button to trigger file upload, folder upload, or folder creation. |
| **Pill Search Bar** | Top Center | Search input (`Search in Drive`) with right-side filter options icon (`🎛️`). |
| **View Mode Toggle** | Top Right Header | Segmented control switching between **List View (`≡`)** and **Grid View (`::`)**. |
| **Promotional Banner** | Main Top Content | Blue announcement banner highlighting features with quick action buttons. |
| **Storage Meter Widget** | Bottom Left Sidebar | Real-time visual progress bar (`11.15 GB of 15 GB used`) with **Get more storage** button. |
| **Right Workspace Dock** | Far Right Panel | Toolbar providing quick access to Calendar, Keep, Tasks, Contacts, and Add-ons. |

---

## 10. Installation, Deployment & Operations Guide

### Requirements
- PHP 8.2+ (Extensions: `pdo_mysql`, `fileinfo`, `openssl`, `gd`, `mbstring`, `json`, `zip`).
- MySQL 8.0+ or MariaDB 10.5+.
- Apache with `mod_rewrite` enabled OR Nginx.

### Step-by-Step Installation
1. **Clone Repository**:
   Place code in your web directory (e.g. `c:\xampp\htdocs\cloudvault` or `/var/www/cloudvault`).
2. **Database Setup**:
   Import `database/migrations/01_initialize_schema.sql` into your MySQL database.
3. **Environment Configuration**:
   Copy `.env.example` to `.env` and fill credentials:
   ```env
   APP_NAME="CloudVault"
   DB_HOST="127.0.0.1"
   DB_NAME="cloudvault"
   DB_USER="root"
   DB_PASS="secret"
   STORAGE_DIR="../storage"
   ```
4. **Directory Permissions**:
   Ensure `storage/` and `storage/files/` directories are writable by the web server (`chmod 775`).
5. **Cron Job Configuration (cPanel / Linux)**:
   Add a 15-minute cron job to purge expired links and trash:
   ```bash
   */15 * * * * curl -s "https://yourdomain.com/cron.php?task=all&token=YOUR_CRON_TOKEN" >/dev/null 2>&1
   ```
