init backend presensi

This commit is contained in:
mwpn
2026-03-05 14:37:36 +07:00
commit b4fda6b9c9
319 changed files with 27261 additions and 0 deletions

126
.gitignore vendored Normal file
View File

@@ -0,0 +1,126 @@
#-------------------------
# Operating Specific Junk Files
#-------------------------
# OS X
.DS_Store
.AppleDouble
.LSOverride
# OS X Thumbnails
._*
# Windows image file caches
Thumbs.db
ehthumbs.db
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msm
*.msp
# Windows shortcuts
*.lnk
# Linux
*~
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
#-------------------------
# Environment Files
#-------------------------
# These should never be under version control,
# as it poses a security risk.
.env
.vagrant
Vagrantfile
#-------------------------
# Temporary Files
#-------------------------
writable/cache/*
!writable/cache/index.html
writable/logs/*
!writable/logs/index.html
writable/session/*
!writable/session/index.html
writable/uploads/*
!writable/uploads/index.html
writable/debugbar/*
!writable/debugbar/index.html
php_errors.log
#-------------------------
# User Guide Temp Files
#-------------------------
user_guide_src/build/*
user_guide_src/cilexer/build/*
user_guide_src/cilexer/dist/*
user_guide_src/cilexer/pycilexer.egg-info/*
#-------------------------
# Test Files
#-------------------------
tests/coverage*
# Don't save phpunit under version control.
phpunit
#-------------------------
# Composer
#-------------------------
vendor/
#-------------------------
# IDE / Development Files
#-------------------------
# Modules Testing
_modules/*
# phpenv local config
.php-version
# Jetbrains editors (PHPStorm, etc)
.idea/
*.iml
# NetBeans
/nbproject/
/build/
/nbbuild/
/dist/
/nbdist/
/nbactions.xml
/nb-configuration.xml
/.nb-gradle/
# Sublime Text
*.tmlanguage.cache
*.tmPreferences.cache
*.stTheme.cache
*.sublime-workspace
*.sublime-project
.phpintel
/api/
# Visual Studio Code
.vscode/
/results/
/phpunit*.xml

68
ACADEMIC_MASTER_AUDIT.md Normal file
View File

@@ -0,0 +1,68 @@
# Academic Master Audit
**Date:** 2026-02-22
## STEP 1 — AUDIT EXISTING FEATURES
| # | Item | Status | Notes |
|---|------|--------|-------|
| 1 | SubjectModel exists | **OK** | `App\Modules\Academic\Models\SubjectModel` |
| 2 | Subject CRUD API | **Exists but incomplete** | GET only; no POST/PUT/DELETE. No `code` field in DB. |
| 3 | Dashboard page for Subjects | **Missing** | No route `/dashboard/academic/subjects` |
| 4 | Teacher management page | **Missing** | No `/dashboard/academic/teachers` |
| 5 | Users (GURU_MAPEL/WALI_KELAS) manageable via UI | **Missing** | GET /api/users?role= exists; no POST/PUT/DELETE for users; no UI |
| 6 | Lesson Slots page in dashboard | **Missing** | Full CRUD API exists; no dashboard page |
| 7 | Schedule Builder linked from settings | **Missing** | No Academic Settings hub; Schedule Builder only in sidebar |
| 8 | Navigation menu groups academic features | **Exists but incomplete** | Only Classes + Schedule Builder under ADMIN; no group label, no Settings/Subjects/Teachers/Lesson Slots |
---
## Summary (after implementation)
- **OK:** SubjectModel, Classes page, Schedule Builder API & page, Lesson Slots API.
- **Incomplete:** Subject API (GET only), Sidebar (no grouping, missing links).
- **Missing:** Academic Settings hub, Subjects dashboard page, Teachers dashboard + user CRUD API, Lesson Slots dashboard page, Sidebar Academic group with all links.
---
## STEP 6 — IMPLEMENTATION SUMMARY
### What was added
1. **Academic Settings Hub**
- Route: `GET /dashboard/academic/settings` (filter: `dashboard_admin_page`)
- View: `app/Views/dashboard/academic_settings.php` — card grid linking to Classes, Subjects, Teachers, Lesson Slots, Schedule Builder
2. **Subject management (full)**
- Migration: `AddCodeToSubjectsTable` — added `code` VARCHAR(50) NULL to `subjects`
- SubjectModel + Subject entity: added `code` to allowedFields and validation (optional)
- API: `POST /api/academic/subjects`, `PUT /api/academic/subjects/{id}`, `DELETE /api/academic/subjects/{id}`
- Dashboard: `GET /dashboard/academic/subjects`, view `dashboard/subjects.php` — table (Name, Code, Actions), Add/Edit modal, Delete confirm, vanilla JS fetch
3. **Teacher management**
- API: `GET /api/academic/teachers` — list users with role GURU_MAPEL or WALI_KELAS (with role names)
- API: `POST /api/users` (body: name, email, password, role_code), `PUT /api/users/{id}`, `DELETE /api/users/{id}` — admin_only
- Dashboard: `GET /dashboard/academic/teachers`, view `dashboard/teachers.php` — list (name, email, role), Add/Edit (name, email, password, role), Delete confirm
4. **Lesson Slots dashboard page**
- Route: `GET /dashboard/academic/lesson-slots`
- View: `dashboard/lesson_slots.php` — table (No, Jam Mulai, Jam Selesai, Actions), Add/Edit modal, Delete confirm; uses existing `/api/academic/lesson-slots` CRUD
5. **Sidebar (Academic group)**
- Group label "Academic" (ADMIN only)
- Links: Settings, Classes, Students, Subjects, Teachers, Lesson Slots, Schedule Builder
- Students still points to `#` (no page yet)
### What was fixed
- Subject API completed with create/update/delete and optional `code` field.
- Navigation: academic features grouped under "Academic" with all management links.
### What was already existing
- SubjectModel, Subject entity, GET /api/academic/subjects.
- Classes: full CRUD API and dashboard page.
- Lesson Slots: full CRUD API (no dashboard page before).
- Schedule Builder: route and page; now linked from Settings hub and sidebar.
- GET /api/users?role= for listing by role.
- Attendance logic, ScheduleResolver, RBAC — not modified.

62
DAPODIK_SYNC_AUDIT.md Normal file
View File

@@ -0,0 +1,62 @@
# Dapodik Sync — Pre-Implementation Audit
| # | Item | Status | Notes |
|---|------|--------|-------|
| 1 | Students dashboard page + API | **EXISTS** | GET/POST/PUT/DELETE /api/academic/students; GET /dashboard/academic/students |
| 2 | Existing Dapodik service code | **MISSING** | No DapodikClient or sync logic; only comments in migrations/model |
| 3 | Existing mapping table | **MISSING** | No dapodik_rombel_mappings or similar |
| 4 | Settings page link for Dapodik | **MISSING** | No Dapodik card in Academic Settings hub |
**Summary:** Students management exists and is ready. Dapodik integration (client, mapping table, settings link) is missing and will be implemented.
---
## Implemented (post-implementation)
- Migration `dapodik_rombel_mappings`, DapodikClient, DapodikSyncService, DapodikSyncController, dashboard Dapodik page, Students UNMAPPED badge + filter.
### Required .env (add to backend/.env)
```
DAPODIK_BASE_URL=http://192.168.7.5:5774/WebService
DAPODIK_TOKEN=bt5ON1LZPSsaJ6h
DAPODIK_NPSN=20227474
```
### Brief test steps
**1) cURL — Sync (requires valid token + base URL)**
```bash
# Login as ADMIN first; use session cookie or pass auth.
curl -X POST "http://localhost/sman1/backend/public/api/academic/dapodik/sync/students" \
-H "Content-Type: application/json" \
-H "X-Requested-With: XMLHttpRequest" \
-d "{\"limit\":50,\"max_pages\":2}" \
--cookie "ci_session=YOUR_SESSION"
```
**2) cURL — List rombel mappings**
```bash
curl "http://localhost/sman1/backend/public/api/academic/dapodik/rombels" \
-H "X-Requested-With: XMLHttpRequest" \
--cookie "ci_session=YOUR_SESSION"
```
**3) cURL — Update mapping**
```bash
curl -X PUT "http://localhost/sman1/backend/public/api/academic/dapodik/rombels/1" \
-H "Content-Type: application/json" \
-H "X-Requested-With: XMLHttpRequest" \
-d "{\"class_id\":1}" \
--cookie "ci_session=YOUR_SESSION"
```
**4) UI**
- Login as ADMIN → Academic → Settings → open **Dapodik** card.
- Click **Jalankan Sinkronisasi**; check summary in pre block and toast.
- In **Mapping Rombel**, set "Kelas (internal)" and click **Simpan** per row; toggle **Hanya unmapped**.
- Go to **Siswa** → tick **Hanya unmapped** to see only unmapped students; confirm **UNMAPPED** badge in Kelas column when class_id is null.

227
DASHBOARD_FEATURE_AUDIT.md Normal file
View File

@@ -0,0 +1,227 @@
# Full Dashboard Feature Audit Summary
**Goal:** Understand why only a few menus appear in the dashboard UI even though many modules exist.
---
## 1. LIST ALL EXISTING DASHBOARD PAGES
**Sources scanned:** `app/Config/Routes.php`, all `app/Modules/*/Routes.php`, `DashboardPageController`, `DashboardAcademicController`, any controller rendering `layouts/main`.
**Finding:** All dashboard **web** routes are defined in `app/Config/Routes.php` only. No module defines HTML page routes; modules define only API routes.
| # | route | controller | view | required_filter | roles_allowed_if_known |
|---|--------|------------|------|------------------|------------------------|
| 1 | `GET /dashboard` | `DashboardPageController::index` | `dashboard/index` | `dashboard_page_auth` | Any authenticated user |
| 2 | `GET /dashboard/attendance/report/(:num)` | `DashboardPageController::attendanceReport` | `dashboard/attendance_report` | `dashboard_page_auth` | Any authenticated user |
| 3 | `GET /dashboard/schedule/today` | `DashboardPageController::scheduleToday` | `dashboard/schedule_today` | `dashboard_page_auth` | Any authenticated user |
| 4 | `GET /dashboard/academic/schedule-builder/(:num)` | `DashboardAcademicController::scheduleBuilder` | `dashboard/schedule_builder` | `dashboard_admin_page` | **ADMIN only** |
**JSON output (as requested):**
```json
[
{
"route": "GET /dashboard",
"controller": "DashboardPageController::index",
"view": "dashboard/index",
"required_filter": "dashboard_page_auth",
"roles_allowed_if_known": "any authenticated"
},
{
"route": "GET /dashboard/attendance/report/(:num)",
"controller": "DashboardPageController::attendanceReport",
"view": "dashboard/attendance_report",
"required_filter": "dashboard_page_auth",
"roles_allowed_if_known": "any authenticated"
},
{
"route": "GET /dashboard/schedule/today",
"controller": "DashboardPageController::scheduleToday",
"view": "dashboard/schedule_today",
"required_filter": "dashboard_page_auth",
"roles_allowed_if_known": "any authenticated"
},
{
"route": "GET /dashboard/academic/schedule-builder/(:num)",
"controller": "DashboardAcademicController::scheduleBuilder",
"view": "dashboard/schedule_builder",
"required_filter": "dashboard_admin_page",
"roles_allowed_if_known": "ADMIN"
}
]
```
---
## 2. LIST ALL DASHBOARD API ENDPOINTS
**Sources:** `app/Modules/Dashboard/Routes.php`, `app/Modules/Attendance/Routes.php`, `app/Modules/Academic/Routes.php`, `app/Config/Routes.php` (api/users).
**Note:** `api/dashboard/*` is protected by global filter `dashboard_auth` in `app/Config/Filters.php` (session required).
### Grouped by feature
**schedules**
- `GET /api/dashboard/schedules/today` — Today's schedules (role-filtered).
- `GET /api/dashboard/schedules/current` — Current lesson or next (role-filtered).
- `GET /api/academic/schedules/class/(:num)` — Weekly schedule grid for class (admin_only).
- `POST /api/academic/schedules/bulk-save` — Bulk save schedules (admin_only).
- `GET /api/academic/lesson-slots` — List lesson slots (admin_only).
- `GET /api/academic/subjects` — List subjects (admin_only).
**attendance**
- `GET /api/dashboard/attendance/progress/current` — Live attendance progress for current schedule.
- `POST /api/attendance/checkin` — Device/mobile check-in (no dashboard filter; used by devices).
- `GET /api/attendance/report/schedule/(:num)` — Schedule report data (used by attendance report page).
**realtime**
- `GET /api/dashboard/summary` — Dashboard summary.
- `GET /api/dashboard/realtime` — Realtime stats.
- `GET /api/dashboard/stream` — SSE stream for live attendance.
- `GET /api/dashboard/devices` — Devices list.
**reports**
- Attendance report page uses: `GET /api/attendance/report/schedule/(:num)` (plus date query). No dedicated “reports” API group.
**devices**
- `GET /api/dashboard/devices` — Used by dashboard UI.
- `POST /api/device/login` — Device auth (not dashboard UI).
- `GET /api/mobile/ping`, `GET /api/mobile/bootstrap` — Mobile (not dashboard UI).
**analytics**
- No dedicated analytics API. Summary/realtime are the closest.
**other (used for dashboard UI)**
- `GET /api/users?role=GURU_MAPEL` — Schedule Builder teacher dropdown (admin_only).
---
## 3. SIDEBAR MENU SOURCE
**Location:** `app/Views/partials/sidebar.php`
**Included by:** `app/Views/layouts/main.php` via `<?= view('partials/sidebar') ?>`.
No separate “layouts/sidebar.php”; no config/menu builder found.
### How menu items are added
- **Fully static:** The sidebar is a single PHP file with hardcoded `<a href="...">` links.
- **No config:** No array or config file drives the menu.
- **No role logic:** The same HTML is rendered for every role; there is no `if (user has role X) show link Y`.
- **No dynamic highlighting:** The first item (Dashboard) uses `bg-primary/10 text-primary`; no logic sets “active” by current URI.
### Current sidebar entries
| Order | Label | href | Notes |
|-------|-----------------|------|--------|
| 1 | Dashboard | `/dashboard` | Real route. |
| 2 | Daily Schedule | `/dashboard/schedule/today` | Real route. |
| 3 | Schedule Builder| `/dashboard/academic/schedule-builder/1` | Real route; class ID hardcoded to 1. |
| 4 | Students | `#` | Placeholder; no page. |
| 5 | Attendance | `#` | Placeholder; no page. |
| 6 | Devices | `#` | Placeholder; no page. |
### Why some features are not visible
1. **Attendance Report** — There is a full page (`/dashboard/attendance/report/{id}`) but **no sidebar link**. Users only reach it via “Open Attendance” on the main dashboard (current lesson) or on Daily Schedule (per row). So the feature exists but is not in the menu.
2. **Students, Attendance (list), Devices** — Sidebar shows labels and icons but links are `#`. There are no corresponding dashboard pages or list views in the codebase; only placeholders.
3. **Current Lesson** — Not a separate page; its a **card on the main dashboard** plus live progress. No sidebar entry (by design).
4. **Academic setup** — Lesson slots, subjects, schedule management exist as **APIs** (admin_only) and one **page** (Schedule Builder). There is no “Academic Setup” or “Lesson Slots” menu item; only “Schedule Builder” with a fixed class ID.
---
## 4. DETECT MISSING MENU ITEMS
**Comparison:** Existing dashboard pages (Section 1) vs actual sidebar links (Section 3).
| route | feature_name | reason_not_visible |
|-------|--------------|--------------------|
| `GET /dashboard/attendance/report/(:num)` | Attendance Report (per schedule) | No sidebar entry; only reachable via “Open Attendance” on dashboard or daily schedule. |
**Missing menu list (structured):**
```json
[
{
"route": "GET /dashboard/attendance/report/(:num)",
"feature_name": "Attendance Report",
"reason_not_visible": "Not in sidebar; only linked from Current Lesson card and Daily Schedule row (Open Attendance)."
}
]
```
**Pages that are in the sidebar:** Dashboard, Daily Schedule, Schedule Builder.
**Placeholder items (no real route):** Students, Attendance (list), Devices — these are visible in the menu but point to `#` and have no backend page.
---
## 5. ROLE FILTER CHECK
**Filters used on dashboard-related routes:**
| Filter | Purpose | Used on |
|--------|---------|--------|
| `dashboard_page_auth` | Must be logged in (session). No role check. Redirects to `/login` if not authenticated. | `GET /dashboard`, `GET /dashboard/attendance/report/(:num)`, `GET /dashboard/schedule/today` |
| `dashboard_admin_page` | Must be logged in **and** have role **ADMIN**. Otherwise redirect to `/dashboard` with error. | `GET /dashboard/academic/schedule-builder/(:num)` |
| `admin_only` | API filter: must be logged in and ADMIN. Returns 401/403 JSON for API. | All `api/academic/*`, `GET /api/users` |
| `dashboard_auth` | Session required for API. Applied globally to `api/dashboard/*` in `Config/Filters.php`. No role check. | All `api/dashboard/*` |
**Which roles can see which pages:**
- **Dashboard (main), Daily Schedule, Attendance Report:** Any **authenticated** user (any role). Backend may still filter data by role (e.g. schedules by WALI_KELAS, GURU_MAPEL, ORANG_TUA).
- **Schedule Builder:** **ADMIN only.** Others get redirect to `/dashboard` with “Akses hanya untuk Admin.”
- **API:**
- `api/dashboard/*`: any authenticated user (data filtered by role in services).
- `api/academic/*` and `api/users`: **ADMIN only** (403 if not admin).
The sidebar does **not** hide Schedule Builder for non-admins; a non-admin who clicks it is redirected after the filter runs.
---
## 6. FINAL SUMMARY
### Current dashboard capability level
- **Implemented and reachable from UI:** Main dashboard (realtime + current lesson + live progress), Daily Schedule, Schedule Builder (class 1 hardcoded), Attendance Report (via links only, not menu).
- **Implemented but not exposed in menu:** Attendance Report as a direct menu item; no “list of schedules” or “pick a class” for Schedule Builder.
- **Placeholder only:** Students, Attendance (list), Devices — labels in sidebar but no pages or list views.
### Features implemented but hidden or partially hidden
1. **Attendance Report** — Full page and API exist; no sidebar link. Users must use “Open Attendance” from dashboard or daily schedule.
2. **Schedule Builder** — Only one class (ID 1) linked from sidebar; no class selector or list.
3. **Current Lesson + Live Progress** — On main dashboard only; no separate “Current Lesson” menu (by design).
4. **Academic APIs** — Lesson slots, subjects, schedules CRUD and bulk-save exist for admin; only Schedule Builder page is in the menu.
### Why only a few menus “work”
- **Three items** point to real routes: Dashboard, Daily Schedule, Schedule Builder.
- **One real page** (Attendance Report) has **no** sidebar entry.
- **Three items** (Students, Attendance, Devices) are **placeholders** (`href="#"`) with no backend pages.
So the menu looks like “many” items, but only three are real destinations; one important page is missing from the menu, and three are non-functional placeholders.
### Recommended menu structure for school system
Aligning with your desired structure and current codebase:
| # | Menu label | Purpose | Current status / suggestion |
|---|-------------------|--------|------------------------------|
| 1 | Dashboard | Home, current lesson, realtime | Exists. Keep. |
| 2 | Daily Schedule | Todays schedules by role | Exists. Keep. |
| 3 | Current Lesson | — | No separate page; keep as card on Dashboard. Optional: menu item that scrolls to or highlights that card. |
| 4 | Attendance Reports| List or pick schedule → report | Add link: e.g. “Attendance Reports” → new page that lists schedules (or todays) with “Open Report” per row, or link to a report index. Currently only per-schedule report exists. |
| 5 | Schedule Builder | Weekly schedule per class | Exists; add class selector or “Schedule Builder” → page that selects class then redirects to `schedule-builder/(:num)`. |
| 6 | Academic Setup | Lesson slots, subjects, maybe classes | No page yet. Add menu item when you have a page (e.g. lesson slots + subjects management). APIs exist (admin_only). |
| 7 | Devices | Device list / management | Add when you have a dashboard page for devices. API `GET /api/dashboard/devices` exists. |
| 8 | Analytics | Future | No implementation; add when built. |
**Concrete next steps (no code change in this audit):**
- Add a **sidebar link** for “Attendance Reports” (e.g. to a report index or todays schedules with report links).
- Replace **Students**, **Attendance**, **Devices** placeholders: either add real routes and link them or remove/hide until implemented.
- Add **class selection** for Schedule Builder (new page or dropdown) so the menu is not tied to class 1 only.
- Optionally add **Academic Setup** and **Devices** when corresponding pages exist; keep **Analytics** for later.
---
*End of audit. No code was modified.*

22
LICENSE Normal file
View File

@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2014-2019 British Columbia Institute of Technology
Copyright (c) 2019-present CodeIgniter Foundation
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.

257
PROJECT_CONDITION_AUDIT.md Normal file
View File

@@ -0,0 +1,257 @@
# Audit Kondisi Project SMAN 1 — Detail
**Tanggal:** 2026-02-23
---
## 1. Struktur Module
### Module yang sudah ada
| Module | Lokasi | Isi utama |
|--------|--------|-----------|
| **Academic** | `app/Modules/Academic/` | Classes, Students, Subjects, Teachers, Schedules, Lesson Slots, **DapodikSync** (controller + service + mapping model) |
| **Attendance** | `app/Modules/Attendance/` | AttendanceSession, Checkin, Report |
| **Auth** | `app/Modules/Auth/` | Login, User, Role, UserRole |
| **Dashboard** | `app/Modules/Dashboard/` | Dashboard, Schedule, Attendance, Realtime |
| **Devices** | `app/Modules/Devices/` | Device, Mobile, DeviceAuth |
| **Notification** | `app/Modules/Notification/` | Telegram, Parent, StudentParent |
| **Geo** | `app/Modules/Geo/` | Zone, GeoFence |
### Cek per modul yang Anda tanyakan
| Modul | Status | Keterangan |
|-------|--------|------------|
| **Classes** | ✅ Ada | Di dalam **Academic**: ClassModel, ClassEntity, ClassController (CRUD), route GET/POST/PUT/DELETE `/api/academic/classes`, halaman `/dashboard/academic/classes` |
| **Students** | ✅ Ada | Di dalam **Academic**: StudentModel, StudentEntity, StudentController (CRUD + paginasi), route GET/POST/PUT/DELETE `/api/academic/students`, halaman `/dashboard/academic/students` |
| **Attendance** | ✅ Ada | Module **Attendance** terpisah: AttendanceSessionModel, AttendanceCheckinService, AttendanceReportService, dll. Tabel: `attendance_sessions` (bukan `attendance_logs`) |
| **Schedule** | ✅ Ada | Di dalam **Academic**: ScheduleModel, ScheduleManagementController, ScheduleResolverService, lesson_slots. Tabel: `schedules`, `lesson_slots` |
| **DapodikSync** | ✅ Ada | Di dalam **Academic**: DapodikClient, DapodikSyncService, DapodikSyncController, DapodikRombelMappingModel. Route: POST sync/students, GET/PUT rombels. Halaman `/dashboard/academic/dapodik` |
**Kesimpulan:** Semua modul yang Anda sebut (Classes, Students, Attendance, Schedule, DapodikSync) **sudah ada**. Tidak ada modul terpisah bernama "Classes" atau "Students"; semuanya di bawah **Academic**.
---
## 2. Database
### Tabel yang ada (beserta struktur)
**Catatan:** Tidak ada tabel bernama `attendance_logs`. Yang dipakai: **`attendance_sessions`**.
### 2.1 Tabel `classes`
| Field | Type | Relasi |
|-------|------|--------|
| id | INT PK AUTO_INCREMENT | - |
| name | VARCHAR(100) | - (rombel, mis. A, B, C) |
| grade | VARCHAR(50) | - (tingkat, mis. 10, X) |
| major | VARCHAR(50) NOT NULL DEFAULT 'IPA' | - (jurusan) |
| wali_user_id | INT NULL | FK → users.id (SET NULL) |
| created_at | DATETIME NULL | - |
| updated_at | DATETIME NULL | - |
**Relasi keluar:** `students.class_id`, `schedules.class_id`, `dapodik_rombel_mappings.class_id` → classes.id
---
### 2.2 Tabel `students`
| Field | Type | Relasi |
|-------|------|--------|
| id | INT PK AUTO_INCREMENT | - |
| nisn | VARCHAR(50) NOT NULL UNIQUE | - |
| name | VARCHAR(255) | - |
| gender | VARCHAR(1) NULL | L/P |
| class_id | INT NULL | FK → classes.id (SET NULL) — **nullable untuk unmapped** |
| is_active | TINYINT(1) DEFAULT 1 | - |
| parent_link_code | VARCHAR | (dari migration lain) |
| created_at | DATETIME NULL | - |
| updated_at | DATETIME NULL | - |
**Relasi:** class_id → classes.id (boleh NULL untuk siswa belum di-map dari Dapodik).
---
### 2.3 Tabel `attendance_sessions` (bukan attendance_logs)
| Field | Type | Relasi |
|-------|------|--------|
| id | INT PK | - |
| student_id | INT | FK → students.id |
| schedule_id | INT NULL | FK → schedules.id |
| device_id | INT | FK → devices.id |
| attendance_date | DATE | (dari migration unik) |
| checkin_at | DATETIME | - |
| latitude, longitude, confidence | DECIMAL | - |
| status | ENUM(PRESENT, LATE, OUTSIDE_ZONE, NO_SCHEDULE, INVALID_DEVICE) | - |
| created_at, updated_at | DATETIME NULL | - |
**Relasi:** student_id → students, schedule_id → schedules, device_id → devices.
---
### 2.4 Tabel `schedules`
| Field | Type | Relasi |
|-------|------|--------|
| id | INT PK | - |
| class_id | INT | FK → classes.id |
| lesson_slot_id | INT NULL | FK → lesson_slots.id |
| subject_id | INT | FK → subjects.id |
| teacher_user_id | INT NULL | FK → users.id |
| teacher_name | VARCHAR(255) | - |
| day_of_week | TINYINT (1=Senin, 7=Minggu) | - |
| start_time, end_time | TIME | - |
| room | VARCHAR(100) NULL | - |
| is_active | TINYINT DEFAULT 1 | - |
| created_at, updated_at | DATETIME NULL | - |
**Unique:** (class_id, lesson_slot_id, day_of_week).
**Relasi:** class_id → classes, subject_id → subjects, teacher_user_id → users, lesson_slot_id → lesson_slots.
---
### 2.5 Tabel tambahan terkait
- **dapodik_rombel_mappings:** id, dapodik_rombel (UNIQUE), class_id (FK → classes, NULL), last_seen_at, created_at, updated_at.
- **lesson_slots:** id, slot_number, start_time, end_time, is_active.
- **subjects:** id, name, code (nullable).
---
## 3. Flow Master Data
### 3.1 Kelas: input manual atau belum?
- **Input kelas:** **manual** lewat halaman **Classes** (`/dashboard/academic/classes`), hanya untuk role ADMIN.
- Form: Tingkat (text), Jurusan (text), Rombel (text), Wali Kelas (dropdown user).
- Data disimpan ke tabel **classes** (name = rombel, grade, major, wali_user_id).
- **Jika belum pernah input:** tabel `classes` **kosong** → tidak ada pilihan kelas di mana pun (Schedule Builder, Students, dll.).
### 3.2 Schedule Builder mengambil data kelas dari mana?
- **Dari API:** `GET /api/academic/classes` (admin_only).
- Halaman Schedule Builder index (`/dashboard/academic/schedule-builder`) memanggil API ini lalu mengisi **dropdown "Kelas"** (option value = class id, text = nama/rombel).
- Data sumber: **tabel `classes`** via ClassController::index().
### 3.3 Kenapa dropdown kelas bisa kosong?
- **Penyebab:** Tabel **classes tidak punya data** (belum ada satu baris pun).
- **Alur:** Tidak ada kelas → API `/api/academic/classes` mengembalikan array kosong → dropdown hanya berisi "— Pilih kelas —" → Open Builder tidak bisa dipakai.
- **Solusi:** Login sebagai ADMIN → buka **Academic → Classes** → tambah minimal satu kelas (mis. Tingkat 10, Jurusan IPA, Rombel 1). Setelah itu dropdown di Schedule Builder akan terisi.
---
## 4. Dapodik Integration
| Aspek | Status | Keterangan |
|-------|--------|------------|
| **Controller Dapodik Sync** | ✅ Ada | `App\Modules\Academic\Controllers\DapodikSyncController` |
| **Endpoint API** | ✅ Ada | POST `/api/academic/dapodik/sync/students`, GET `/api/academic/dapodik/rombels`, PUT `/api/academic/dapodik/rombels/{id}` (semua admin_only) |
| **Rencana vs realisasi** | ✅ Sudah diimplementasi | DapodikClient (getSekolah, getPesertaDidik), DapodikSyncService (sync siswa + rombel mapping), halaman Dapodik di dashboard |
**Env yang dipakai:** DAPODIK_BASE_URL, DAPODIK_TOKEN, DAPODIK_NPSN (di .env).
---
## 5. Student Page
### Apakah halaman Student sudah tampil?
- **Route:** ✅ Ada — `GET /dashboard/academic/students``DashboardAcademicController::students`, filter `dashboard_admin_page`.
- **Controller:** ✅ Ada — method `students()` me-render view `dashboard/students`.
- **View:** ✅ Ada — `app/Views/dashboard/students.php` (tabel, filter, paginasi, modal tambah/edit/hapus).
- **Query/relasi:** ✅ API GET `/api/academic/students` jalan; join ke `classes` untuk class_label; `class_id` boleh NULL (tidak gagal).
### Kenapa bisa “belum tampil”?
Kemungkinan:
1. **Bukan ADMIN** — halaman dan menu Students hanya untuk role ADMIN. Jika login bukan ADMIN, menu Academic (termasuk Students) tidak muncul.
2. **URL salah** — harus akses tepat: `/dashboard/academic/students` (mis. `http://localhost/sman1/backend/public/dashboard/academic/students`).
3. **Session/redirect** — jika belum login atau filter redirect, akan ke halaman login/dashboard.
4. **Data kosong** — halaman tetap tampil; yang kosong hanya **tabel siswa** (belum ada data siswa). Bukan penyebab “halaman tidak tampil”.
**Kesimpulan:** Secara kode, route, controller, view, dan relasi **sudah ada dan konsisten**. Kalau “belum tampil”, paling mungkin karena **bukan user ADMIN** atau **salah URL/base URL**.
---
## 6. Problem Diagnosis
### “Schedule Builder meminta kelas, tapi tidak ada tempat input kelas”
- **Faktanya:** **Sudah ada tempat input kelas**, yaitu halaman **Classes** (`/dashboard/academic/classes`), hanya untuk ADMIN.
- **Alur yang benar:**
1. ADMIN buka **Academic → Classes** (atau lewat **Academic → Settings** → kartu Classes).
2. Klik **Tambah Kelas** → isi Tingkat, Jurusan, Rombel, (opsional) Wali Kelas → Simpan.
3. Setelah ada minimal 1 kelas, buka **Schedule Builder** → dropdown **Kelas** terisi → pilih kelas → Open Builder.
Jadi masalahnya bukan “tidak ada tempat input”, melainkan:
- **User belum pernah mengisi kelas** di halaman Classes, atau
- **Menu Classes tidak terlihat** (mis. karena tidak login sebagai ADMIN).
**Rekomendasi:** Di halaman Schedule Builder index bisa ditambah kalimat singkat: “Jika dropdown kosong, tambah dulu kelas di **Academic → Classes**.”
---
## 7. Ringkasan Kondisi Project
| Aspek | Status | Keterangan |
|-------|--------|------------|
| **Module Academic (Classes, Students, Subjects, Teachers, Schedules, Lesson Slots)** | ✅ Sudah jadi | CRUD API + halaman dashboard per entitas |
| **Module Attendance** | ✅ Sudah jadi | attendance_sessions, check-in, report |
| **Module Schedule (jadwal per kelas)** | ✅ Sudah jadi | Schedule Builder, bulk save, lesson_slots |
| **Module DapodikSync** | ✅ Sudah jadi | Sync siswa, mapping rombel → class, halaman Dapodik |
| **Tabel classes, students, schedules, attendance_sessions** | ✅ Sudah jadi | Struktur + relasi jelas (termasuk lesson_slots, subjects, dapodik_rombel_mappings) |
| **Input kelas manual** | ✅ Sudah jadi | Halaman Classes, form lengkap |
| **Schedule Builder pakai data kelas** | ✅ Sudah jadi | Dari GET /api/academic/classes |
| **Halaman Students** | ✅ Sudah jadi | Route, controller, view, API, paginasi, filter |
| **Dropdown kelas kosong** | ⚠️ Setengah jadi | Fitur jalan; kosong karena **belum ada data kelas** di DB |
| **Dapodik sebagai sumber master kelas** | ⚠️ Setengah jadi | Saat ini Dapodik hanya **sync siswa** + mapping **rombel → class**. Kelas internal tetap **buat manual** di Classes; belum ada “sync rombel → buat kelas otomatis” |
---
## 8. Arsitektur saran: Dapodik sebagai sumber utama master data
Target alur: **DAPODIK → Sync → Classes → Students → Schedule → Attendance**.
### Kondisi saat ini
- **Classes:** input manual; tidak ada sync dari Dapodik.
- **Students:** bisa dari Dapodik (sync siswa + mapping rombel → class_id). class_id bisa NULL (unmapped).
- **Schedule & Attendance:** sudah mengandalkan classes + students.
### Opsi arsitektur
**Opsi A — Kelas tetap manual (minimal change)**
- Tetap: Classes diisi manual (grade + major + rombel).
- Dapodik: sync siswa + mapping **dapodik_rombel → class_id**.
- Sesuai jika: rombel Dapodik banyak dan Anda ingin satu rombel Dapodik = satu kelas internal yang sudah Anda buat manual.
**Opsi B — Sync rombel Dapodik → buat/update kelas (disarankan untuk “Dapodik sumber utama”)**
1. **Tambah sync kelas/rombel dari Dapodik**
- Endpoint Dapodik: daftar rombongan belajar (rombel) per sekolah.
- Logic: untuk setiap rombel Dapodik, **buat atau update** satu baris di `classes` (mis. parse nama rombel jadi grade + major + name/rombel), plus **tetap** isi `dapodik_rombel_mappings` (dapodik_rombel → class_id) agar siswa sync bisa map ke kelas yang sama.
- Aturan: satu `dapodik_rombel` = satu `class_id`; kelas bisa dibuat otomatis dari nama rombel Dapodik (mis. "10 IPA 1" → grade=10, major=IPA, name=1).
2. **Urutan sync disarankan**
- **Sync rombel/kelas dulu** (baca Dapodik → insert/update `classes` + `dapodik_rombel_mappings`).
- **Lalu sync siswa** (seperti sekarang); mapping rombel → class_id sudah terisi, sehingga siswa dapat class_id otomatis.
3. **Tetap boleh edit manual**
- Halaman **Classes** tetap dipakai untuk koreksi/naming (grade, major, rombel, wali).
- Setelah sync, admin bisa ubah nama/struktur kelas jika perlu.
**Opsi C — Hybrid (seperti B + flag sumber)**
- Tambah kolom mis. `source` (manual / dapodik) di `classes` supaya bisa bedakan kelas yang dari Dapodik vs yang buat manual.
### Rekomendasi singkat
- **Langkah 1:** Pastikan **ada data kelas** (manual) dulu agar Schedule Builder dan dropdown siswa tidak kosong.
- **Langkah 2:** Jika ingin Dapodik sebagai sumber utama kelas, tambah **sync rombel Dapodik → classes** (Opsi B); jadwalkan sync rombel dulu, baru sync siswa.
- **Langkah 3:** Tetap pakai **Dapodik Sync** yang sudah ada untuk siswa dan mapping rombel → class; setelah kelas bisa dari Dapodik, mapping itu akan mengisi class_id siswa tanpa perlu input kelas manual dulu.
Dengan ini, arsitektur bergerak ke: **DAPODIK → Sync (rombel + siswa) → Classes & Students terisi → Schedule (manual di builder) → Attendance**.

69
README.md Normal file
View File

@@ -0,0 +1,69 @@
# CodeIgniter 4 Application Starter
## What is CodeIgniter?
CodeIgniter is a PHP full-stack web framework that is light, fast, flexible and secure.
More information can be found at the [official site](https://codeigniter.com).
This repository holds a composer-installable app starter.
It has been built from the
[development repository](https://github.com/codeigniter4/CodeIgniter4).
More information about the plans for version 4 can be found in [CodeIgniter 4](https://forum.codeigniter.com/forumdisplay.php?fid=28) on the forums.
You can read the [user guide](https://codeigniter.com/user_guide/)
corresponding to the latest version of the framework.
## Installation & updates
`composer create-project codeigniter4/appstarter` then `composer update` whenever
there is a new release of the framework.
When updating, check the release notes to see if there are any changes you might need to apply
to your `app` folder. The affected files can be copied or merged from
`vendor/codeigniter4/framework/app`.
## Setup
Copy `env` to `.env` and tailor for your app, specifically the baseURL
and any database settings.
## Important Change with index.php
`index.php` is no longer in the root of the project! It has been moved inside the *public* folder,
for better security and separation of components.
This means that you should configure your web server to "point" to your project's *public* folder, and
not to the project root. A better practice would be to configure a virtual host to point there. A poor practice would be to point your web server to the project root and expect to enter *public/...*, as the rest of your logic and the
framework are exposed.
**Please** read the user guide for a better explanation of how CI4 works!
## Repository Management
We use GitHub issues, in our main repository, to track **BUGS** and to track approved **DEVELOPMENT** work packages.
We use our [forum](http://forum.codeigniter.com) to provide SUPPORT and to discuss
FEATURE REQUESTS.
This repository is a "distribution" one, built by our release preparation script.
Problems with it can be raised on our forum, or as issues in the main repository.
## Server Requirements
PHP version 8.2 or higher is required, with the following extensions installed:
- [intl](http://php.net/manual/en/intl.requirements.php)
- [mbstring](http://php.net/manual/en/mbstring.installation.php)
> [!WARNING]
> - The end of life date for PHP 7.4 was November 28, 2022.
> - The end of life date for PHP 8.0 was November 26, 2023.
> - The end of life date for PHP 8.1 was December 31, 2025.
> - If you are still using below PHP 8.2, you should upgrade immediately.
> - The end of life date for PHP 8.2 will be December 31, 2026.
Additionally, make sure that the following extensions are enabled in your PHP:
- json (enabled by default - don't turn it off)
- [mysqlnd](http://php.net/manual/en/mysqlnd.install.php) if you plan to use MySQL
- [libcurl](http://php.net/manual/en/curl.requirements.php) if you plan to use the HTTP\CURLRequest library

43
SETUP_PRESENSI.md Normal file
View File

@@ -0,0 +1,43 @@
# Pengaturan Presensi di Backend (Dashboard)
Semua pengaturan presensi **terpusat** di satu tempat. Login sebagai **Admin** dulu.
---
## Satu halaman: Pengaturan Presensi
**Dashboard** → sidebar kiri → **Pengaturan Presensi** (icon pin map).
Di sini admin mengatur:
1. **Koordinat Sekolah (Zona Presensi)**
Satu koordinat untuk **seluruh sekolah**: Latitude, Longitude, Radius (meter).
Semua absen (mobile & device) hanya valid jika siswa berada di dalam radius ini. Tidak ada lagi pengaturan koordinat per device.
2. **Jadwal Masuk & Pulang**
Window waktu untuk absen masuk dan absen pulang (jam mulaiakhir).
Contoh: Masuk 06:3007:00, Pulang 14:0014:30.
Simpan → dipakai untuk validasi geofence dan jadwal.
---
## Jam per mapel (opsional)
Kalau ingin jadwal per mata pelajaran (slot jam pelajaran, Schedule Builder), tetap lewat:
- **Pengaturan Academic** → **Jam Pelajaran** (slot jam) + **Schedule Builder** (jadwal per kelas).
Pengaturan Presensi dipakai untuk **base** masuk/pulang; detail slot mapel tetap di Academic bila dipakai.
---
## Ringkas
| Yang diatur | Menu | Keterangan |
|--------------------|-------------------------|-------------------------------------|
| Koordinat sekolah | **Pengaturan Presensi** | Satu zona untuk semua absen |
| Jam masuk & pulang | **Pengaturan Presensi** | Satu set jam masuk dan pulang |
| Jam per mapel | Pengaturan Academic | Jam Pelajaran + Schedule Builder |
**Device Absen** di sidebar hanya untuk daftar/monitoring device; koordinat tidak lagi diatur per device.

6
app/.htaccess Normal file
View File

@@ -0,0 +1,6 @@
<IfModule authz_core_module>
Require all denied
</IfModule>
<IfModule !authz_core_module>
Deny from all
</IfModule>

15
app/Common.php Normal file
View File

@@ -0,0 +1,15 @@
<?php
/**
* The goal of this file is to allow developers a location
* where they can overwrite core procedural functions and
* replace them with their own. This file is loaded during
* the bootstrap process and is called during the framework's
* execution.
*
* This can be looked at as a `master helper` file that is
* loaded early on, and may also contain additional functions
* that you'd like to use throughout your entire application
*
* @see: https://codeigniter.com/user_guide/extending/common.html
*/

202
app/Config/App.php Normal file
View File

@@ -0,0 +1,202 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class App extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Base Site URL
* --------------------------------------------------------------------------
*
* URL to your CodeIgniter root. Typically, this will be your base URL,
* WITH a trailing slash:
*
* E.g., http://example.com/
*/
public string $baseURL = 'http://localhost:8080/';
/**
* Allowed Hostnames in the Site URL other than the hostname in the baseURL.
* If you want to accept multiple Hostnames, set this.
*
* E.g.,
* When your site URL ($baseURL) is 'http://example.com/', and your site
* also accepts 'http://media.example.com/' and 'http://accounts.example.com/':
* ['media.example.com', 'accounts.example.com']
*
* @var list<string>
*/
public array $allowedHostnames = [];
/**
* --------------------------------------------------------------------------
* Index File
* --------------------------------------------------------------------------
*
* Typically, this will be your `index.php` file, unless you've renamed it to
* something else. If you have configured your web server to remove this file
* from your site URIs, set this variable to an empty string.
*/
public string $indexPage = 'index.php';
/**
* --------------------------------------------------------------------------
* URI PROTOCOL
* --------------------------------------------------------------------------
*
* This item determines which server global should be used to retrieve the
* URI string. The default setting of 'REQUEST_URI' works for most servers.
* If your links do not seem to work, try one of the other delicious flavors:
*
* 'REQUEST_URI': Uses $_SERVER['REQUEST_URI']
* 'QUERY_STRING': Uses $_SERVER['QUERY_STRING']
* 'PATH_INFO': Uses $_SERVER['PATH_INFO']
*
* WARNING: If you set this to 'PATH_INFO', URIs will always be URL-decoded!
*/
public string $uriProtocol = 'REQUEST_URI';
/*
|--------------------------------------------------------------------------
| Allowed URL Characters
|--------------------------------------------------------------------------
|
| This lets you specify which characters are permitted within your URLs.
| When someone tries to submit a URL with disallowed characters they will
| get a warning message.
|
| As a security measure you are STRONGLY encouraged to restrict URLs to
| as few characters as possible.
|
| By default, only these are allowed: `a-z 0-9~%.:_-`
|
| Set an empty string to allow all characters -- but only if you are insane.
|
| The configured value is actually a regular expression character group
| and it will be used as: '/\A[<permittedURIChars>]+\z/iu'
|
| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!!
|
*/
public string $permittedURIChars = 'a-z 0-9~%.:_\-';
/**
* --------------------------------------------------------------------------
* Default Locale
* --------------------------------------------------------------------------
*
* The Locale roughly represents the language and location that your visitor
* is viewing the site from. It affects the language strings and other
* strings (like currency markers, numbers, etc), that your program
* should run under for this request.
*/
public string $defaultLocale = 'en';
/**
* --------------------------------------------------------------------------
* Negotiate Locale
* --------------------------------------------------------------------------
*
* If true, the current Request object will automatically determine the
* language to use based on the value of the Accept-Language header.
*
* If false, no automatic detection will be performed.
*/
public bool $negotiateLocale = false;
/**
* --------------------------------------------------------------------------
* Supported Locales
* --------------------------------------------------------------------------
*
* If $negotiateLocale is true, this array lists the locales supported
* by the application in descending order of priority. If no match is
* found, the first locale will be used.
*
* IncomingRequest::setLocale() also uses this list.
*
* @var list<string>
*/
public array $supportedLocales = ['en'];
/**
* --------------------------------------------------------------------------
* Application Timezone
* --------------------------------------------------------------------------
*
* The default timezone that will be used in your application to display
* dates with the date helper, and can be retrieved through app_timezone()
*
* @see https://www.php.net/manual/en/timezones.php for list of timezones
* supported by PHP.
*/
public string $appTimezone = 'UTC';
/**
* --------------------------------------------------------------------------
* Default Character Set
* --------------------------------------------------------------------------
*
* This determines which character set is used by default in various methods
* that require a character set to be provided.
*
* @see http://php.net/htmlspecialchars for a list of supported charsets.
*/
public string $charset = 'UTF-8';
/**
* --------------------------------------------------------------------------
* Force Global Secure Requests
* --------------------------------------------------------------------------
*
* If true, this will force every request made to this application to be
* made via a secure connection (HTTPS). If the incoming request is not
* secure, the user will be redirected to a secure version of the page
* and the HTTP Strict Transport Security (HSTS) header will be set.
*/
public bool $forceGlobalSecureRequests = false;
/**
* --------------------------------------------------------------------------
* Reverse Proxy IPs
* --------------------------------------------------------------------------
*
* If your server is behind a reverse proxy, you must whitelist the proxy
* IP addresses from which CodeIgniter should trust headers such as
* X-Forwarded-For or Client-IP in order to properly identify
* the visitor's IP address.
*
* You need to set a proxy IP address or IP address with subnets and
* the HTTP header for the client IP address.
*
* Here are some examples:
* [
* '10.0.1.200' => 'X-Forwarded-For',
* '192.168.5.0/24' => 'X-Real-IP',
* ]
*
* @var array<string, string>
*/
public array $proxyIPs = [];
/**
* --------------------------------------------------------------------------
* Content Security Policy
* --------------------------------------------------------------------------
*
* Enables the Response's Content Secure Policy to restrict the sources that
* can be used for images, scripts, CSS files, audio, video, etc. If enabled,
* the Response object will populate default values for the policy from the
* `ContentSecurityPolicy.php` file. Controllers can always add to those
* restrictions at run time.
*
* For a better understanding of CSP, see these documents:
*
* @see http://www.html5rocks.com/en/tutorials/security/content-security-policy/
* @see http://www.w3.org/TR/CSP/
*/
public bool $CSPEnabled = false;
}

28
app/Config/Attendance.php Normal file
View File

@@ -0,0 +1,28 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Attendance configuration
*
* Attendance window: check-in is only allowed from (schedule start - open_before)
* until (schedule start + close_after). Outside this window → ABSENCE_WINDOW_CLOSED (no insert).
*/
class Attendance extends BaseConfig
{
/**
* Minutes before schedule start_time when attendance opens
*
* @var int
*/
public int $attendanceOpenBeforeMinutes = 5;
/**
* Minutes after schedule start_time when attendance closes
*
* @var int
*/
public int $attendanceCloseAfterMinutes = 15;
}

93
app/Config/Autoload.php Normal file
View File

@@ -0,0 +1,93 @@
<?php
namespace Config;
use CodeIgniter\Config\AutoloadConfig;
/**
* -------------------------------------------------------------------
* AUTOLOADER CONFIGURATION
* -------------------------------------------------------------------
*
* This file defines the namespaces and class maps so the Autoloader
* can find the files as needed.
*
* NOTE: If you use an identical key in $psr4 or $classmap, then
* the values in this file will overwrite the framework's values.
*
* NOTE: This class is required prior to Autoloader instantiation,
* and does not extend BaseConfig.
*/
class Autoload extends AutoloadConfig
{
/**
* -------------------------------------------------------------------
* Namespaces
* -------------------------------------------------------------------
* This maps the locations of any namespaces in your application to
* their location on the file system. These are used by the autoloader
* to locate files the first time they have been instantiated.
*
* The 'Config' (APPPATH . 'Config') and 'CodeIgniter' (SYSTEMPATH) are
* already mapped for you.
*
* You may change the name of the 'App' namespace if you wish,
* but this should be done prior to creating any namespaced classes,
* else you will need to modify all of those classes for this to work.
*
* @var array<string, list<string>|string>
*/
public $psr4 = [
APP_NAMESPACE => APPPATH,
'App\\Modules\\' => APPPATH . 'Modules' . DIRECTORY_SEPARATOR,
];
/**
* -------------------------------------------------------------------
* Class Map
* -------------------------------------------------------------------
* The class map provides a map of class names and their exact
* location on the drive. Classes loaded in this manner will have
* slightly faster performance because they will not have to be
* searched for within one or more directories as they would if they
* were being autoloaded through a namespace.
*
* Prototype:
* $classmap = [
* 'MyClass' => '/path/to/class/file.php'
* ];
*
* @var array<string, string>
*/
public $classmap = [];
/**
* -------------------------------------------------------------------
* Files
* -------------------------------------------------------------------
* The files array provides a list of paths to __non-class__ files
* that will be autoloaded. This can be useful for bootstrap operations
* or for loading functions.
*
* Prototype:
* $files = [
* '/path/to/my/file.php',
* ];
*
* @var list<string>
*/
public $files = [];
/**
* -------------------------------------------------------------------
* Helpers
* -------------------------------------------------------------------
* Prototype:
* $helpers = [
* 'form',
* ];
*
* @var list<string>
*/
public $helpers = [];
}

View File

@@ -0,0 +1,34 @@
<?php
/*
|--------------------------------------------------------------------------
| ERROR DISPLAY
|--------------------------------------------------------------------------
| In development, we want to show as many errors as possible to help
| make sure they don't make it to production. And save us hours of
| painful debugging.
|
| If you set 'display_errors' to '1', CI4's detailed error report will show.
*/
error_reporting(E_ALL);
ini_set('display_errors', '1');
/*
|--------------------------------------------------------------------------
| DEBUG BACKTRACES
|--------------------------------------------------------------------------
| If true, this constant will tell the error screens to display debug
| backtraces along with the other error information. If you would
| prefer to not see this, set this value to false.
*/
defined('SHOW_DEBUG_BACKTRACE') || define('SHOW_DEBUG_BACKTRACE', true);
/*
|--------------------------------------------------------------------------
| DEBUG MODE
|--------------------------------------------------------------------------
| Debug mode is an experimental flag that can allow changes throughout
| the system. This will control whether Kint is loaded, and a few other
| items. It can always be used within your own application too.
*/
defined('CI_DEBUG') || define('CI_DEBUG', true);

View File

@@ -0,0 +1,25 @@
<?php
/*
|--------------------------------------------------------------------------
| ERROR DISPLAY
|--------------------------------------------------------------------------
| Don't show ANY in production environments. Instead, let the system catch
| it and display a generic error message.
|
| If you set 'display_errors' to '1', CI4's detailed error report will show.
*/
error_reporting(E_ALL & ~E_DEPRECATED);
// If you want to suppress more types of errors.
// error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED);
ini_set('display_errors', '0');
/*
|--------------------------------------------------------------------------
| DEBUG MODE
|--------------------------------------------------------------------------
| Debug mode is an experimental flag that can allow changes throughout
| the system. It's not widely used currently, and may not survive
| release of the framework.
*/
defined('CI_DEBUG') || define('CI_DEBUG', false);

View File

@@ -0,0 +1,38 @@
<?php
/*
* The environment testing is reserved for PHPUnit testing. It has special
* conditions built into the framework at various places to assist with that.
* You cant use it for your development.
*/
/*
|--------------------------------------------------------------------------
| ERROR DISPLAY
|--------------------------------------------------------------------------
| In development, we want to show as many errors as possible to help
| make sure they don't make it to production. And save us hours of
| painful debugging.
*/
error_reporting(E_ALL);
ini_set('display_errors', '1');
/*
|--------------------------------------------------------------------------
| DEBUG BACKTRACES
|--------------------------------------------------------------------------
| If true, this constant will tell the error screens to display debug
| backtraces along with the other error information. If you would
| prefer to not see this, set this value to false.
*/
defined('SHOW_DEBUG_BACKTRACE') || define('SHOW_DEBUG_BACKTRACE', true);
/*
|--------------------------------------------------------------------------
| DEBUG MODE
|--------------------------------------------------------------------------
| Debug mode is an experimental flag that can allow changes throughout
| the system. It's not widely used currently, and may not survive
| release of the framework.
*/
defined('CI_DEBUG') || define('CI_DEBUG', true);

View File

@@ -0,0 +1,36 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class CURLRequest extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* CURLRequest Share Connection Options
* --------------------------------------------------------------------------
*
* Share connection options between requests.
*
* @var list<int>
*
* @see https://www.php.net/manual/en/curl.constants.php#constant.curl-lock-data-connect
*/
public array $shareConnectionOptions = [
CURL_LOCK_DATA_CONNECT,
CURL_LOCK_DATA_DNS,
];
/**
* --------------------------------------------------------------------------
* CURLRequest Share Options
* --------------------------------------------------------------------------
*
* Whether share options between requests or not.
*
* If true, all the options won't be reset between requests.
* It may cause an error request with unnecessary headers.
*/
public bool $shareOptions = false;
}

198
app/Config/Cache.php Normal file
View File

@@ -0,0 +1,198 @@
<?php
namespace Config;
use CodeIgniter\Cache\CacheInterface;
use CodeIgniter\Cache\Handlers\ApcuHandler;
use CodeIgniter\Cache\Handlers\DummyHandler;
use CodeIgniter\Cache\Handlers\FileHandler;
use CodeIgniter\Cache\Handlers\MemcachedHandler;
use CodeIgniter\Cache\Handlers\PredisHandler;
use CodeIgniter\Cache\Handlers\RedisHandler;
use CodeIgniter\Cache\Handlers\WincacheHandler;
use CodeIgniter\Config\BaseConfig;
class Cache extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Primary Handler
* --------------------------------------------------------------------------
*
* The name of the preferred handler that should be used. If for some reason
* it is not available, the $backupHandler will be used in its place.
*/
public string $handler = 'file';
/**
* --------------------------------------------------------------------------
* Backup Handler
* --------------------------------------------------------------------------
*
* The name of the handler that will be used in case the first one is
* unreachable. Often, 'file' is used here since the filesystem is
* always available, though that's not always practical for the app.
*/
public string $backupHandler = 'dummy';
/**
* --------------------------------------------------------------------------
* Key Prefix
* --------------------------------------------------------------------------
*
* This string is added to all cache item names to help avoid collisions
* if you run multiple applications with the same cache engine.
*/
public string $prefix = '';
/**
* --------------------------------------------------------------------------
* Default TTL
* --------------------------------------------------------------------------
*
* The default number of seconds to save items when none is specified.
*
* WARNING: This is not used by framework handlers where 60 seconds is
* hard-coded, but may be useful to projects and modules. This will replace
* the hard-coded value in a future release.
*/
public int $ttl = 60;
/**
* --------------------------------------------------------------------------
* Reserved Characters
* --------------------------------------------------------------------------
*
* A string of reserved characters that will not be allowed in keys or tags.
* Strings that violate this restriction will cause handlers to throw.
* Default: {}()/\@:
*
* NOTE: The default set is required for PSR-6 compliance.
*/
public string $reservedCharacters = '{}()/\@:';
/**
* --------------------------------------------------------------------------
* File settings
* --------------------------------------------------------------------------
*
* Your file storage preferences can be specified below, if you are using
* the File driver.
*
* @var array{storePath?: string, mode?: int}
*/
public array $file = [
'storePath' => WRITEPATH . 'cache/',
'mode' => 0640,
];
/**
* -------------------------------------------------------------------------
* Memcached settings
* -------------------------------------------------------------------------
*
* Your Memcached servers can be specified below, if you are using
* the Memcached drivers.
*
* @see https://codeigniter.com/user_guide/libraries/caching.html#memcached
*
* @var array{host?: string, port?: int, weight?: int, raw?: bool}
*/
public array $memcached = [
'host' => '127.0.0.1',
'port' => 11211,
'weight' => 1,
'raw' => false,
];
/**
* -------------------------------------------------------------------------
* Redis settings
* -------------------------------------------------------------------------
*
* Your Redis server can be specified below, if you are using
* the Redis or Predis drivers.
*
* @var array{
* host?: string,
* password?: string|null,
* port?: int,
* timeout?: int,
* async?: bool,
* persistent?: bool,
* database?: int
* }
*/
public array $redis = [
'host' => '127.0.0.1',
'password' => null,
'port' => 6379,
'timeout' => 0,
'async' => false, // specific to Predis and ignored by the native Redis extension
'persistent' => false,
'database' => 0,
];
/**
* --------------------------------------------------------------------------
* Available Cache Handlers
* --------------------------------------------------------------------------
*
* This is an array of cache engine alias' and class names. Only engines
* that are listed here are allowed to be used.
*
* @var array<string, class-string<CacheInterface>>
*/
public array $validHandlers = [
'apcu' => ApcuHandler::class,
'dummy' => DummyHandler::class,
'file' => FileHandler::class,
'memcached' => MemcachedHandler::class,
'predis' => PredisHandler::class,
'redis' => RedisHandler::class,
'wincache' => WincacheHandler::class,
];
/**
* --------------------------------------------------------------------------
* Web Page Caching: Cache Include Query String
* --------------------------------------------------------------------------
*
* Whether to take the URL query string into consideration when generating
* output cache files. Valid options are:
*
* false = Disabled
* true = Enabled, take all query parameters into account.
* Please be aware that this may result in numerous cache
* files generated for the same page over and over again.
* ['q'] = Enabled, but only take into account the specified list
* of query parameters.
*
* @var bool|list<string>
*/
public $cacheQueryString = false;
/**
* --------------------------------------------------------------------------
* Web Page Caching: Cache Status Codes
* --------------------------------------------------------------------------
*
* HTTP status codes that are allowed to be cached. Only responses with
* these status codes will be cached by the PageCache filter.
*
* Default: [] - Cache all status codes (backward compatible)
*
* Recommended: [200] - Only cache successful responses
*
* You can also use status codes like:
* [200, 404, 410] - Cache successful responses and specific error codes
* [200, 201, 202, 203, 204] - All 2xx successful responses
*
* WARNING: Using [] may cache temporary error pages (404, 500, etc).
* Consider restricting to [200] for production applications to avoid
* caching errors that should be temporary.
*
* @var list<int>
*/
public array $cacheStatusCodes = [];
}

79
app/Config/Constants.php Normal file
View File

@@ -0,0 +1,79 @@
<?php
/*
| --------------------------------------------------------------------
| App Namespace
| --------------------------------------------------------------------
|
| This defines the default Namespace that is used throughout
| CodeIgniter to refer to the Application directory. Change
| this constant to change the namespace that all application
| classes should use.
|
| NOTE: changing this will require manually modifying the
| existing namespaces of App\* namespaced-classes.
*/
defined('APP_NAMESPACE') || define('APP_NAMESPACE', 'App');
/*
| --------------------------------------------------------------------------
| Composer Path
| --------------------------------------------------------------------------
|
| The path that Composer's autoload file is expected to live. By default,
| the vendor folder is in the Root directory, but you can customize that here.
*/
defined('COMPOSER_PATH') || define('COMPOSER_PATH', ROOTPATH . 'vendor/autoload.php');
/*
|--------------------------------------------------------------------------
| Timing Constants
|--------------------------------------------------------------------------
|
| Provide simple ways to work with the myriad of PHP functions that
| require information to be in seconds.
*/
defined('SECOND') || define('SECOND', 1);
defined('MINUTE') || define('MINUTE', 60);
defined('HOUR') || define('HOUR', 3600);
defined('DAY') || define('DAY', 86400);
defined('WEEK') || define('WEEK', 604800);
defined('MONTH') || define('MONTH', 2_592_000);
defined('YEAR') || define('YEAR', 31_536_000);
defined('DECADE') || define('DECADE', 315_360_000);
/*
| --------------------------------------------------------------------------
| Exit Status Codes
| --------------------------------------------------------------------------
|
| Used to indicate the conditions under which the script is exit()ing.
| While there is no universal standard for error codes, there are some
| broad conventions. Three such conventions are mentioned below, for
| those who wish to make use of them. The CodeIgniter defaults were
| chosen for the least overlap with these conventions, while still
| leaving room for others to be defined in future versions and user
| applications.
|
| The three main conventions used for determining exit status codes
| are as follows:
|
| Standard C/C++ Library (stdlibc):
| http://www.gnu.org/software/libc/manual/html_node/Exit-Status.html
| (This link also contains other GNU-specific conventions)
| BSD sysexits.h:
| http://www.gsp.com/cgi-bin/man.cgi?section=3&topic=sysexits
| Bash scripting:
| http://tldp.org/LDP/abs/html/exitcodes.html
|
*/
defined('EXIT_SUCCESS') || define('EXIT_SUCCESS', 0); // no errors
defined('EXIT_ERROR') || define('EXIT_ERROR', 1); // generic error
defined('EXIT_CONFIG') || define('EXIT_CONFIG', 3); // configuration error
defined('EXIT_UNKNOWN_FILE') || define('EXIT_UNKNOWN_FILE', 4); // file not found
defined('EXIT_UNKNOWN_CLASS') || define('EXIT_UNKNOWN_CLASS', 5); // unknown class
defined('EXIT_UNKNOWN_METHOD') || define('EXIT_UNKNOWN_METHOD', 6); // unknown class member
defined('EXIT_USER_INPUT') || define('EXIT_USER_INPUT', 7); // invalid user input
defined('EXIT_DATABASE') || define('EXIT_DATABASE', 8); // database error
defined('EXIT__AUTO_MIN') || define('EXIT__AUTO_MIN', 9); // lowest automatically-assigned error code
defined('EXIT__AUTO_MAX') || define('EXIT__AUTO_MAX', 125); // highest automatically-assigned error code

View File

@@ -0,0 +1,216 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Stores the default settings for the ContentSecurityPolicy, if you
* choose to use it. The values here will be read in and set as defaults
* for the site. If needed, they can be overridden on a page-by-page basis.
*
* Suggested reference for explanations:
*
* @see https://www.html5rocks.com/en/tutorials/security/content-security-policy/
*/
class ContentSecurityPolicy extends BaseConfig
{
// -------------------------------------------------------------------------
// Broadbrush CSP management
// -------------------------------------------------------------------------
/**
* Default CSP report context
*/
public bool $reportOnly = false;
/**
* Specifies a URL where a browser will send reports
* when a content security policy is violated.
*/
public ?string $reportURI = null;
/**
* Specifies a reporting endpoint to which violation reports ought to be sent.
*/
public ?string $reportTo = null;
/**
* Instructs user agents to rewrite URL schemes, changing
* HTTP to HTTPS. This directive is for websites with
* large numbers of old URLs that need to be rewritten.
*/
public bool $upgradeInsecureRequests = false;
// -------------------------------------------------------------------------
// CSP DIRECTIVES SETTINGS
// NOTE: once you set a policy to 'none', it cannot be further restricted
// -------------------------------------------------------------------------
/**
* Will default to `'self'` if not overridden
*
* @var list<string>|string|null
*/
public $defaultSrc;
/**
* Lists allowed scripts' URLs.
*
* @var list<string>|string
*/
public $scriptSrc = 'self';
/**
* Specifies valid sources for JavaScript <script> elements.
*
* @var list<string>|string
*/
public array|string $scriptSrcElem = 'self';
/**
* Specifies valid sources for JavaScript inline event
* handlers and JavaScript URLs.
*
* @var list<string>|string
*/
public array|string $scriptSrcAttr = 'self';
/**
* Lists allowed stylesheets' URLs.
*
* @var list<string>|string
*/
public $styleSrc = 'self';
/**
* Specifies valid sources for stylesheets <link> elements.
*
* @var list<string>|string
*/
public array|string $styleSrcElem = 'self';
/**
* Specifies valid sources for stylesheets inline
* style attributes and `<style>` elements.
*
* @var list<string>|string
*/
public array|string $styleSrcAttr = 'self';
/**
* Defines the origins from which images can be loaded.
*
* @var list<string>|string
*/
public $imageSrc = 'self';
/**
* Restricts the URLs that can appear in a page's `<base>` element.
*
* Will default to self if not overridden
*
* @var list<string>|string|null
*/
public $baseURI;
/**
* Lists the URLs for workers and embedded frame contents
*
* @var list<string>|string
*/
public $childSrc = 'self';
/**
* Limits the origins that you can connect to (via XHR,
* WebSockets, and EventSource).
*
* @var list<string>|string
*/
public $connectSrc = 'self';
/**
* Specifies the origins that can serve web fonts.
*
* @var list<string>|string
*/
public $fontSrc;
/**
* Lists valid endpoints for submission from `<form>` tags.
*
* @var list<string>|string
*/
public $formAction = 'self';
/**
* Specifies the sources that can embed the current page.
* This directive applies to `<frame>`, `<iframe>`, `<embed>`,
* and `<applet>` tags. This directive can't be used in
* `<meta>` tags and applies only to non-HTML resources.
*
* @var list<string>|string|null
*/
public $frameAncestors;
/**
* The frame-src directive restricts the URLs which may
* be loaded into nested browsing contexts.
*
* @var list<string>|string|null
*/
public $frameSrc;
/**
* Restricts the origins allowed to deliver video and audio.
*
* @var list<string>|string|null
*/
public $mediaSrc;
/**
* Allows control over Flash and other plugins.
*
* @var list<string>|string
*/
public $objectSrc = 'self';
/**
* @var list<string>|string|null
*/
public $manifestSrc;
/**
* @var list<string>|string
*/
public array|string $workerSrc = [];
/**
* Limits the kinds of plugins a page may invoke.
*
* @var list<string>|string|null
*/
public $pluginTypes;
/**
* List of actions allowed.
*
* @var list<string>|string|null
*/
public $sandbox;
/**
* Nonce placeholder for style tags.
*/
public string $styleNonceTag = '{csp-style-nonce}';
/**
* Nonce placeholder for script tags.
*/
public string $scriptNonceTag = '{csp-script-nonce}';
/**
* Replace nonce tag automatically?
*/
public bool $autoNonce = true;
}

107
app/Config/Cookie.php Normal file
View File

@@ -0,0 +1,107 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use DateTimeInterface;
class Cookie extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Cookie Prefix
* --------------------------------------------------------------------------
*
* Set a cookie name prefix if you need to avoid collisions.
*/
public string $prefix = '';
/**
* --------------------------------------------------------------------------
* Cookie Expires Timestamp
* --------------------------------------------------------------------------
*
* Default expires timestamp for cookies. Setting this to `0` will mean the
* cookie will not have the `Expires` attribute and will behave as a session
* cookie.
*
* @var DateTimeInterface|int|string
*/
public $expires = 0;
/**
* --------------------------------------------------------------------------
* Cookie Path
* --------------------------------------------------------------------------
*
* Typically will be a forward slash.
*/
public string $path = '/';
/**
* --------------------------------------------------------------------------
* Cookie Domain
* --------------------------------------------------------------------------
*
* Set to `.your-domain.com` for site-wide cookies.
*/
public string $domain = '';
/**
* --------------------------------------------------------------------------
* Cookie Secure
* --------------------------------------------------------------------------
*
* Cookie will only be set if a secure HTTPS connection exists.
*/
public bool $secure = false;
/**
* --------------------------------------------------------------------------
* Cookie HTTPOnly
* --------------------------------------------------------------------------
*
* Cookie will only be accessible via HTTP(S) (no JavaScript).
*/
public bool $httponly = true;
/**
* --------------------------------------------------------------------------
* Cookie SameSite
* --------------------------------------------------------------------------
*
* Configure cookie SameSite setting. Allowed values are:
* - None
* - Lax
* - Strict
* - ''
*
* Alternatively, you can use the constant names:
* - `Cookie::SAMESITE_NONE`
* - `Cookie::SAMESITE_LAX`
* - `Cookie::SAMESITE_STRICT`
*
* Defaults to `Lax` for compatibility with modern browsers. Setting `''`
* (empty string) means default SameSite attribute set by browsers (`Lax`)
* will be set on cookies. If set to `None`, `$secure` must also be set.
*
* @var ''|'Lax'|'None'|'Strict'
*/
public string $samesite = 'Lax';
/**
* --------------------------------------------------------------------------
* Cookie Raw
* --------------------------------------------------------------------------
*
* This flag allows setting a "raw" cookie, i.e., its name and value are
* not URL encoded using `rawurlencode()`.
*
* If this is set to `true`, cookie names should be compliant of RFC 2616's
* list of allowed characters.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#attributes
* @see https://tools.ietf.org/html/rfc2616#section-2.2
*/
public bool $raw = false;
}

105
app/Config/Cors.php Normal file
View File

@@ -0,0 +1,105 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Cross-Origin Resource Sharing (CORS) Configuration
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
*/
class Cors extends BaseConfig
{
/**
* The default CORS configuration.
*
* @var array{
* allowedOrigins: list<string>,
* allowedOriginsPatterns: list<string>,
* supportsCredentials: bool,
* allowedHeaders: list<string>,
* exposedHeaders: list<string>,
* allowedMethods: list<string>,
* maxAge: int,
* }
*/
public array $default = [
/**
* Origins for the `Access-Control-Allow-Origin` header.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
*
* E.g.:
* - ['http://localhost:8080']
* - ['https://www.example.com']
*/
'allowedOrigins' => ['*'], // Allow all origins for mobile app development
/**
* Origin regex patterns for the `Access-Control-Allow-Origin` header.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
*
* NOTE: A pattern specified here is part of a regular expression. It will
* be actually `#\A<pattern>\z#`.
*
* E.g.:
* - ['https://\w+\.example\.com']
*/
'allowedOriginsPatterns' => [],
/**
* Weather to send the `Access-Control-Allow-Credentials` header.
*
* The Access-Control-Allow-Credentials response header tells browsers whether
* the server allows cross-origin HTTP requests to include credentials.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
*/
'supportsCredentials' => false,
/**
* Set headers to allow.
*
* The Access-Control-Allow-Headers response header is used in response to
* a preflight request which includes the Access-Control-Request-Headers to
* indicate which HTTP headers can be used during the actual request.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
*/
'allowedHeaders' => ['Content-Type', 'Authorization', 'X-Requested-With'],
/**
* Set headers to expose.
*
* The Access-Control-Expose-Headers response header allows a server to
* indicate which response headers should be made available to scripts running
* in the browser, in response to a cross-origin request.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
*/
'exposedHeaders' => [],
/**
* Set methods to allow.
*
* The Access-Control-Allow-Methods response header specifies one or more
* methods allowed when accessing a resource in response to a preflight
* request.
*
* E.g.:
* - ['GET', 'POST', 'PUT', 'DELETE']
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods
*/
'allowedMethods' => ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'],
/**
* Set how many seconds the results of a preflight request can be cached.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age
*/
'maxAge' => 7200,
];
}

229
app/Config/Database.php Normal file
View File

@@ -0,0 +1,229 @@
<?php
namespace Config;
use CodeIgniter\Database\Config;
/**
* Database Configuration
*/
class Database extends Config
{
/**
* The directory that holds the Migrations and Seeds directories.
*/
public string $filesPath = APPPATH . 'Database' . DIRECTORY_SEPARATOR;
/**
* Lets you choose which connection group to use if no other is specified.
*/
public string $defaultGroup = 'default';
/**
* The default database connection.
*
* @var array<string, mixed>
*/
public array $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => '',
'password' => '',
'database' => '',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => true,
'charset' => 'utf8mb4',
'DBCollat' => 'utf8mb4_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
'numberNative' => false,
'foundRows' => false,
'dateFormat' => [
'date' => 'Y-m-d',
'datetime' => 'Y-m-d H:i:s',
'time' => 'H:i:s',
],
];
/**
* Merge .env database config into default (for CLI/env override)
*/
public function __construct()
{
parent::__construct();
$hostname = env('database.default.hostname') ?? env('database_default_hostname');
if ($hostname !== null && $hostname !== '') {
$this->default['hostname'] = $hostname;
}
$database = env('database.default.database') ?? env('database_default_database');
if ($database !== null && $database !== '') {
$this->default['database'] = $database;
}
$username = env('database.default.username') ?? env('database_default_username');
if ($username !== null && $username !== '') {
$this->default['username'] = $username;
}
$password = env('database.default.password') ?? env('database_default_password');
if ($password !== null) {
$this->default['password'] = (string) $password;
}
$driver = env('database.default.DBDriver') ?? env('database_default_DBDriver');
if ($driver !== null && $driver !== '') {
$this->default['DBDriver'] = $driver;
}
$port = env('database.default.port') ?? env('database_default_port');
if ($port !== null && $port !== '') {
$this->default['port'] = (int) $port;
}
if (ENVIRONMENT === 'testing') {
$this->defaultGroup = 'tests';
}
}
// /**
// * Sample database connection for SQLite3.
// *
// * @var array<string, mixed>
// */
// public array $default = [
// 'database' => 'database.db',
// 'DBDriver' => 'SQLite3',
// 'DBPrefix' => '',
// 'DBDebug' => true,
// 'swapPre' => '',
// 'failover' => [],
// 'foreignKeys' => true,
// 'busyTimeout' => 1000,
// 'synchronous' => null,
// 'dateFormat' => [
// 'date' => 'Y-m-d',
// 'datetime' => 'Y-m-d H:i:s',
// 'time' => 'H:i:s',
// ],
// ];
// /**
// * Sample database connection for Postgre.
// *
// * @var array<string, mixed>
// */
// public array $default = [
// 'DSN' => '',
// 'hostname' => 'localhost',
// 'username' => 'root',
// 'password' => 'root',
// 'database' => 'ci4',
// 'schema' => 'public',
// 'DBDriver' => 'Postgre',
// 'DBPrefix' => '',
// 'pConnect' => false,
// 'DBDebug' => true,
// 'charset' => 'utf8',
// 'swapPre' => '',
// 'failover' => [],
// 'port' => 5432,
// 'dateFormat' => [
// 'date' => 'Y-m-d',
// 'datetime' => 'Y-m-d H:i:s',
// 'time' => 'H:i:s',
// ],
// ];
// /**
// * Sample database connection for SQLSRV.
// *
// * @var array<string, mixed>
// */
// public array $default = [
// 'DSN' => '',
// 'hostname' => 'localhost',
// 'username' => 'root',
// 'password' => 'root',
// 'database' => 'ci4',
// 'schema' => 'dbo',
// 'DBDriver' => 'SQLSRV',
// 'DBPrefix' => '',
// 'pConnect' => false,
// 'DBDebug' => true,
// 'charset' => 'utf8',
// 'swapPre' => '',
// 'encrypt' => false,
// 'failover' => [],
// 'port' => 1433,
// 'dateFormat' => [
// 'date' => 'Y-m-d',
// 'datetime' => 'Y-m-d H:i:s',
// 'time' => 'H:i:s',
// ],
// ];
// /**
// * Sample database connection for OCI8.
// *
// * You may need the following environment variables:
// * NLS_LANG = 'AMERICAN_AMERICA.UTF8'
// * NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS'
// * NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS'
// * NLS_TIMESTAMP_TZ_FORMAT = 'YYYY-MM-DD HH24:MI:SS'
// *
// * @var array<string, mixed>
// */
// public array $default = [
// 'DSN' => 'localhost:1521/XEPDB1',
// 'username' => 'root',
// 'password' => 'root',
// 'DBDriver' => 'OCI8',
// 'DBPrefix' => '',
// 'pConnect' => false,
// 'DBDebug' => true,
// 'charset' => 'AL32UTF8',
// 'swapPre' => '',
// 'failover' => [],
// 'dateFormat' => [
// 'date' => 'Y-m-d',
// 'datetime' => 'Y-m-d H:i:s',
// 'time' => 'H:i:s',
// ],
// ];
/**
* This database connection is used when running PHPUnit database tests.
*
* @var array<string, mixed>
*/
public array $tests = [
'DSN' => '',
'hostname' => '127.0.0.1',
'username' => '',
'password' => '',
'database' => ':memory:',
'DBDriver' => 'SQLite3',
'DBPrefix' => 'db_', // Needed to ensure we're working correctly with prefixes live. DO NOT REMOVE FOR CI DEVS
'pConnect' => false,
'DBDebug' => true,
'charset' => 'utf8',
'DBCollat' => '',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
'foreignKeys' => true,
'busyTimeout' => 1000,
'synchronous' => null,
'dateFormat' => [
'date' => 'Y-m-d',
'datetime' => 'Y-m-d H:i:s',
'time' => 'H:i:s',
],
];
}

43
app/Config/DocTypes.php Normal file
View File

@@ -0,0 +1,43 @@
<?php
namespace Config;
class DocTypes
{
/**
* List of valid document types.
*
* @var array<string, string>
*/
public array $list = [
'xhtml11' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">',
'xhtml1-strict' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
'xhtml1-trans' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
'xhtml1-frame' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">',
'xhtml-basic11' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">',
'html5' => '<!DOCTYPE html>',
'html4-strict' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">',
'html4-trans' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">',
'html4-frame' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">',
'mathml1' => '<!DOCTYPE math SYSTEM "http://www.w3.org/Math/DTD/mathml1/mathml.dtd">',
'mathml2' => '<!DOCTYPE math PUBLIC "-//W3C//DTD MathML 2.0//EN" "http://www.w3.org/Math/DTD/mathml2/mathml2.dtd">',
'svg10' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">',
'svg11' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">',
'svg11-basic' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1 Basic//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-basic.dtd">',
'svg11-tiny' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1 Tiny//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd">',
'xhtml-math-svg-xh' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">',
'xhtml-math-svg-sh' => '<!DOCTYPE svg:svg PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">',
'xhtml-rdfa-1' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">',
'xhtml-rdfa-2' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.1//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-2.dtd">',
];
/**
* Whether to remove the solidus (`/`) character for void HTML elements (e.g. `<input>`)
* for HTML5 compatibility.
*
* Set to:
* `true` - to be HTML5 compatible
* `false` - to be XHTML compatible
*/
public bool $html5 = true;
}

126
app/Config/Email.php Normal file
View File

@@ -0,0 +1,126 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Email extends BaseConfig
{
public string $fromEmail = '';
public string $fromName = '';
public string $recipients = '';
/**
* The "user agent"
*/
public string $userAgent = 'CodeIgniter';
/**
* The mail sending protocol: mail, sendmail, smtp
*/
public string $protocol = 'mail';
/**
* The server path to Sendmail.
*/
public string $mailPath = '/usr/sbin/sendmail';
/**
* SMTP Server Hostname
*/
public string $SMTPHost = '';
/**
* Which SMTP authentication method to use: login, plain
*/
public string $SMTPAuthMethod = 'login';
/**
* SMTP Username
*/
public string $SMTPUser = '';
/**
* SMTP Password
*/
public string $SMTPPass = '';
/**
* SMTP Port
*/
public int $SMTPPort = 25;
/**
* SMTP Timeout (in seconds)
*/
public int $SMTPTimeout = 5;
/**
* Enable persistent SMTP connections
*/
public bool $SMTPKeepAlive = false;
/**
* SMTP Encryption.
*
* @var string '', 'tls' or 'ssl'. 'tls' will issue a STARTTLS command
* to the server. 'ssl' means implicit SSL. Connection on port
* 465 should set this to ''.
*/
public string $SMTPCrypto = 'tls';
/**
* Enable word-wrap
*/
public bool $wordWrap = true;
/**
* Character count to wrap at
*/
public int $wrapChars = 76;
/**
* Type of mail, either 'text' or 'html'
*/
public string $mailType = 'text';
/**
* Character set (utf-8, iso-8859-1, etc.)
*/
public string $charset = 'UTF-8';
/**
* Whether to validate the email address
*/
public bool $validate = false;
/**
* Email Priority. 1 = highest. 5 = lowest. 3 = normal
*/
public int $priority = 3;
/**
* Newline character. (Use “\r\n” to comply with RFC 822)
*/
public string $CRLF = "\r\n";
/**
* Newline character. (Use “\r\n” to comply with RFC 822)
*/
public string $newline = "\r\n";
/**
* Enable BCC Batch Mode.
*/
public bool $BCCBatchMode = false;
/**
* Number of emails in each BCC batch
*/
public int $BCCBatchSize = 200;
/**
* Enable notify message from server
*/
public bool $DSN = false;
}

109
app/Config/Encryption.php Normal file
View File

@@ -0,0 +1,109 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Encryption configuration.
*
* These are the settings used for encryption, if you don't pass a parameter
* array to the encrypter for creation/initialization.
*/
class Encryption extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Encryption Key Starter
* --------------------------------------------------------------------------
*
* If you use the Encryption class you must set an encryption key (seed).
* You need to ensure it is long enough for the cipher and mode you plan to use.
* See the user guide for more info.
*/
public string $key = '';
/**
* --------------------------------------------------------------------------
* Previous Encryption Keys
* --------------------------------------------------------------------------
*
* When rotating encryption keys, add old keys here to maintain ability
* to decrypt data encrypted with previous keys. Encryption always uses
* the current $key. Decryption tries current key first, then falls back
* to previous keys if decryption fails.
*
* In .env file, use comma-separated string:
* encryption.previousKeys = hex2bin:9be8c64fcea509867...,hex2bin:3f5a1d8e9c2b7a4f6...
*
* @var list<string>|string
*/
public array|string $previousKeys = '';
/**
* --------------------------------------------------------------------------
* Encryption Driver to Use
* --------------------------------------------------------------------------
*
* One of the supported encryption drivers.
*
* Available drivers:
* - OpenSSL
* - Sodium
*/
public string $driver = 'OpenSSL';
/**
* --------------------------------------------------------------------------
* SodiumHandler's Padding Length in Bytes
* --------------------------------------------------------------------------
*
* This is the number of bytes that will be padded to the plaintext message
* before it is encrypted. This value should be greater than zero.
*
* See the user guide for more information on padding.
*/
public int $blockSize = 16;
/**
* --------------------------------------------------------------------------
* Encryption digest
* --------------------------------------------------------------------------
*
* HMAC digest to use, e.g. 'SHA512' or 'SHA256'. Default value is 'SHA512'.
*/
public string $digest = 'SHA512';
/**
* Whether the cipher-text should be raw. If set to false, then it will be base64 encoded.
* This setting is only used by OpenSSLHandler.
*
* Set to false for CI3 Encryption compatibility.
*/
public bool $rawData = true;
/**
* Encryption key info.
* This setting is only used by OpenSSLHandler.
*
* Set to 'encryption' for CI3 Encryption compatibility.
*/
public string $encryptKeyInfo = '';
/**
* Authentication key info.
* This setting is only used by OpenSSLHandler.
*
* Set to 'authentication' for CI3 Encryption compatibility.
*/
public string $authKeyInfo = '';
/**
* Cipher to use.
* This setting is only used by OpenSSLHandler.
*
* Set to 'AES-128-CBC' to decrypt encrypted data that encrypted
* by CI3 Encryption default configuration.
*/
public string $cipher = 'AES-256-CTR';
}

55
app/Config/Events.php Normal file
View File

@@ -0,0 +1,55 @@
<?php
namespace Config;
use CodeIgniter\Events\Events;
use CodeIgniter\Exceptions\FrameworkException;
use CodeIgniter\HotReloader\HotReloader;
/*
* --------------------------------------------------------------------
* Application Events
* --------------------------------------------------------------------
* Events allow you to tap into the execution of the program without
* modifying or extending core files. This file provides a central
* location to define your events, though they can always be added
* at run-time, also, if needed.
*
* You create code that can execute by subscribing to events with
* the 'on()' method. This accepts any form of callable, including
* Closures, that will be executed when the event is triggered.
*
* Example:
* Events::on('create', [$myInstance, 'myMethod']);
*/
Events::on('pre_system', static function (): void {
if (ENVIRONMENT !== 'testing') {
if (ini_get('zlib.output_compression')) {
throw FrameworkException::forEnabledZlibOutputCompression();
}
while (ob_get_level() > 0) {
ob_end_flush();
}
ob_start(static fn ($buffer) => $buffer);
}
/*
* --------------------------------------------------------------------
* Debug Toolbar Listeners.
* --------------------------------------------------------------------
* If you delete, they will no longer be collected.
*/
if (CI_DEBUG && ! is_cli()) {
Events::on('DBQuery', 'CodeIgniter\Debug\Toolbar\Collectors\Database::collect');
service('toolbar')->respond();
// Hot Reload route - for framework use on the hot reloader.
if (ENVIRONMENT === 'development') {
service('routes')->get('__hot-reload', static function (): void {
(new HotReloader())->run();
});
}
}
});

106
app/Config/Exceptions.php Normal file
View File

@@ -0,0 +1,106 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Debug\ExceptionHandler;
use CodeIgniter\Debug\ExceptionHandlerInterface;
use Psr\Log\LogLevel;
use Throwable;
/**
* Setup how the exception handler works.
*/
class Exceptions extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* LOG EXCEPTIONS?
* --------------------------------------------------------------------------
* If true, then exceptions will be logged
* through Services::Log.
*
* Default: true
*/
public bool $log = true;
/**
* --------------------------------------------------------------------------
* DO NOT LOG STATUS CODES
* --------------------------------------------------------------------------
* Any status codes here will NOT be logged if logging is turned on.
* By default, only 404 (Page Not Found) exceptions are ignored.
*
* @var list<int>
*/
public array $ignoreCodes = [404];
/**
* --------------------------------------------------------------------------
* Error Views Path
* --------------------------------------------------------------------------
* This is the path to the directory that contains the 'cli' and 'html'
* directories that hold the views used to generate errors.
*
* Default: APPPATH.'Views/errors'
*/
public string $errorViewPath = APPPATH . 'Views/errors';
/**
* --------------------------------------------------------------------------
* HIDE FROM DEBUG TRACE
* --------------------------------------------------------------------------
* Any data that you would like to hide from the debug trace.
* In order to specify 2 levels, use "/" to separate.
* ex. ['server', 'setup/password', 'secret_token']
*
* @var list<string>
*/
public array $sensitiveDataInTrace = [];
/**
* --------------------------------------------------------------------------
* WHETHER TO THROW AN EXCEPTION ON DEPRECATED ERRORS
* --------------------------------------------------------------------------
* If set to `true`, DEPRECATED errors are only logged and no exceptions are
* thrown. This option also works for user deprecations.
*/
public bool $logDeprecations = true;
/**
* --------------------------------------------------------------------------
* LOG LEVEL THRESHOLD FOR DEPRECATIONS
* --------------------------------------------------------------------------
* If `$logDeprecations` is set to `true`, this sets the log level
* to which the deprecation will be logged. This should be one of the log
* levels recognized by PSR-3.
*
* The related `Config\Logger::$threshold` should be adjusted, if needed,
* to capture logging the deprecations.
*/
public string $deprecationLogLevel = LogLevel::WARNING;
/*
* DEFINE THE HANDLERS USED
* --------------------------------------------------------------------------
* Given the HTTP status code, returns exception handler that
* should be used to deal with this error. By default, it will run CodeIgniter's
* default handler and display the error information in the expected format
* for CLI, HTTP, or AJAX requests, as determined by is_cli() and the expected
* response format.
*
* Custom handlers can be returned if you want to handle one or more specific
* error codes yourself like:
*
* if (in_array($statusCode, [400, 404, 500])) {
* return new \App\Libraries\MyExceptionHandler();
* }
* if ($exception instanceOf PageNotFoundException) {
* return new \App\Libraries\MyExceptionHandler();
* }
*/
public function handler(int $statusCode, Throwable $exception): ExceptionHandlerInterface
{
return new ExceptionHandler($this);
}
}

37
app/Config/Feature.php Normal file
View File

@@ -0,0 +1,37 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Enable/disable backward compatibility breaking features.
*/
class Feature extends BaseConfig
{
/**
* Use improved new auto routing instead of the legacy version.
*/
public bool $autoRoutesImproved = true;
/**
* Use filter execution order in 4.4 or before.
*/
public bool $oldFilterOrder = false;
/**
* The behavior of `limit(0)` in Query Builder.
*
* If true, `limit(0)` returns all records. (the behavior of 4.4.x or before in version 4.x.)
* If false, `limit(0)` returns no records. (the behavior of 3.1.9 or later in version 3.x.)
*/
public bool $limitZeroAsAll = true;
/**
* Use strict location negotiation.
*
* By default, the locale is selected based on a loose comparison of the language code (ISO 639-1)
* Enabling strict comparison will also consider the region code (ISO 3166-1 alpha-2).
*/
public bool $strictLocaleNegotiation = false;
}

128
app/Config/Filters.php Normal file
View File

@@ -0,0 +1,128 @@
<?php
namespace Config;
use CodeIgniter\Config\Filters as BaseFilters;
use CodeIgniter\Filters\Cors;
use CodeIgniter\Filters\CSRF;
use CodeIgniter\Filters\DebugToolbar;
use CodeIgniter\Filters\ForceHTTPS;
use CodeIgniter\Filters\Honeypot;
use CodeIgniter\Filters\InvalidChars;
use CodeIgniter\Filters\PageCache;
use CodeIgniter\Filters\PerformanceMetrics;
use CodeIgniter\Filters\SecureHeaders;
use App\Filters\AdminOnlyFilter;
use App\Filters\MobileStudentFacePhotoFilter;
use App\Filters\DashboardAdminPageFilter;
use App\Filters\DashboardAuthFilter;
use App\Filters\DashboardPageAuthFilter;
class Filters extends BaseFilters
{
/**
* Configures aliases for Filter classes to
* make reading things nicer and simpler.
*
* @var array<string, class-string|list<class-string>>
*
* [filter_name => classname]
* or [filter_name => [classname1, classname2, ...]]
*/
public array $aliases = [
'csrf' => CSRF::class,
'toolbar' => DebugToolbar::class,
'honeypot' => Honeypot::class,
'invalidchars' => InvalidChars::class,
'secureheaders' => SecureHeaders::class,
'cors' => Cors::class,
'forcehttps' => ForceHTTPS::class,
'pagecache' => PageCache::class,
'performance' => PerformanceMetrics::class,
'dashboard_auth' => DashboardAuthFilter::class,
'dashboard_page_auth' => DashboardPageAuthFilter::class,
'admin_only' => AdminOnlyFilter::class,
'dashboard_admin_page' => DashboardAdminPageFilter::class,
'mobile_student_face' => MobileStudentFacePhotoFilter::class,
];
/**
* List of special required filters.
*
* The filters listed here are special. They are applied before and after
* other kinds of filters, and always applied even if a route does not exist.
*
* Filters set by default provide framework functionality. If removed,
* those functions will no longer work.
*
* @see https://codeigniter.com/user_guide/incoming/filters.html#provided-filters
*
* @var array{before: list<string>, after: list<string>}
*/
public array $required = [
'before' => [
'forcehttps', // Force Global Secure Requests
'pagecache', // Web Page Caching
],
'after' => [
'pagecache', // Web Page Caching
'performance', // Performance Metrics
'toolbar', // Debug Toolbar
],
];
/**
* List of filter aliases that are always
* applied before and after every request.
*
* @var array{
* before: array<string, array{except: list<string>|string}>|list<string>,
* after: array<string, array{except: list<string>|string}>|list<string>
* }
*/
public array $globals = [
'before' => [
'cors', // Enable CORS for all requests
// 'honeypot',
// 'csrf',
// 'invalidchars',
],
'after' => [
// 'honeypot',
// 'secureheaders',
],
];
/**
* List of filter aliases that works on a
* particular HTTP method (GET, POST, etc.).
*
* Example:
* 'POST' => ['foo', 'bar']
*
* If you use this, you should disable auto-routing because auto-routing
* permits any HTTP method to access a controller. Accessing the controller
* with a method you don't expect could bypass the filter.
*
* @var array<string, list<string>>
*/
public array $methods = [];
/**
* List of filter aliases that should run on any
* before or after URI patterns.
*
* Example:
* 'isLoggedIn' => ['before' => ['account/*', 'profiles/*']]
*
* @var array<string, array<string, list<string>>>
*/
public array $filters = [
'dashboard_auth' => [
'before' => ['api/dashboard/*'],
],
'mobile_student_face' => [
'before' => ['api/mobile/student/face-photo'],
],
];
}

View File

@@ -0,0 +1,12 @@
<?php
namespace Config;
use CodeIgniter\Config\ForeignCharacters as BaseForeignCharacters;
/**
* @immutable
*/
class ForeignCharacters extends BaseForeignCharacters
{
}

73
app/Config/Format.php Normal file
View File

@@ -0,0 +1,73 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Format\JSONFormatter;
use CodeIgniter\Format\XMLFormatter;
class Format extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Available Response Formats
* --------------------------------------------------------------------------
*
* When you perform content negotiation with the request, these are the
* available formats that your application supports. This is currently
* only used with the API\ResponseTrait. A valid Formatter must exist
* for the specified format.
*
* These formats are only checked when the data passed to the respond()
* method is an array.
*
* @var list<string>
*/
public array $supportedResponseFormats = [
'application/json',
'application/xml', // machine-readable XML
'text/xml', // human-readable XML
];
/**
* --------------------------------------------------------------------------
* Formatters
* --------------------------------------------------------------------------
*
* Lists the class to use to format responses with of a particular type.
* For each mime type, list the class that should be used. Formatters
* can be retrieved through the getFormatter() method.
*
* @var array<string, string>
*/
public array $formatters = [
'application/json' => JSONFormatter::class,
'application/xml' => XMLFormatter::class,
'text/xml' => XMLFormatter::class,
];
/**
* --------------------------------------------------------------------------
* Formatters Options
* --------------------------------------------------------------------------
*
* Additional Options to adjust default formatters behaviour.
* For each mime type, list the additional options that should be used.
*
* @var array<string, int>
*/
public array $formatterOptions = [
'application/json' => JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES,
'application/xml' => 0,
'text/xml' => 0,
];
/**
* --------------------------------------------------------------------------
* Maximum depth for JSON encoding.
* --------------------------------------------------------------------------
*
* This value determines how deep the JSON encoder will traverse nested structures.
*/
public int $jsonEncodeDepth = 512;
}

44
app/Config/Generators.php Normal file
View File

@@ -0,0 +1,44 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Generators extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Generator Commands' Views
* --------------------------------------------------------------------------
*
* This array defines the mapping of generator commands to the view files
* they are using. If you need to customize them for your own, copy these
* view files in your own folder and indicate the location here.
*
* You will notice that the views have special placeholders enclosed in
* curly braces `{...}`. These placeholders are used internally by the
* generator commands in processing replacements, thus you are warned
* not to delete them or modify the names. If you will do so, you may
* end up disrupting the scaffolding process and throw errors.
*
* YOU HAVE BEEN WARNED!
*
* @var array<string, array<string, string>|string>
*/
public array $views = [
'make:cell' => [
'class' => 'CodeIgniter\Commands\Generators\Views\cell.tpl.php',
'view' => 'CodeIgniter\Commands\Generators\Views\cell_view.tpl.php',
],
'make:command' => 'CodeIgniter\Commands\Generators\Views\command.tpl.php',
'make:config' => 'CodeIgniter\Commands\Generators\Views\config.tpl.php',
'make:controller' => 'CodeIgniter\Commands\Generators\Views\controller.tpl.php',
'make:entity' => 'CodeIgniter\Commands\Generators\Views\entity.tpl.php',
'make:filter' => 'CodeIgniter\Commands\Generators\Views\filter.tpl.php',
'make:migration' => 'CodeIgniter\Commands\Generators\Views\migration.tpl.php',
'make:model' => 'CodeIgniter\Commands\Generators\Views\model.tpl.php',
'make:seeder' => 'CodeIgniter\Commands\Generators\Views\seeder.tpl.php',
'make:validation' => 'CodeIgniter\Commands\Generators\Views\validation.tpl.php',
'session:migration' => 'CodeIgniter\Commands\Generators\Views\migration.tpl.php',
];
}

42
app/Config/Honeypot.php Normal file
View File

@@ -0,0 +1,42 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Honeypot extends BaseConfig
{
/**
* Makes Honeypot visible or not to human
*/
public bool $hidden = true;
/**
* Honeypot Label Content
*/
public string $label = 'Fill This Field';
/**
* Honeypot Field Name
*/
public string $name = 'honeypot';
/**
* Honeypot HTML Template
*/
public string $template = '<label>{label}</label><input type="text" name="{name}" value="">';
/**
* Honeypot container
*
* If you enabled CSP, you can remove `style="display:none"`.
*/
public string $container = '<div style="display:none">{template}</div>';
/**
* The id attribute for Honeypot container tag
*
* Used when CSP is enabled.
*/
public string $containerId = 'hpc';
}

40
app/Config/Hostnames.php Normal file
View File

@@ -0,0 +1,40 @@
<?php
namespace Config;
class Hostnames
{
// List of known two-part TLDs for subdomain extraction
public const TWO_PART_TLDS = [
'co.uk', 'org.uk', 'gov.uk', 'ac.uk', 'sch.uk', 'ltd.uk', 'plc.uk',
'com.au', 'net.au', 'org.au', 'edu.au', 'gov.au', 'asn.au', 'id.au',
'co.jp', 'ac.jp', 'go.jp', 'or.jp', 'ne.jp', 'gr.jp',
'co.nz', 'org.nz', 'govt.nz', 'ac.nz', 'net.nz', 'geek.nz', 'maori.nz', 'school.nz',
'co.in', 'net.in', 'org.in', 'ind.in', 'ac.in', 'gov.in', 'res.in',
'com.cn', 'net.cn', 'org.cn', 'gov.cn', 'edu.cn',
'com.sg', 'net.sg', 'org.sg', 'gov.sg', 'edu.sg', 'per.sg',
'co.za', 'org.za', 'gov.za', 'ac.za', 'net.za',
'co.kr', 'or.kr', 'go.kr', 'ac.kr', 'ne.kr', 'pe.kr',
'co.th', 'or.th', 'go.th', 'ac.th', 'net.th', 'in.th',
'com.my', 'net.my', 'org.my', 'edu.my', 'gov.my', 'mil.my', 'name.my',
'com.mx', 'org.mx', 'net.mx', 'edu.mx', 'gob.mx',
'com.br', 'net.br', 'org.br', 'gov.br', 'edu.br', 'art.br', 'eng.br',
'co.il', 'org.il', 'ac.il', 'gov.il', 'net.il', 'muni.il',
'co.id', 'or.id', 'ac.id', 'go.id', 'net.id', 'web.id', 'my.id',
'com.hk', 'edu.hk', 'gov.hk', 'idv.hk', 'net.hk', 'org.hk',
'com.tw', 'net.tw', 'org.tw', 'edu.tw', 'gov.tw', 'idv.tw',
'com.sa', 'net.sa', 'org.sa', 'gov.sa', 'edu.sa', 'sch.sa', 'med.sa',
'co.ae', 'net.ae', 'org.ae', 'gov.ae', 'ac.ae', 'sch.ae',
'com.tr', 'net.tr', 'org.tr', 'gov.tr', 'edu.tr', 'av.tr', 'gen.tr',
'co.ke', 'or.ke', 'go.ke', 'ac.ke', 'sc.ke', 'me.ke', 'mobi.ke', 'info.ke',
'com.ng', 'org.ng', 'gov.ng', 'edu.ng', 'net.ng', 'sch.ng', 'name.ng',
'com.pk', 'net.pk', 'org.pk', 'gov.pk', 'edu.pk', 'fam.pk',
'com.eg', 'edu.eg', 'gov.eg', 'org.eg', 'net.eg',
'com.cy', 'net.cy', 'org.cy', 'gov.cy', 'ac.cy',
'com.lk', 'org.lk', 'edu.lk', 'gov.lk', 'net.lk', 'int.lk',
'com.bd', 'net.bd', 'org.bd', 'ac.bd', 'gov.bd', 'mil.bd',
'com.ar', 'net.ar', 'org.ar', 'gov.ar', 'edu.ar', 'mil.ar',
'gob.cl', 'com.pl', 'net.pl', 'org.pl', 'gov.pl', 'edu.pl',
'co.ir', 'ac.ir', 'org.ir', 'id.ir', 'gov.ir', 'sch.ir', 'net.ir',
];
}

33
app/Config/Images.php Normal file
View File

@@ -0,0 +1,33 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Images\Handlers\GDHandler;
use CodeIgniter\Images\Handlers\ImageMagickHandler;
class Images extends BaseConfig
{
/**
* Default handler used if no other handler is specified.
*/
public string $defaultHandler = 'gd';
/**
* The path to the image library.
* Required for ImageMagick, GraphicsMagick, or NetPBM.
*
* @deprecated 4.7.0 No longer used.
*/
public string $libraryPath = '/usr/local/bin/convert';
/**
* The available handler classes.
*
* @var array<string, string>
*/
public array $handlers = [
'gd' => GDHandler::class,
'imagick' => ImageMagickHandler::class,
];
}

63
app/Config/Kint.php Normal file
View File

@@ -0,0 +1,63 @@
<?php
namespace Config;
use Kint\Parser\ConstructablePluginInterface;
use Kint\Renderer\Rich\TabPluginInterface;
use Kint\Renderer\Rich\ValuePluginInterface;
/**
* --------------------------------------------------------------------------
* Kint
* --------------------------------------------------------------------------
*
* We use Kint's `RichRenderer` and `CLIRenderer`. This area contains options
* that you can set to customize how Kint works for you.
*
* @see https://kint-php.github.io/kint/ for details on these settings.
*/
class Kint
{
/*
|--------------------------------------------------------------------------
| Global Settings
|--------------------------------------------------------------------------
*/
/**
* @var list<class-string<ConstructablePluginInterface>|ConstructablePluginInterface>|null
*/
public $plugins;
public int $maxDepth = 6;
public bool $displayCalledFrom = true;
public bool $expanded = false;
/*
|--------------------------------------------------------------------------
| RichRenderer Settings
|--------------------------------------------------------------------------
*/
public string $richTheme = 'aante-light.css';
public bool $richFolder = false;
/**
* @var array<string, class-string<ValuePluginInterface>>|null
*/
public $richObjectPlugins;
/**
* @var array<string, class-string<TabPluginInterface>>|null
*/
public $richTabPlugins;
/*
|--------------------------------------------------------------------------
| CLI Settings
|--------------------------------------------------------------------------
*/
public bool $cliColors = true;
public bool $cliForceUTF8 = false;
public bool $cliDetectWidth = true;
public int $cliMinWidth = 40;
}

151
app/Config/Logger.php Normal file
View File

@@ -0,0 +1,151 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Log\Handlers\FileHandler;
use CodeIgniter\Log\Handlers\HandlerInterface;
class Logger extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Error Logging Threshold
* --------------------------------------------------------------------------
*
* You can enable error logging by setting a threshold over zero. The
* threshold determines what gets logged. Any values below or equal to the
* threshold will be logged.
*
* Threshold options are:
*
* - 0 = Disables logging, Error logging TURNED OFF
* - 1 = Emergency Messages - System is unusable
* - 2 = Alert Messages - Action Must Be Taken Immediately
* - 3 = Critical Messages - Application component unavailable, unexpected exception.
* - 4 = Runtime Errors - Don't need immediate action, but should be monitored.
* - 5 = Warnings - Exceptional occurrences that are not errors.
* - 6 = Notices - Normal but significant events.
* - 7 = Info - Interesting events, like user logging in, etc.
* - 8 = Debug - Detailed debug information.
* - 9 = All Messages
*
* You can also pass an array with threshold levels to show individual error types
*
* array(1, 2, 3, 8) = Emergency, Alert, Critical, and Debug messages
*
* For a live site you'll usually enable Critical or higher (3) to be logged otherwise
* your log files will fill up very fast.
*
* @var int|list<int>
*/
public $threshold = (ENVIRONMENT === 'production') ? 4 : 9;
/**
* --------------------------------------------------------------------------
* Date Format for Logs
* --------------------------------------------------------------------------
*
* Each item that is logged has an associated date. You can use PHP date
* codes to set your own date formatting
*/
public string $dateFormat = 'Y-m-d H:i:s';
/**
* --------------------------------------------------------------------------
* Log Handlers
* --------------------------------------------------------------------------
*
* The logging system supports multiple actions to be taken when something
* is logged. This is done by allowing for multiple Handlers, special classes
* designed to write the log to their chosen destinations, whether that is
* a file on the getServer, a cloud-based service, or even taking actions such
* as emailing the dev team.
*
* Each handler is defined by the class name used for that handler, and it
* MUST implement the `CodeIgniter\Log\Handlers\HandlerInterface` interface.
*
* The value of each key is an array of configuration items that are sent
* to the constructor of each handler. The only required configuration item
* is the 'handles' element, which must be an array of integer log levels.
* This is most easily handled by using the constants defined in the
* `Psr\Log\LogLevel` class.
*
* Handlers are executed in the order defined in this array, starting with
* the handler on top and continuing down.
*
* @var array<class-string<HandlerInterface>, array<string, int|list<string>|string>>
*/
public array $handlers = [
/*
* --------------------------------------------------------------------
* File Handler
* --------------------------------------------------------------------
*/
FileHandler::class => [
// The log levels that this handler will handle.
'handles' => [
'critical',
'alert',
'emergency',
'debug',
'error',
'info',
'notice',
'warning',
],
/*
* The default filename extension for log files.
* An extension of 'php' allows for protecting the log files via basic
* scripting, when they are to be stored under a publicly accessible directory.
*
* NOTE: Leaving it blank will default to 'log'.
*/
'fileExtension' => '',
/*
* The file system permissions to be applied on newly created log files.
*
* IMPORTANT: This MUST be an integer (no quotes) and you MUST use octal
* integer notation (i.e. 0700, 0644, etc.)
*/
'filePermissions' => 0644,
/*
* Logging Directory Path
*
* By default, logs are written to WRITEPATH . 'logs/'
* Specify a different destination here, if desired.
*/
'path' => '',
],
/*
* The ChromeLoggerHandler requires the use of the Chrome web browser
* and the ChromeLogger extension. Uncomment this block to use it.
*/
// 'CodeIgniter\Log\Handlers\ChromeLoggerHandler' => [
// /*
// * The log levels that this handler will handle.
// */
// 'handles' => ['critical', 'alert', 'emergency', 'debug',
// 'error', 'info', 'notice', 'warning'],
// ],
/*
* The ErrorlogHandler writes the logs to PHP's native `error_log()` function.
* Uncomment this block to use it.
*/
// 'CodeIgniter\Log\Handlers\ErrorlogHandler' => [
// /* The log levels this handler can handle. */
// 'handles' => ['critical', 'alert', 'emergency', 'debug', 'error', 'info', 'notice', 'warning'],
//
// /*
// * The message type where the error should go. Can be 0 or 4, or use the
// * class constants: `ErrorlogHandler::TYPE_OS` (0) or `ErrorlogHandler::TYPE_SAPI` (4)
// */
// 'messageType' => 0,
// ],
];
}

65
app/Config/Migrations.php Normal file
View File

@@ -0,0 +1,65 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Migrations extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Enable/Disable Migrations
* --------------------------------------------------------------------------
*
* Migrations are enabled by default.
*
* You should enable migrations whenever you intend to do a schema migration
* and disable it back when you're done.
*/
public bool $enabled = true;
/**
* --------------------------------------------------------------------------
* Migrations Table
* --------------------------------------------------------------------------
*
* This is the name of the table that will store the current migrations state.
* When migrations runs it will store in a database table which migration
* files have already been run.
*/
public string $table = 'migrations';
/**
* --------------------------------------------------------------------------
* Timestamp Format
* --------------------------------------------------------------------------
*
* This is the format that will be used when creating new migrations
* using the CLI command:
* > php spark make:migration
*
* NOTE: if you set an unsupported format, migration runner will not find
* your migration files.
*
* Supported formats:
* - YmdHis_
* - Y-m-d-His_
* - Y_m_d_His_
*/
public string $timestampFormat = 'Y-m-d-His_';
/**
* --------------------------------------------------------------------------
* Enable/Disable Migration Lock
* --------------------------------------------------------------------------
*
* Locking is disabled by default.
*
* When enabled, it will prevent multiple migration processes
* from running at the same time by using a lock mechanism.
*
* This is useful in production environments to avoid conflicts
* or race conditions during concurrent deployments.
*/
public bool $lock = false;
}

534
app/Config/Mimes.php Normal file
View File

@@ -0,0 +1,534 @@
<?php
namespace Config;
/**
* This file contains an array of mime types. It is used by the
* Upload class to help identify allowed file types.
*
* When more than one variation for an extension exist (like jpg, jpeg, etc)
* the most common one should be first in the array to aid the guess*
* methods. The same applies when more than one mime-type exists for a
* single extension.
*
* When working with mime types, please make sure you have the ´fileinfo´
* extension enabled to reliably detect the media types.
*/
class Mimes
{
/**
* Map of extensions to mime types.
*
* @var array<string, list<string>|string>
*/
public static array $mimes = [
'hqx' => [
'application/mac-binhex40',
'application/mac-binhex',
'application/x-binhex40',
'application/x-mac-binhex40',
],
'cpt' => 'application/mac-compactpro',
'csv' => [
'text/csv',
'text/x-comma-separated-values',
'text/comma-separated-values',
'application/vnd.ms-excel',
'application/x-csv',
'text/x-csv',
'application/csv',
'application/excel',
'application/vnd.msexcel',
'text/plain',
],
'bin' => [
'application/macbinary',
'application/mac-binary',
'application/octet-stream',
'application/x-binary',
'application/x-macbinary',
],
'dms' => 'application/octet-stream',
'lha' => 'application/octet-stream',
'lzh' => 'application/octet-stream',
'exe' => [
'application/octet-stream',
'application/vnd.microsoft.portable-executable',
'application/x-dosexec',
'application/x-msdownload',
],
'class' => 'application/octet-stream',
'psd' => [
'application/x-photoshop',
'image/vnd.adobe.photoshop',
],
'so' => 'application/octet-stream',
'sea' => 'application/octet-stream',
'dll' => 'application/octet-stream',
'oda' => 'application/oda',
'pdf' => [
'application/pdf',
'application/force-download',
'application/x-download',
],
'ai' => [
'application/pdf',
'application/postscript',
],
'eps' => 'application/postscript',
'ps' => 'application/postscript',
'smi' => 'application/smil',
'smil' => 'application/smil',
'mif' => 'application/vnd.mif',
'xls' => [
'application/vnd.ms-excel',
'application/msexcel',
'application/x-msexcel',
'application/x-ms-excel',
'application/x-excel',
'application/x-dos_ms_excel',
'application/xls',
'application/x-xls',
'application/excel',
'application/download',
'application/vnd.ms-office',
'application/msword',
],
'ppt' => [
'application/vnd.ms-powerpoint',
'application/powerpoint',
'application/vnd.ms-office',
'application/msword',
],
'pptx' => [
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
],
'wbxml' => 'application/wbxml',
'wmlc' => 'application/wmlc',
'dcr' => 'application/x-director',
'dir' => 'application/x-director',
'dxr' => 'application/x-director',
'dvi' => 'application/x-dvi',
'gtar' => 'application/x-gtar',
'gz' => 'application/x-gzip',
'gzip' => 'application/x-gzip',
'php' => [
'application/x-php',
'application/x-httpd-php',
'application/php',
'text/php',
'text/x-php',
'application/x-httpd-php-source',
],
'php4' => 'application/x-httpd-php',
'php3' => 'application/x-httpd-php',
'phtml' => 'application/x-httpd-php',
'phps' => 'application/x-httpd-php-source',
'js' => [
'application/x-javascript',
'text/plain',
],
'swf' => 'application/x-shockwave-flash',
'sit' => 'application/x-stuffit',
'tar' => 'application/x-tar',
'tgz' => [
'application/x-tar',
'application/x-gzip-compressed',
],
'z' => 'application/x-compress',
'xhtml' => 'application/xhtml+xml',
'xht' => 'application/xhtml+xml',
'zip' => [
'application/x-zip',
'application/zip',
'application/x-zip-compressed',
'application/s-compressed',
'multipart/x-zip',
],
'rar' => [
'application/vnd.rar',
'application/x-rar',
'application/rar',
'application/x-rar-compressed',
],
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mpga' => 'audio/mpeg',
'mp2' => 'audio/mpeg',
'mp3' => [
'audio/mpeg',
'audio/mpg',
'audio/mpeg3',
'audio/mp3',
],
'aif' => [
'audio/x-aiff',
'audio/aiff',
],
'aiff' => [
'audio/x-aiff',
'audio/aiff',
],
'aifc' => 'audio/x-aiff',
'ram' => 'audio/x-pn-realaudio',
'rm' => 'audio/x-pn-realaudio',
'rpm' => 'audio/x-pn-realaudio-plugin',
'ra' => 'audio/x-realaudio',
'rv' => 'video/vnd.rn-realvideo',
'wav' => [
'audio/x-wav',
'audio/wave',
'audio/wav',
],
'bmp' => [
'image/bmp',
'image/x-bmp',
'image/x-bitmap',
'image/x-xbitmap',
'image/x-win-bitmap',
'image/x-windows-bmp',
'image/ms-bmp',
'image/x-ms-bmp',
'application/bmp',
'application/x-bmp',
'application/x-win-bitmap',
],
'gif' => 'image/gif',
'jpg' => [
'image/jpeg',
'image/pjpeg',
],
'jpeg' => [
'image/jpeg',
'image/pjpeg',
],
'jpe' => [
'image/jpeg',
'image/pjpeg',
],
'jp2' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'j2k' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'jpf' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'jpg2' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'jpx' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'jpm' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'mj2' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'mjp2' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'png' => [
'image/png',
'image/x-png',
],
'webp' => 'image/webp',
'tif' => 'image/tiff',
'tiff' => 'image/tiff',
'css' => [
'text/css',
'text/plain',
],
'html' => [
'text/html',
'text/plain',
],
'htm' => [
'text/html',
'text/plain',
],
'shtml' => [
'text/html',
'text/plain',
],
'txt' => 'text/plain',
'text' => 'text/plain',
'log' => [
'text/plain',
'text/x-log',
],
'rtx' => 'text/richtext',
'rtf' => 'text/rtf',
'xml' => [
'application/xml',
'text/xml',
'text/plain',
],
'xsl' => [
'application/xml',
'text/xsl',
'text/xml',
],
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpe' => 'video/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
'avi' => [
'video/x-msvideo',
'video/msvideo',
'video/avi',
'application/x-troff-msvideo',
],
'movie' => 'video/x-sgi-movie',
'doc' => [
'application/msword',
'application/vnd.ms-office',
],
'docx' => [
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/zip',
'application/msword',
'application/x-zip',
],
'dot' => [
'application/msword',
'application/vnd.ms-office',
],
'dotx' => [
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/zip',
'application/msword',
],
'xlsx' => [
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/zip',
'application/vnd.ms-excel',
'application/msword',
'application/x-zip',
],
'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12',
'word' => [
'application/msword',
'application/octet-stream',
],
'xl' => 'application/excel',
'eml' => 'message/rfc822',
'json' => [
'application/json',
'text/json',
],
'pem' => [
'application/x-x509-user-cert',
'application/x-pem-file',
'application/octet-stream',
],
'p10' => [
'application/x-pkcs10',
'application/pkcs10',
],
'p12' => 'application/x-pkcs12',
'p7a' => 'application/x-pkcs7-signature',
'p7c' => [
'application/pkcs7-mime',
'application/x-pkcs7-mime',
],
'p7m' => [
'application/pkcs7-mime',
'application/x-pkcs7-mime',
],
'p7r' => 'application/x-pkcs7-certreqresp',
'p7s' => 'application/pkcs7-signature',
'crt' => [
'application/x-x509-ca-cert',
'application/x-x509-user-cert',
'application/pkix-cert',
],
'crl' => [
'application/pkix-crl',
'application/pkcs-crl',
],
'der' => 'application/x-x509-ca-cert',
'kdb' => 'application/octet-stream',
'pgp' => 'application/pgp',
'gpg' => 'application/gpg-keys',
'sst' => 'application/octet-stream',
'csr' => 'application/octet-stream',
'rsa' => 'application/x-pkcs7',
'cer' => [
'application/pkix-cert',
'application/x-x509-ca-cert',
],
'3g2' => 'video/3gpp2',
'3gp' => [
'video/3gp',
'video/3gpp',
],
'mp4' => 'video/mp4',
'm4a' => 'audio/x-m4a',
'f4v' => [
'video/mp4',
'video/x-f4v',
],
'flv' => 'video/x-flv',
'webm' => 'video/webm',
'aac' => 'audio/x-acc',
'm4u' => 'application/vnd.mpegurl',
'm3u' => 'text/plain',
'xspf' => 'application/xspf+xml',
'vlc' => 'application/videolan',
'wmv' => [
'video/x-ms-wmv',
'video/x-ms-asf',
],
'au' => 'audio/x-au',
'ac3' => 'audio/ac3',
'flac' => 'audio/x-flac',
'ogg' => [
'audio/ogg',
'video/ogg',
'application/ogg',
],
'kmz' => [
'application/vnd.google-earth.kmz',
'application/zip',
'application/x-zip',
],
'kml' => [
'application/vnd.google-earth.kml+xml',
'application/xml',
'text/xml',
],
'ics' => 'text/calendar',
'ical' => 'text/calendar',
'zsh' => 'text/x-scriptzsh',
'7zip' => [
'application/x-compressed',
'application/x-zip-compressed',
'application/zip',
'multipart/x-zip',
],
'cdr' => [
'application/cdr',
'application/coreldraw',
'application/x-cdr',
'application/x-coreldraw',
'image/cdr',
'image/x-cdr',
'zz-application/zz-winassoc-cdr',
],
'wma' => [
'audio/x-ms-wma',
'video/x-ms-asf',
],
'jar' => [
'application/java-archive',
'application/x-java-application',
'application/x-jar',
'application/x-compressed',
],
'svg' => [
'image/svg+xml',
'image/svg',
'application/xml',
'text/xml',
],
'vcf' => 'text/x-vcard',
'srt' => [
'text/srt',
'text/plain',
],
'vtt' => [
'text/vtt',
'text/plain',
],
'ico' => [
'image/x-icon',
'image/x-ico',
'image/vnd.microsoft.icon',
],
'stl' => [
'application/sla',
'application/vnd.ms-pki.stl',
'application/x-navistyle',
'model/stl',
'application/octet-stream',
],
];
/**
* Attempts to determine the best mime type for the given file extension.
*
* @return string|null The mime type found, or none if unable to determine.
*/
public static function guessTypeFromExtension(string $extension)
{
$extension = trim(strtolower($extension), '. ');
if (! array_key_exists($extension, static::$mimes)) {
return null;
}
return is_array(static::$mimes[$extension]) ? static::$mimes[$extension][0] : static::$mimes[$extension];
}
/**
* Attempts to determine the best file extension for a given mime type.
*
* @param string|null $proposedExtension - default extension (in case there is more than one with the same mime type)
*
* @return string|null The extension determined, or null if unable to match.
*/
public static function guessExtensionFromType(string $type, ?string $proposedExtension = null)
{
$type = trim(strtolower($type), '. ');
$proposedExtension = trim(strtolower($proposedExtension ?? ''));
if (
$proposedExtension !== ''
&& array_key_exists($proposedExtension, static::$mimes)
&& in_array($type, (array) static::$mimes[$proposedExtension], true)
) {
// The detected mime type matches with the proposed extension.
return $proposedExtension;
}
// Reverse check the mime type list if no extension was proposed.
// This search is order sensitive!
foreach (static::$mimes as $ext => $types) {
if (in_array($type, (array) $types, true)) {
return $ext;
}
}
return null;
}
}

View File

@@ -0,0 +1,84 @@
# Module Loader Documentation
## Overview
ModuleLoader adalah sistem yang secara otomatis memuat route dari setiap modul di `app/Modules/*`. Setiap modul dapat memiliki file `Routes.php` yang akan otomatis dimuat saat aplikasi di-boot.
## Cara Kerja
1. **Automatic Discovery**: ModuleLoader secara otomatis memindai semua direktori di `app/Modules/*`
2. **Route Loading**: Jika sebuah modul memiliki file `Routes.php`, file tersebut akan otomatis dimuat
3. **Route Registration**: Route yang didefinisikan di file `Routes.php` modul akan terdaftar ke sistem routing CodeIgniter
## Struktur Modul
Setiap modul harus mengikuti struktur berikut:
```
app/Modules/
└── {ModuleName}/
├── Routes.php # File route untuk modul ini (opsional)
├── Controllers/
├── Models/
├── Services/
└── Entities/
```
## Cara Membuat Routes di Modul
Buat file `Routes.php` di root direktori modul Anda:
```php
<?php
/**
* {ModuleName} Module Routes
*
* @var RouteCollection $routes
*/
// Contoh route dengan group
$routes->group('api/module-name', ['namespace' => 'App\Modules\{ModuleName}\Controllers'], function($routes) {
$routes->get('/', 'ControllerName::index');
$routes->post('/', 'ControllerName::create');
$routes->get('(:num)', 'ControllerName::show/$1');
$routes->put('(:num)', 'ControllerName::update/$1');
$routes->delete('(:num)', 'ControllerName::delete/$1');
});
// Atau route langsung
$routes->get('api/module-name/endpoint', 'App\Modules\{ModuleName}\Controllers\ControllerName::method');
```
## Integrasi
ModuleLoader sudah terintegrasi di `app/Config/Routes.php`:
```php
use Config\ModuleLoader;
$moduleLoader = new ModuleLoader();
$moduleLoader->loadModuleRoutes($routes);
```
Route dari modul akan dimuat sebelum route utama aplikasi, sehingga route utama dapat override route modul jika diperlukan.
## API Methods
### `loadModuleRoutes(RouteCollection $routes): void`
Memuat semua route dari modul yang memiliki file `Routes.php`.
### `getAvailableModules(): array`
Mengembalikan array nama modul yang tersedia.
### `moduleExists(string $moduleName): bool`
Memeriksa apakah modul dengan nama tertentu ada.
### `getModulePath(string $moduleName): ?string`
Mengembalikan path lengkap ke modul, atau `null` jika tidak ditemukan.
## Catatan
- File `Routes.php` di modul harus menggunakan variabel `$routes` yang sudah tersedia
- Route dari modul dimuat dalam urutan alfabetis berdasarkan nama modul
- Jika ada konflik route, route yang dimuat terakhir akan mengambil prioritas

138
app/Config/ModuleLoader.php Normal file
View File

@@ -0,0 +1,138 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Router\RouteCollection;
/**
* Module Loader Configuration
*
* Handles automatic discovery and loading of module routes.
* Each module can contain a Routes.php file that will be automatically loaded.
*/
class ModuleLoader extends BaseConfig
{
/**
* Base path for modules directory
*
* @var string
*/
protected string $modulesPath = APPPATH . 'Modules' . DIRECTORY_SEPARATOR;
/**
* Route file name to look for in each module
*
* @var string
*/
protected string $routeFileName = 'Routes.php';
/**
* Load all module routes automatically
*
* Scans app/Modules/* directories and loads Routes.php from each module
* if it exists.
*
* @param RouteCollection $routes The route collection instance
* @return void
*/
public function loadModuleRoutes(RouteCollection $routes): void
{
if (!is_dir($this->modulesPath)) {
return;
}
// Get all module directories
$modules = $this->getModuleDirectories();
foreach ($modules as $moduleName => $modulePath) {
$routeFile = $modulePath . DIRECTORY_SEPARATOR . $this->routeFileName;
if (file_exists($routeFile)) {
$this->loadModuleRouteFile($routeFile, $routes, $moduleName);
}
}
}
/**
* Get all module directories
*
* @return array<string, string> Array of module name => module path
*/
protected function getModuleDirectories(): array
{
$modules = [];
$dirs = scandir($this->modulesPath);
foreach ($dirs as $dir) {
if ($dir === '.' || $dir === '..') {
continue;
}
$modulePath = $this->modulesPath . $dir;
if (is_dir($modulePath)) {
$modules[$dir] = $modulePath;
}
}
return $modules;
}
/**
* Load a module route file
*
* @param string $routeFile Full path to Routes.php file
* @param RouteCollection $routes The route collection instance
* @param string $moduleName Name of the module
* @return void
*/
protected function loadModuleRouteFile(string $routeFile, RouteCollection $routes, string $moduleName): void
{
// Include the route file
// The route file should use the $routes variable passed to it
if (file_exists($routeFile)) {
// Make $routes available in the included file's scope
// Extract to current scope so Routes.php can access $routes variable
extract(['routes' => $routes], EXTR_SKIP);
require $routeFile;
}
}
/**
* Get list of available modules
*
* @return array<string> List of module names
*/
public function getAvailableModules(): array
{
return array_keys($this->getModuleDirectories());
}
/**
* Check if a module exists
*
* @param string $moduleName Name of the module
* @return bool
*/
public function moduleExists(string $moduleName): bool
{
$modulePath = $this->modulesPath . $moduleName;
return is_dir($modulePath);
}
/**
* Get module path
*
* @param string $moduleName Name of the module
* @return string|null Module path or null if not found
*/
public function getModulePath(string $moduleName): ?string
{
if (!$this->moduleExists($moduleName)) {
return null;
}
return $this->modulesPath . $moduleName;
}
}

82
app/Config/Modules.php Normal file
View File

@@ -0,0 +1,82 @@
<?php
namespace Config;
use CodeIgniter\Modules\Modules as BaseModules;
/**
* Modules Configuration.
*
* NOTE: This class is required prior to Autoloader instantiation,
* and does not extend BaseConfig.
*/
class Modules extends BaseModules
{
/**
* --------------------------------------------------------------------------
* Enable Auto-Discovery?
* --------------------------------------------------------------------------
*
* If true, then auto-discovery will happen across all elements listed in
* $aliases below. If false, no auto-discovery will happen at all,
* giving a slight performance boost.
*
* @var bool
*/
public $enabled = true;
/**
* --------------------------------------------------------------------------
* Enable Auto-Discovery Within Composer Packages?
* --------------------------------------------------------------------------
*
* If true, then auto-discovery will happen across all namespaces loaded
* by Composer, as well as the namespaces configured locally.
*
* @var bool
*/
public $discoverInComposer = true;
/**
* The Composer package list for Auto-Discovery
* This setting is optional.
*
* E.g.:
* [
* 'only' => [
* // List up all packages to auto-discover
* 'codeigniter4/shield',
* ],
* ]
* or
* [
* 'exclude' => [
* // List up packages to exclude.
* 'pestphp/pest',
* ],
* ]
*
* @var array{only?: list<string>, exclude?: list<string>}
*/
public $composerPackages = [];
/**
* --------------------------------------------------------------------------
* Auto-Discovery Rules
* --------------------------------------------------------------------------
*
* Aliases list of all discovery classes that will be active and used during
* the current application request.
*
* If it is not listed, only the base application elements will be used.
*
* @var list<string>
*/
public $aliases = [
'events',
'filters',
'registrars',
'routes',
'services',
];
}

32
app/Config/Optimize.php Normal file
View File

@@ -0,0 +1,32 @@
<?php
namespace Config;
/**
* Optimization Configuration.
*
* NOTE: This class does not extend BaseConfig for performance reasons.
* So you cannot replace the property values with Environment Variables.
*
* WARNING: Do not use these options when running the app in the Worker Mode.
*/
class Optimize
{
/**
* --------------------------------------------------------------------------
* Config Caching
* --------------------------------------------------------------------------
*
* @see https://codeigniter.com/user_guide/concepts/factories.html#config-caching
*/
public bool $configCacheEnabled = false;
/**
* --------------------------------------------------------------------------
* Config Caching
* --------------------------------------------------------------------------
*
* @see https://codeigniter.com/user_guide/concepts/autoloader.html#file-locator-caching
*/
public bool $locatorCacheEnabled = false;
}

37
app/Config/Pager.php Normal file
View File

@@ -0,0 +1,37 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Pager extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Templates
* --------------------------------------------------------------------------
*
* Pagination links are rendered out using views to configure their
* appearance. This array contains aliases and the view names to
* use when rendering the links.
*
* Within each view, the Pager object will be available as $pager,
* and the desired group as $pagerGroup;
*
* @var array<string, string>
*/
public array $templates = [
'default_full' => 'CodeIgniter\Pager\Views\default_full',
'default_simple' => 'CodeIgniter\Pager\Views\default_simple',
'default_head' => 'CodeIgniter\Pager\Views\default_head',
];
/**
* --------------------------------------------------------------------------
* Items Per Page
* --------------------------------------------------------------------------
*
* The default number of results shown in a single page.
*/
public int $perPage = 20;
}

78
app/Config/Paths.php Normal file
View File

@@ -0,0 +1,78 @@
<?php
namespace Config;
/**
* Paths
*
* Holds the paths that are used by the system to
* locate the main directories, app, system, etc.
*
* Modifying these allows you to restructure your application,
* share a system folder between multiple applications, and more.
*
* All paths are relative to the project's root folder.
*
* NOTE: This class is required prior to Autoloader instantiation,
* and does not extend BaseConfig.
*/
class Paths
{
/**
* ---------------------------------------------------------------
* SYSTEM FOLDER NAME
* ---------------------------------------------------------------
*
* This must contain the name of your "system" folder. Include
* the path if the folder is not in the same directory as this file.
*/
public string $systemDirectory = __DIR__ . '/../../vendor/codeigniter4/framework/system';
/**
* ---------------------------------------------------------------
* APPLICATION FOLDER NAME
* ---------------------------------------------------------------
*
* If you want this front controller to use a different "app"
* folder than the default one you can set its name here. The folder
* can also be renamed or relocated anywhere on your server. If
* you do, use a full server path.
*
* @see http://codeigniter.com/user_guide/general/managing_apps.html
*/
public string $appDirectory = __DIR__ . '/..';
/**
* ---------------------------------------------------------------
* WRITABLE DIRECTORY NAME
* ---------------------------------------------------------------
*
* This variable must contain the name of your "writable" directory.
* The writable directory allows you to group all directories that
* need write permission to a single place that can be tucked away
* for maximum security, keeping it out of the app and/or
* system directories.
*/
public string $writableDirectory = __DIR__ . '/../../writable';
/**
* ---------------------------------------------------------------
* TESTS DIRECTORY NAME
* ---------------------------------------------------------------
*
* This variable must contain the name of your "tests" directory.
*/
public string $testsDirectory = __DIR__ . '/../../tests';
/**
* ---------------------------------------------------------------
* VIEW DIRECTORY NAME
* ---------------------------------------------------------------
*
* This variable must contain the name of the directory that
* contains the view files used by your application. By
* default this is in `app/Views`. This value
* is used when no value is provided to `Services::renderer()`.
*/
public string $viewDirectory = __DIR__ . '/../Views';
}

28
app/Config/Publisher.php Normal file
View File

@@ -0,0 +1,28 @@
<?php
namespace Config;
use CodeIgniter\Config\Publisher as BasePublisher;
/**
* Publisher Configuration
*
* Defines basic security restrictions for the Publisher class
* to prevent abuse by injecting malicious files into a project.
*/
class Publisher extends BasePublisher
{
/**
* A list of allowed destinations with a (pseudo-)regex
* of allowed files for each destination.
* Attempts to publish to directories not in this list will
* result in a PublisherException. Files that do no fit the
* pattern will cause copy/merge to fail.
*
* @var array<string, string>
*/
public $restrictions = [
ROOTPATH => '*',
FCPATH => '#\.(s?css|js|map|html?|xml|json|webmanifest|ttf|eot|woff2?|gif|jpe?g|tiff?|png|webp|bmp|ico|svg)$#i',
];
}

48
app/Config/Routes.php Normal file
View File

@@ -0,0 +1,48 @@
<?php
use CodeIgniter\Router\RouteCollection;
use Config\ModuleLoader;
/**
* @var RouteCollection $routes
*/
// Root: redirect ke halaman login dashboard
$routes->get('/', static function () {
return redirect()->to('/login');
});
// Load module routes automatically
$moduleLoader = new ModuleLoader();
$moduleLoader->loadModuleRoutes($routes);
// API: users (admin only) — list by role, create/update/delete for teachers
$routes->get('api/users', '\App\Modules\Auth\Controllers\UserController::index', ['filter' => 'admin_only']);
$routes->post('api/users', '\App\Modules\Auth\Controllers\UserController::store', ['filter' => 'admin_only']);
$routes->put('api/users/(:num)', '\App\Modules\Auth\Controllers\UserController::update/$1', ['filter' => 'admin_only']);
$routes->delete('api/users/(:num)', '\App\Modules\Auth\Controllers\UserController::delete/$1', ['filter' => 'admin_only']);
// Web dashboard (requires authenticated session)
$routes->get('login', 'LoginController::index');
$routes->post('logout', 'LogoutController::index');
$routes->get('dashboard', 'DashboardPageController::index', ['filter' => 'dashboard_page_auth']);
$routes->get('dashboard/attendance/reports', 'DashboardPageController::attendanceReports', ['filter' => 'dashboard_page_auth']);
$routes->get('dashboard/attendance/report/(:num)', 'DashboardPageController::attendanceReport/$1', ['filter' => 'dashboard_page_auth']);
$routes->get('dashboard/schedule/today', 'DashboardPageController::scheduleToday', ['filter' => 'dashboard_page_auth']);
$routes->get('dashboard/discipline', 'DashboardPageController::discipline', ['filter' => 'dashboard_page_auth']);
$routes->get('dashboard/parent', 'DashboardPageController::parent', ['filter' => 'dashboard_page_auth']);
$routes->get('dashboard/academic/settings', 'DashboardAcademicController::academicSettings', ['filter' => 'dashboard_admin_page']);
$routes->get('dashboard/academic/classes', 'DashboardAcademicController::classes', ['filter' => 'dashboard_admin_page']);
$routes->get('dashboard/academic/subjects', 'DashboardAcademicController::subjects', ['filter' => 'dashboard_admin_page']);
$routes->get('dashboard/academic/teachers', 'DashboardAcademicController::teachers', ['filter' => 'dashboard_admin_page']);
$routes->get('dashboard/academic/lesson-slots', 'DashboardAcademicController::lessonSlots', ['filter' => 'dashboard_admin_page']);
$routes->get('dashboard/academic/students', 'DashboardAcademicController::students', ['filter' => 'dashboard_admin_page']);
$routes->get('dashboard/academic/dapodik', 'DashboardAcademicController::dapodik', ['filter' => 'dashboard_admin_page']);
$routes->get('dashboard/academic/schedule-builder', 'DashboardAcademicController::scheduleBuilderIndex', ['filter' => 'dashboard_admin_page']);
$routes->get('dashboard/academic/schedule-builder/(:num)', 'DashboardAcademicController::scheduleBuilder/$1', ['filter' => 'dashboard_admin_page']);
$routes->get('dashboard/academic/discipline-settings', 'DashboardAcademicController::disciplineSettings', ['filter' => 'dashboard_admin_page']);
$routes->get('dashboard/presence-settings', 'DashboardPageController::presenceSettings', ['filter' => 'dashboard_admin_page']);
$routes->get('dashboard/devices', 'DashboardPageController::devices', ['filter' => 'dashboard_admin_page']);
// Main application routes can be defined here
// Module routes are automatically loaded from app/Modules/*/Routes.php

149
app/Config/Routing.php Normal file
View File

@@ -0,0 +1,149 @@
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Config;
use CodeIgniter\Config\Routing as BaseRouting;
/**
* Routing configuration
*/
class Routing extends BaseRouting
{
/**
* For Defined Routes.
* An array of files that contain route definitions.
* Route files are read in order, with the first match
* found taking precedence.
*
* Default: APPPATH . 'Config/Routes.php'
*
* @var list<string>
*/
public array $routeFiles = [
APPPATH . 'Config/Routes.php',
];
/**
* For Defined Routes and Auto Routing.
* The default namespace to use for Controllers when no other
* namespace has been specified.
*
* Default: 'App\Controllers'
*/
public string $defaultNamespace = 'App\Controllers';
/**
* For Auto Routing.
* The default controller to use when no other controller has been
* specified.
*
* Default: 'Home'
*/
public string $defaultController = 'Home';
/**
* For Defined Routes and Auto Routing.
* The default method to call on the controller when no other
* method has been set in the route.
*
* Default: 'index'
*/
public string $defaultMethod = 'index';
/**
* For Auto Routing.
* Whether to translate dashes in URIs for controller/method to underscores.
* Primarily useful when using the auto-routing.
*
* Default: false
*/
public bool $translateURIDashes = false;
/**
* Sets the class/method that should be called if routing doesn't
* find a match. It can be the controller/method name like: Users::index
*
* This setting is passed to the Router class and handled there.
*
* If you want to use a closure, you will have to set it in the
* routes file by calling:
*
* $routes->set404Override(function() {
* // Do something here
* });
*
* Example:
* public $override404 = 'App\Errors::show404';
*/
public ?string $override404 = null;
/**
* If TRUE, the system will attempt to match the URI against
* Controllers by matching each segment against folders/files
* in APPPATH/Controllers, when a match wasn't found against
* defined routes.
*
* If FALSE, will stop searching and do NO automatic routing.
*/
public bool $autoRoute = false;
/**
* If TRUE, the system will look for attributes on controller
* class and methods that can run before and after the
* controller/method.
*
* If FALSE, will ignore any attributes.
*/
public bool $useControllerAttributes = true;
/**
* For Defined Routes.
* If TRUE, will enable the use of the 'prioritize' option
* when defining routes.
*
* Default: false
*/
public bool $prioritize = false;
/**
* For Defined Routes.
* If TRUE, matched multiple URI segments will be passed as one parameter.
*
* Default: false
*/
public bool $multipleSegmentsOneParam = false;
/**
* For Auto Routing (Improved).
* Map of URI segments and namespaces.
*
* The key is the first URI segment. The value is the controller namespace.
* E.g.,
* [
* 'blog' => 'Acme\Blog\Controllers',
* ]
*
* @var array<string, string>
*/
public array $moduleRoutes = [];
/**
* For Auto Routing (Improved).
* Whether to translate dashes in URIs for controller/method to CamelCase.
* E.g., blog-controller -> BlogController
*
* If you enable this, $translateURIDashes is ignored.
*
* Default: false
*/
public bool $translateUriToCamelCase = true;
}

86
app/Config/Security.php Normal file
View File

@@ -0,0 +1,86 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Security extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* CSRF Protection Method
* --------------------------------------------------------------------------
*
* Protection Method for Cross Site Request Forgery protection.
*
* @var string 'cookie' or 'session'
*/
public string $csrfProtection = 'cookie';
/**
* --------------------------------------------------------------------------
* CSRF Token Randomization
* --------------------------------------------------------------------------
*
* Randomize the CSRF Token for added security.
*/
public bool $tokenRandomize = false;
/**
* --------------------------------------------------------------------------
* CSRF Token Name
* --------------------------------------------------------------------------
*
* Token name for Cross Site Request Forgery protection.
*/
public string $tokenName = 'csrf_test_name';
/**
* --------------------------------------------------------------------------
* CSRF Header Name
* --------------------------------------------------------------------------
*
* Header name for Cross Site Request Forgery protection.
*/
public string $headerName = 'X-CSRF-TOKEN';
/**
* --------------------------------------------------------------------------
* CSRF Cookie Name
* --------------------------------------------------------------------------
*
* Cookie name for Cross Site Request Forgery protection.
*/
public string $cookieName = 'csrf_cookie_name';
/**
* --------------------------------------------------------------------------
* CSRF Expires
* --------------------------------------------------------------------------
*
* Expiration time for Cross Site Request Forgery protection cookie.
*
* Defaults to two hours (in seconds).
*/
public int $expires = 7200;
/**
* --------------------------------------------------------------------------
* CSRF Regenerate
* --------------------------------------------------------------------------
*
* Regenerate CSRF Token on every submission.
*/
public bool $regenerate = true;
/**
* --------------------------------------------------------------------------
* CSRF Redirect
* --------------------------------------------------------------------------
*
* Redirect to previous page with error on failure.
*
* @see https://codeigniter4.github.io/userguide/libraries/security.html#redirection-on-failure
*/
public bool $redirect = (ENVIRONMENT === 'production');
}

32
app/Config/Services.php Normal file
View File

@@ -0,0 +1,32 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseService;
/**
* Services Configuration file.
*
* Services are simply other classes/libraries that the system uses
* to do its job. This is used by CodeIgniter to allow the core of the
* framework to be swapped out easily without affecting the usage within
* the rest of your application.
*
* This file holds any application-specific services, or service overrides
* that you might need. An example has been included with the general
* method format you should use for your service methods. For more examples,
* see the core Services file at system/Config/Services.php.
*/
class Services extends BaseService
{
/*
* public static function example($getShared = true)
* {
* if ($getShared) {
* return static::getSharedInstance('example');
* }
*
* return new \CodeIgniter\Example();
* }
*/
}

128
app/Config/Session.php Normal file
View File

@@ -0,0 +1,128 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Session\Handlers\BaseHandler;
use CodeIgniter\Session\Handlers\FileHandler;
class Session extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Session Driver
* --------------------------------------------------------------------------
*
* The session storage driver to use:
* - `CodeIgniter\Session\Handlers\ArrayHandler` (for testing)
* - `CodeIgniter\Session\Handlers\FileHandler`
* - `CodeIgniter\Session\Handlers\DatabaseHandler`
* - `CodeIgniter\Session\Handlers\MemcachedHandler`
* - `CodeIgniter\Session\Handlers\RedisHandler`
*
* @var class-string<BaseHandler>
*/
public string $driver = FileHandler::class;
/**
* --------------------------------------------------------------------------
* Session Cookie Name
* --------------------------------------------------------------------------
*
* The session cookie name, must contain only [0-9a-z_-] characters
*/
public string $cookieName = 'ci_session';
/**
* --------------------------------------------------------------------------
* Session Expiration
* --------------------------------------------------------------------------
*
* The number of SECONDS you want the session to last.
* Setting to 0 (zero) means expire when the browser is closed.
*/
public int $expiration = 7200;
/**
* --------------------------------------------------------------------------
* Session Save Path
* --------------------------------------------------------------------------
*
* The location to save sessions to and is driver dependent.
*
* For the 'files' driver, it's a path to a writable directory.
* WARNING: Only absolute paths are supported!
*
* For the 'database' driver, it's a table name.
* Please read up the manual for the format with other session drivers.
*
* IMPORTANT: You are REQUIRED to set a valid save path!
*/
public string $savePath = WRITEPATH . 'session';
/**
* --------------------------------------------------------------------------
* Session Match IP
* --------------------------------------------------------------------------
*
* Whether to match the user's IP address when reading the session data.
*
* WARNING: If you're using the database driver, don't forget to update
* your session table's PRIMARY KEY when changing this setting.
*/
public bool $matchIP = false;
/**
* --------------------------------------------------------------------------
* Session Time to Update
* --------------------------------------------------------------------------
*
* How many seconds between CI regenerating the session ID.
*/
public int $timeToUpdate = 300;
/**
* --------------------------------------------------------------------------
* Session Regenerate Destroy
* --------------------------------------------------------------------------
*
* Whether to destroy session data associated with the old session ID
* when auto-regenerating the session ID. When set to FALSE, the data
* will be later deleted by the garbage collector.
*/
public bool $regenerateDestroy = false;
/**
* --------------------------------------------------------------------------
* Session Database Group
* --------------------------------------------------------------------------
*
* DB Group for the database session.
*/
public ?string $DBGroup = null;
/**
* --------------------------------------------------------------------------
* Lock Retry Interval (microseconds)
* --------------------------------------------------------------------------
*
* This is used for RedisHandler.
*
* Time (microseconds) to wait if lock cannot be acquired.
* The default is 100,000 microseconds (= 0.1 seconds).
*/
public int $lockRetryInterval = 100_000;
/**
* --------------------------------------------------------------------------
* Lock Max Retries
* --------------------------------------------------------------------------
*
* This is used for RedisHandler.
*
* Maximum number of lock acquisition attempts.
* The default is 300 times. That is lock timeout is about 30 (0.1 * 300)
* seconds.
*/
public int $lockMaxRetries = 300;
}

147
app/Config/Toolbar.php Normal file
View File

@@ -0,0 +1,147 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Debug\Toolbar\Collectors\Database;
use CodeIgniter\Debug\Toolbar\Collectors\Events;
use CodeIgniter\Debug\Toolbar\Collectors\Files;
use CodeIgniter\Debug\Toolbar\Collectors\Logs;
use CodeIgniter\Debug\Toolbar\Collectors\Routes;
use CodeIgniter\Debug\Toolbar\Collectors\Timers;
use CodeIgniter\Debug\Toolbar\Collectors\Views;
/**
* --------------------------------------------------------------------------
* Debug Toolbar
* --------------------------------------------------------------------------
*
* The Debug Toolbar provides a way to see information about the performance
* and state of your application during that page display. By default it will
* NOT be displayed under production environments, and will only display if
* `CI_DEBUG` is true, since if it's not, there's not much to display anyway.
*/
class Toolbar extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Toolbar Collectors
* --------------------------------------------------------------------------
*
* List of toolbar collectors that will be called when Debug Toolbar
* fires up and collects data from.
*
* @var list<class-string>
*/
public array $collectors = [
Timers::class,
Database::class,
Logs::class,
Views::class,
// \CodeIgniter\Debug\Toolbar\Collectors\Cache::class,
Files::class,
Routes::class,
Events::class,
];
/**
* --------------------------------------------------------------------------
* Collect Var Data
* --------------------------------------------------------------------------
*
* If set to false var data from the views will not be collected. Useful to
* avoid high memory usage when there are lots of data passed to the view.
*/
public bool $collectVarData = true;
/**
* --------------------------------------------------------------------------
* Max History
* --------------------------------------------------------------------------
*
* `$maxHistory` sets a limit on the number of past requests that are stored,
* helping to conserve file space used to store them. You can set it to
* 0 (zero) to not have any history stored, or -1 for unlimited history.
*/
public int $maxHistory = 20;
/**
* --------------------------------------------------------------------------
* Toolbar Views Path
* --------------------------------------------------------------------------
*
* The full path to the the views that are used by the toolbar.
* This MUST have a trailing slash.
*/
public string $viewsPath = SYSTEMPATH . 'Debug/Toolbar/Views/';
/**
* --------------------------------------------------------------------------
* Max Queries
* --------------------------------------------------------------------------
*
* If the Database Collector is enabled, it will log every query that the
* the system generates so they can be displayed on the toolbar's timeline
* and in the query log. This can lead to memory issues in some instances
* with hundreds of queries.
*
* `$maxQueries` defines the maximum amount of queries that will be stored.
*/
public int $maxQueries = 100;
/**
* --------------------------------------------------------------------------
* Watched Directories
* --------------------------------------------------------------------------
*
* Contains an array of directories that will be watched for changes and
* used to determine if the hot-reload feature should reload the page or not.
* We restrict the values to keep performance as high as possible.
*
* NOTE: The ROOTPATH will be prepended to all values.
*
* @var list<string>
*/
public array $watchedDirectories = [
'app',
];
/**
* --------------------------------------------------------------------------
* Watched File Extensions
* --------------------------------------------------------------------------
*
* Contains an array of file extensions that will be watched for changes and
* used to determine if the hot-reload feature should reload the page or not.
*
* @var list<string>
*/
public array $watchedExtensions = [
'php', 'css', 'js', 'html', 'svg', 'json', 'env',
];
/**
* --------------------------------------------------------------------------
* Ignored HTTP Headers
* --------------------------------------------------------------------------
*
* CodeIgniter Debug Toolbar normally injects HTML and JavaScript into every
* HTML response. This is correct for full page loads, but it breaks requests
* that expect only a clean HTML fragment.
*
* Libraries like HTMX, Unpoly, and Hotwire (Turbo) update parts of the page or
* manage navigation on the client side. Injecting the Debug Toolbar into their
* responses can cause invalid HTML, duplicated scripts, or JavaScript errors
* (such as infinite loops or "Maximum call stack size exceeded").
*
* Any request containing one of the following headers is treated as a
* client-managed or partial request, and the Debug Toolbar injection is skipped.
*
* @var array<string, string|null>
*/
public array $disableOnHeaders = [
'X-Requested-With' => 'xmlhttprequest', // AJAX requests
'HX-Request' => 'true', // HTMX requests
'X-Up-Version' => null, // Unpoly partial requests
];
}

262
app/Config/UserAgents.php Normal file
View File

@@ -0,0 +1,262 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* -------------------------------------------------------------------
* User Agents
* -------------------------------------------------------------------
*
* This file contains four arrays of user agent data. It is used by the
* User Agent Class to help identify browser, platform, robot, and
* mobile device data. The array keys are used to identify the device
* and the array values are used to set the actual name of the item.
*/
class UserAgents extends BaseConfig
{
/**
* -------------------------------------------------------------------
* OS Platforms
* -------------------------------------------------------------------
*
* @var array<string, string>
*/
public array $platforms = [
'windows nt 10.0' => 'Windows 10',
'windows nt 6.3' => 'Windows 8.1',
'windows nt 6.2' => 'Windows 8',
'windows nt 6.1' => 'Windows 7',
'windows nt 6.0' => 'Windows Vista',
'windows nt 5.2' => 'Windows 2003',
'windows nt 5.1' => 'Windows XP',
'windows nt 5.0' => 'Windows 2000',
'windows nt 4.0' => 'Windows NT 4.0',
'winnt4.0' => 'Windows NT 4.0',
'winnt 4.0' => 'Windows NT',
'winnt' => 'Windows NT',
'windows 98' => 'Windows 98',
'win98' => 'Windows 98',
'windows 95' => 'Windows 95',
'win95' => 'Windows 95',
'windows phone' => 'Windows Phone',
'windows' => 'Unknown Windows OS',
'android' => 'Android',
'blackberry' => 'BlackBerry',
'iphone' => 'iOS',
'ipad' => 'iOS',
'ipod' => 'iOS',
'os x' => 'Mac OS X',
'ppc mac' => 'Power PC Mac',
'freebsd' => 'FreeBSD',
'ppc' => 'Macintosh',
'linux' => 'Linux',
'debian' => 'Debian',
'sunos' => 'Sun Solaris',
'beos' => 'BeOS',
'apachebench' => 'ApacheBench',
'aix' => 'AIX',
'irix' => 'Irix',
'osf' => 'DEC OSF',
'hp-ux' => 'HP-UX',
'netbsd' => 'NetBSD',
'bsdi' => 'BSDi',
'openbsd' => 'OpenBSD',
'gnu' => 'GNU/Linux',
'unix' => 'Unknown Unix OS',
'symbian' => 'Symbian OS',
];
/**
* -------------------------------------------------------------------
* Browsers
* -------------------------------------------------------------------
*
* The order of this array should NOT be changed. Many browsers return
* multiple browser types so we want to identify the subtype first.
*
* @var array<string, string>
*/
public array $browsers = [
'OPR' => 'Opera',
'Flock' => 'Flock',
'Edge' => 'Spartan',
'Edg' => 'Edge',
'Chrome' => 'Chrome',
// Opera 10+ always reports Opera/9.80 and appends Version/<real version> to the user agent string
'Opera.*?Version' => 'Opera',
'Opera' => 'Opera',
'MSIE' => 'Internet Explorer',
'Internet Explorer' => 'Internet Explorer',
'Trident.* rv' => 'Internet Explorer',
'Shiira' => 'Shiira',
'Firefox' => 'Firefox',
'Chimera' => 'Chimera',
'Phoenix' => 'Phoenix',
'Firebird' => 'Firebird',
'Camino' => 'Camino',
'Netscape' => 'Netscape',
'OmniWeb' => 'OmniWeb',
'Safari' => 'Safari',
'Mozilla' => 'Mozilla',
'Konqueror' => 'Konqueror',
'icab' => 'iCab',
'Lynx' => 'Lynx',
'Links' => 'Links',
'hotjava' => 'HotJava',
'amaya' => 'Amaya',
'IBrowse' => 'IBrowse',
'Maxthon' => 'Maxthon',
'Ubuntu' => 'Ubuntu Web Browser',
'Vivaldi' => 'Vivaldi',
];
/**
* -------------------------------------------------------------------
* Mobiles
* -------------------------------------------------------------------
*
* @var array<string, string>
*/
public array $mobiles = [
// legacy array, old values commented out
'mobileexplorer' => 'Mobile Explorer',
// 'openwave' => 'Open Wave',
// 'opera mini' => 'Opera Mini',
// 'operamini' => 'Opera Mini',
// 'elaine' => 'Palm',
'palmsource' => 'Palm',
// 'digital paths' => 'Palm',
// 'avantgo' => 'Avantgo',
// 'xiino' => 'Xiino',
'palmscape' => 'Palmscape',
// 'nokia' => 'Nokia',
// 'ericsson' => 'Ericsson',
// 'blackberry' => 'BlackBerry',
// 'motorola' => 'Motorola'
// Phones and Manufacturers
'motorola' => 'Motorola',
'nokia' => 'Nokia',
'palm' => 'Palm',
'iphone' => 'Apple iPhone',
'ipad' => 'iPad',
'ipod' => 'Apple iPod Touch',
'sony' => 'Sony Ericsson',
'ericsson' => 'Sony Ericsson',
'blackberry' => 'BlackBerry',
'cocoon' => 'O2 Cocoon',
'blazer' => 'Treo',
'lg' => 'LG',
'amoi' => 'Amoi',
'xda' => 'XDA',
'mda' => 'MDA',
'vario' => 'Vario',
'htc' => 'HTC',
'samsung' => 'Samsung',
'sharp' => 'Sharp',
'sie-' => 'Siemens',
'alcatel' => 'Alcatel',
'benq' => 'BenQ',
'ipaq' => 'HP iPaq',
'mot-' => 'Motorola',
'playstation portable' => 'PlayStation Portable',
'playstation 3' => 'PlayStation 3',
'playstation vita' => 'PlayStation Vita',
'hiptop' => 'Danger Hiptop',
'nec-' => 'NEC',
'panasonic' => 'Panasonic',
'philips' => 'Philips',
'sagem' => 'Sagem',
'sanyo' => 'Sanyo',
'spv' => 'SPV',
'zte' => 'ZTE',
'sendo' => 'Sendo',
'nintendo dsi' => 'Nintendo DSi',
'nintendo ds' => 'Nintendo DS',
'nintendo 3ds' => 'Nintendo 3DS',
'wii' => 'Nintendo Wii',
'open web' => 'Open Web',
'openweb' => 'OpenWeb',
// Operating Systems
'android' => 'Android',
'symbian' => 'Symbian',
'SymbianOS' => 'SymbianOS',
'elaine' => 'Palm',
'series60' => 'Symbian S60',
'windows ce' => 'Windows CE',
// Browsers
'obigo' => 'Obigo',
'netfront' => 'Netfront Browser',
'openwave' => 'Openwave Browser',
'mobilexplorer' => 'Mobile Explorer',
'operamini' => 'Opera Mini',
'opera mini' => 'Opera Mini',
'opera mobi' => 'Opera Mobile',
'fennec' => 'Firefox Mobile',
// Other
'digital paths' => 'Digital Paths',
'avantgo' => 'AvantGo',
'xiino' => 'Xiino',
'novarra' => 'Novarra Transcoder',
'vodafone' => 'Vodafone',
'docomo' => 'NTT DoCoMo',
'o2' => 'O2',
// Fallback
'mobile' => 'Generic Mobile',
'wireless' => 'Generic Mobile',
'j2me' => 'Generic Mobile',
'midp' => 'Generic Mobile',
'cldc' => 'Generic Mobile',
'up.link' => 'Generic Mobile',
'up.browser' => 'Generic Mobile',
'smartphone' => 'Generic Mobile',
'cellphone' => 'Generic Mobile',
];
/**
* -------------------------------------------------------------------
* Robots
* -------------------------------------------------------------------
*
* There are hundred of bots but these are the most common.
*
* @var array<string, string>
*/
public array $robots = [
'googlebot' => 'Googlebot',
'google-pagerenderer' => 'Google Page Renderer',
'google-read-aloud' => 'Google Read Aloud',
'google-safety' => 'Google Safety Bot',
'msnbot' => 'MSNBot',
'baiduspider' => 'Baiduspider',
'bingbot' => 'Bing',
'bingpreview' => 'BingPreview',
'slurp' => 'Inktomi Slurp',
'yahoo' => 'Yahoo',
'ask jeeves' => 'Ask Jeeves',
'fastcrawler' => 'FastCrawler',
'infoseek' => 'InfoSeek Robot 1.0',
'lycos' => 'Lycos',
'yandex' => 'YandexBot',
'mediapartners-google' => 'MediaPartners Google',
'CRAZYWEBCRAWLER' => 'Crazy Webcrawler',
'adsbot-google' => 'AdsBot Google',
'feedfetcher-google' => 'Feedfetcher Google',
'curious george' => 'Curious George',
'ia_archiver' => 'Alexa Crawler',
'MJ12bot' => 'Majestic-12',
'Uptimebot' => 'Uptimebot',
'duckduckbot' => 'DuckDuckBot',
'sogou' => 'Sogou Spider',
'exabot' => 'Exabot',
'bot' => 'Generic Bot',
'crawler' => 'Generic Crawler',
'spider' => 'Generic Spider',
];
}

44
app/Config/Validation.php Normal file
View File

@@ -0,0 +1,44 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Validation\StrictRules\CreditCardRules;
use CodeIgniter\Validation\StrictRules\FileRules;
use CodeIgniter\Validation\StrictRules\FormatRules;
use CodeIgniter\Validation\StrictRules\Rules;
class Validation extends BaseConfig
{
// --------------------------------------------------------------------
// Setup
// --------------------------------------------------------------------
/**
* Stores the classes that contain the
* rules that are available.
*
* @var list<string>
*/
public array $ruleSets = [
Rules::class,
FormatRules::class,
FileRules::class,
CreditCardRules::class,
];
/**
* Specifies the views that are used to display the
* errors.
*
* @var array<string, string>
*/
public array $templates = [
'list' => 'CodeIgniter\Validation\Views\list',
'single' => 'CodeIgniter\Validation\Views\single',
];
// --------------------------------------------------------------------
// Rules
// --------------------------------------------------------------------
}

79
app/Config/View.php Normal file
View File

@@ -0,0 +1,79 @@
<?php
namespace Config;
use CodeIgniter\Config\View as BaseView;
use CodeIgniter\View\ViewDecoratorInterface;
/**
* @phpstan-type parser_callable (callable(mixed): mixed)
* @phpstan-type parser_callable_string (callable(mixed): mixed)&string
*/
class View extends BaseView
{
/**
* When false, the view method will clear the data between each
* call. This keeps your data safe and ensures there is no accidental
* leaking between calls, so you would need to explicitly pass the data
* to each view. You might prefer to have the data stick around between
* calls so that it is available to all views. If that is the case,
* set $saveData to true.
*
* @var bool
*/
public $saveData = true;
/**
* Parser Filters map a filter name with any PHP callable. When the
* Parser prepares a variable for display, it will chain it
* through the filters in the order defined, inserting any parameters.
* To prevent potential abuse, all filters MUST be defined here
* in order for them to be available for use within the Parser.
*
* Examples:
* { title|esc(js) }
* { created_on|date(Y-m-d)|esc(attr) }
*
* @var array<string, string>
* @phpstan-var array<string, parser_callable_string>
*/
public $filters = [];
/**
* Parser Plugins provide a way to extend the functionality provided
* by the core Parser by creating aliases that will be replaced with
* any callable. Can be single or tag pair.
*
* @var array<string, callable|list<string>|string>
* @phpstan-var array<string, list<parser_callable_string>|parser_callable_string|parser_callable>
*/
public $plugins = [];
/**
* View Decorators are class methods that will be run in sequence to
* have a chance to alter the generated output just prior to caching
* the results.
*
* All classes must implement CodeIgniter\View\ViewDecoratorInterface
*
* @var list<class-string<ViewDecoratorInterface>>
*/
public array $decorators = [];
/**
* Subdirectory within app/Views for namespaced view overrides.
*
* Namespaced views will be searched in:
*
* app/Views/{$appOverridesFolder}/{Namespace}/{view_path}.{php|html...}
*
* This allows application-level overrides for package or module views
* without modifying vendor source files.
*
* Examples:
* 'overrides' -> app/Views/overrides/Example/Blog/post/card.php
* 'vendor' -> app/Views/vendor/Example/Blog/post/card.php
* '' -> app/Views/Example/Blog/post/card.php (direct mapping)
*/
public string $appOverridesFolder = 'overrides';
}

50
app/Config/WorkerMode.php Normal file
View File

@@ -0,0 +1,50 @@
<?php
namespace Config;
/**
* This configuration controls how CodeIgniter behaves when running
* in worker mode (with FrankenPHP).
*/
class WorkerMode
{
/**
* Persistent Services
*
* List of service names that should persist across requests.
* These services will NOT be reset between requests.
*
* Services not in this list will be reset for each request to prevent
* state leakage.
*
* Recommended persistent services:
* - `autoloader`: PSR-4 autoloading configuration
* - `locator`: File locator
* - `exceptions`: Exception handler
* - `commands`: CLI commands registry
* - `codeigniter`: Main application instance
* - `superglobals`: Superglobals wrapper
* - `routes`: Router configuration
* - `cache`: Cache instance
*
* @var list<string>
*/
public array $persistentServices = [
'autoloader',
'locator',
'exceptions',
'commands',
'codeigniter',
'superglobals',
'routes',
'cache',
];
/**
* Force Garbage Collection
*
* Whether to force garbage collection after each request.
* Helps prevent memory leaks at a small performance cost.
*/
public bool $forceGarbageCollection = true;
}

View File

@@ -0,0 +1,45 @@
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
/**
* BaseController provides a convenient place for loading components
* and performing functions that are needed by all your controllers.
*
* Extend this class in any new controllers:
* ```
* class Home extends BaseController
* ```
*
* For security, be sure to declare any new methods as protected or private.
*/
abstract class BaseController extends Controller
{
/**
* Be sure to declare properties for any property fetch you initialized.
* The creation of dynamic property is deprecated in PHP 8.2.
*/
// protected $session;
/**
* @return void
*/
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
// Load here all helpers you want to be available in your controllers that extend BaseController.
// Caution: Do not put the this below the parent::initController() call below.
// $this->helpers = ['form', 'url'];
// Caution: Do not edit this line.
parent::initController($request, $response, $logger);
// Preload any models, libraries, etc, here.
// $this->session = service('session');
}
}

View File

@@ -0,0 +1,152 @@
<?php
namespace App\Controllers;
use App\Modules\Auth\Services\AuthService;
use App\Modules\Academic\Models\ClassModel;
use CodeIgniter\HTTP\ResponseInterface;
/**
* Dashboard Academic (admin-only) pages.
*/
class DashboardAcademicController extends BaseController
{
/**
* GET /dashboard/academic/settings
* Academic settings hub (ADMIN only).
*/
public function academicSettings(): ResponseInterface
{
$authService = new AuthService();
$user = $authService->currentUser();
$data = ['user' => $user, 'content' => view('dashboard/academic_settings')];
return $this->response->setBody(view('layouts/main', $data));
}
/**
* GET /dashboard/academic/classes
* Class management page (ADMIN only).
*/
public function classes(): ResponseInterface
{
$authService = new AuthService();
$user = $authService->currentUser();
$data = ['user' => $user, 'content' => view('dashboard/classes')];
return $this->response->setBody(view('layouts/main', $data));
}
/**
* GET /dashboard/academic/subjects
*/
public function subjects(): ResponseInterface
{
$authService = new AuthService();
$user = $authService->currentUser();
$data = ['user' => $user, 'content' => view('dashboard/subjects')];
return $this->response->setBody(view('layouts/main', $data));
}
/**
* GET /dashboard/academic/teachers
*/
public function teachers(): ResponseInterface
{
$authService = new AuthService();
$user = $authService->currentUser();
$data = ['user' => $user, 'content' => view('dashboard/teachers')];
return $this->response->setBody(view('layouts/main', $data));
}
/**
* GET /dashboard/academic/lesson-slots
*/
public function lessonSlots(): ResponseInterface
{
$authService = new AuthService();
$user = $authService->currentUser();
$data = ['user' => $user, 'content' => view('dashboard/lesson_slots')];
return $this->response->setBody(view('layouts/main', $data));
}
/**
* GET /dashboard/academic/students
*/
public function students(): ResponseInterface
{
$authService = new AuthService();
$user = $authService->currentUser();
$data = ['user' => $user, 'content' => view('dashboard/students')];
return $this->response->setBody(view('layouts/main', $data));
}
/**
* GET /dashboard/academic/dapodik
*/
public function dapodik(): ResponseInterface
{
$authService = new AuthService();
$user = $authService->currentUser();
$data = ['user' => $user, 'content' => view('dashboard/dapodik')];
return $this->response->setBody(view('layouts/main', $data));
}
/**
* GET /dashboard/academic/schedule-builder
* Class selector page; then redirect to schedule-builder/{classId}.
*/
public function scheduleBuilderIndex(): ResponseInterface
{
$authService = new AuthService();
$user = $authService->currentUser();
$data = [
'user' => $user,
'content' => view('dashboard/schedule_builder_index'),
];
return $this->response->setBody(view('layouts/main', $data));
}
/**
* GET /dashboard/academic/schedule-builder/{classId}
*/
public function scheduleBuilder($classId): ResponseInterface
{
$authService = new AuthService();
$user = $authService->currentUser();
$classId = (int) $classId;
$classModel = new ClassModel();
$classEntity = $classModel->find($classId);
$className = $classEntity ? (string) $classEntity->name : 'Kelas ' . $classId;
$data = [
'user' => $user,
'classId' => $classId,
'className' => $className,
'content' => view('dashboard/schedule_builder', [
'classId' => $classId,
'className' => $className,
]),
];
return $this->response->setBody(view('layouts/main', $data));
}
/**
* GET /dashboard/academic/discipline-settings
* Master poin pelanggaran (ADMIN only, via route filter).
*/
public function disciplineSettings(): ResponseInterface
{
$authService = new AuthService();
$user = $authService->currentUser();
$data = [
'user' => $user,
'content' => view('dashboard/discipline_settings'),
];
return $this->response->setBody(view('layouts/main', $data));
}
}

View File

@@ -0,0 +1,147 @@
<?php
namespace App\Controllers;
use App\Modules\Auth\Services\AuthService;
use CodeIgniter\HTTP\ResponseInterface;
/**
* Web Dashboard Page Controller
*
* Serves /dashboard with TailAdmin layout. Requires authenticated session.
*/
class DashboardPageController extends BaseController
{
public function index(): ResponseInterface
{
$authService = new AuthService();
$user = $authService->currentUser();
$data = [
'user' => $user,
'content' => view('dashboard/index'),
];
return $this->response->setBody(view('layouts/main', $data));
}
/**
* GET /dashboard/attendance/reports
* Attendance reports index: pick date, list schedules, link to report per schedule.
*/
public function attendanceReports(): ResponseInterface
{
$authService = new AuthService();
$user = $authService->currentUser();
$data = [
'user' => $user,
'content' => view('dashboard/attendance_reports'),
];
return $this->response->setBody(view('layouts/main', $data));
}
/**
* GET /dashboard/attendance/report/{scheduleId}
* Schedule attendance report page (expected, present, late, absent).
*/
public function attendanceReport($scheduleId): ResponseInterface
{
$authService = new AuthService();
$user = $authService->currentUser();
$data = [
'user' => $user,
'scheduleId' => (int) $scheduleId,
'content' => view('dashboard/attendance_report', ['scheduleId' => (int) $scheduleId]),
];
return $this->response->setBody(view('layouts/main', $data));
}
/**
* GET /dashboard/devices
* Devices list page (ADMIN only).
*/
public function devices(): ResponseInterface
{
$authService = new AuthService();
$user = $authService->currentUser();
$data = [
'user' => $user,
'content' => view('dashboard/devices'),
];
return $this->response->setBody(view('layouts/main', $data));
}
/**
* GET /dashboard/schedule/today
* Daily schedule page (today's schedules, role-filtered).
*/
public function scheduleToday(): ResponseInterface
{
$authService = new AuthService();
$user = $authService->currentUser();
$data = [
'user' => $user,
'content' => view('dashboard/schedule_today'),
];
return $this->response->setBody(view('layouts/main', $data));
}
/**
* GET /dashboard/discipline
* Poin pelanggaran / disiplin siswa (guru, wali, admin).
*/
public function discipline(): ResponseInterface
{
$authService = new AuthService();
$user = $authService->currentUser();
$data = [
'user' => $user,
'content' => view('dashboard/discipline'),
];
return $this->response->setBody(view('layouts/main', $data));
}
/**
* GET /dashboard/parent
* Portal Orang Tua - untuk melihat data anak (absensi, pelanggaran).
*/
public function parent(): ResponseInterface
{
$authService = new AuthService();
$user = $authService->currentUser();
$data = [
'user' => $user,
'content' => view('dashboard/parent'),
];
return $this->response->setBody(view('layouts/main', $data));
}
/**
* GET /dashboard/presence-settings
* Pengaturan presensi terpusat: koordinat sekolah + jam masuk & jam pulang (ADMIN only).
*/
public function presenceSettings(): ResponseInterface
{
$authService = new AuthService();
$user = $authService->currentUser();
$data = [
'user' => $user,
'content' => view('dashboard/presence_settings'),
];
return $this->response->setBody(view('layouts/main', $data));
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace App\Controllers;
use App\Modules\Auth\Services\AuthService;
use CodeIgniter\HTTP\ResponseInterface;
/**
* Login Page Controller
*
* GET /login shows form; form submits to /api/auth/login (client-side).
*/
class LoginController extends BaseController
{
public function index(): ResponseInterface
{
$authService = new AuthService();
if ($authService->currentUser() !== null) {
return redirect()->to('/dashboard');
}
return $this->response->setBody(view('login/index'));
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace App\Controllers;
use App\Modules\Auth\Services\AuthService;
use CodeIgniter\HTTP\ResponseInterface;
/**
* Web Logout: clears session and redirects to login.
*/
class LogoutController extends BaseController
{
public function index(): ResponseInterface
{
(new AuthService())->logout();
return redirect()->to('/login');
}
}

View File

@@ -0,0 +1,81 @@
<?php
namespace App\Core;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
/**
* Base API Controller
*
* Provides standardized JSON response methods for all API controllers.
* All responses follow a consistent format:
* {
* success: boolean,
* message: string,
* data: mixed,
* meta?: object
* }
*/
abstract class BaseApiController extends BaseController
{
/**
* Send a successful JSON response
*
* @param mixed $data Response data
* @param string $message Success message
* @param array|null $meta Optional metadata
* @param int $statusCode HTTP status code (default: 200)
* @return ResponseInterface
*/
protected function successResponse(
mixed $data = null,
string $message = 'Success',
?array $meta = null,
int $statusCode = ResponseInterface::HTTP_OK
): ResponseInterface {
$response = [
'success' => true,
'message' => $message,
'data' => $data,
];
if ($meta !== null) {
$response['meta'] = $meta;
}
return $this->response
->setStatusCode($statusCode)
->setJSON($response);
}
/**
* Send an error JSON response
*
* @param string $message Error message
* @param mixed $data Optional error data
* @param array|null $meta Optional metadata
* @param int $statusCode HTTP status code (default: 400)
* @return ResponseInterface
*/
protected function errorResponse(
string $message = 'An error occurred',
mixed $data = null,
?array $meta = null,
int $statusCode = ResponseInterface::HTTP_BAD_REQUEST
): ResponseInterface {
$response = [
'success' => false,
'message' => $message,
'data' => $data,
];
if ($meta !== null) {
$response['meta'] = $meta;
}
return $this->response
->setStatusCode($statusCode)
->setJSON($response);
}
}

View File

View File

@@ -0,0 +1,58 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateDevicesTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
'device_code' => [
'type' => 'VARCHAR',
'constraint' => '100',
'unique' => true,
],
'device_name' => [
'type' => 'VARCHAR',
'constraint' => '255',
],
'api_key' => [
'type' => 'VARCHAR',
'constraint' => '255',
],
'is_active' => [
'type' => 'TINYINT',
'constraint' => 1,
'default' => 1,
],
'last_seen_at' => [
'type' => 'DATETIME',
'null' => true,
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
'updated_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->createTable('devices');
}
public function down()
{
$this->forge->dropTable('devices');
}
}

View File

@@ -0,0 +1,44 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateClassesTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
'name' => [
'type' => 'VARCHAR',
'constraint' => '100',
],
'grade' => [
'type' => 'VARCHAR',
'constraint' => '50',
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
'updated_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->createTable('classes');
}
public function down()
{
$this->forge->dropTable('classes');
}
}

View File

@@ -0,0 +1,52 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateStudentsTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
'nis' => [
'type' => 'VARCHAR',
'constraint' => '50',
'unique' => true,
],
'name' => [
'type' => 'VARCHAR',
'constraint' => '255',
],
'class_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
'updated_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->addKey('class_id');
$this->forge->addForeignKey('class_id', 'classes', 'id', 'CASCADE', 'CASCADE');
$this->forge->createTable('students');
}
public function down()
{
$this->forge->dropTable('students');
}
}

View File

@@ -0,0 +1,40 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateSubjectsTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
'name' => [
'type' => 'VARCHAR',
'constraint' => '255',
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
'updated_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->createTable('subjects');
}
public function down()
{
$this->forge->dropTable('subjects');
}
}

View File

@@ -0,0 +1,69 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateSchedulesTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
'class_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
],
'subject_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
],
'teacher_name' => [
'type' => 'VARCHAR',
'constraint' => '255',
],
'day_of_week' => [
'type' => 'TINYINT',
'constraint' => 1,
'comment' => '1=Monday, 7=Sunday',
],
'start_time' => [
'type' => 'TIME',
],
'end_time' => [
'type' => 'TIME',
],
'room' => [
'type' => 'VARCHAR',
'constraint' => '100',
'null' => true,
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
'updated_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->addKey(['class_id', 'day_of_week']);
$this->forge->addForeignKey('class_id', 'classes', 'id', 'CASCADE', 'CASCADE');
$this->forge->addForeignKey('subject_id', 'subjects', 'id', 'CASCADE', 'CASCADE');
$this->forge->createTable('schedules');
}
public function down()
{
$this->forge->dropTable('schedules');
}
}

View File

@@ -0,0 +1,63 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateZonesTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
'zone_code' => [
'type' => 'VARCHAR',
'constraint' => '100',
'unique' => true,
],
'zone_name' => [
'type' => 'VARCHAR',
'constraint' => '255',
],
'latitude' => [
'type' => 'DECIMAL',
'constraint' => '10,8',
],
'longitude' => [
'type' => 'DECIMAL',
'constraint' => '11,8',
],
'radius_meters' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
],
'is_active' => [
'type' => 'TINYINT',
'constraint' => 1,
'default' => 1,
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
'updated_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->createTable('zones');
}
public function down()
{
$this->forge->dropTable('zones');
}
}

View File

@@ -0,0 +1,78 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateAttendanceSessionsTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
'student_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
],
'schedule_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'null' => true,
],
'device_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
],
'checkin_at' => [
'type' => 'DATETIME',
],
'latitude' => [
'type' => 'DECIMAL',
'constraint' => '10,8',
],
'longitude' => [
'type' => 'DECIMAL',
'constraint' => '11,8',
],
'confidence' => [
'type' => 'DECIMAL',
'constraint' => '5,2',
'null' => true,
],
'status' => [
'type' => 'ENUM',
'constraint' => ['PRESENT', 'LATE', 'OUTSIDE_ZONE', 'NO_SCHEDULE', 'INVALID_DEVICE'],
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
'updated_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->addKey(['student_id', 'checkin_at']);
$this->forge->addKey('schedule_id');
$this->forge->addKey('device_id');
$this->forge->addForeignKey('student_id', 'students', 'id', 'CASCADE', 'CASCADE');
$this->forge->addForeignKey('schedule_id', 'schedules', 'id', 'SET NULL', 'CASCADE');
$this->forge->addForeignKey('device_id', 'devices', 'id', 'CASCADE', 'CASCADE');
$this->forge->createTable('attendance_sessions');
}
public function down()
{
$this->forge->dropTable('attendance_sessions');
}
}

View File

@@ -0,0 +1,45 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateParentsTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
'name' => [
'type' => 'VARCHAR',
'constraint' => '255',
],
'phone_number' => [
'type' => 'VARCHAR',
'constraint' => '20',
'null' => true,
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
'updated_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->createTable('parents');
}
public function down()
{
$this->forge->dropTable('parents');
}
}

View File

@@ -0,0 +1,62 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateTelegramAccountsTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
'telegram_user_id' => [
'type' => 'BIGINT',
'constraint' => 20,
'unsigned' => true,
'unique' => true,
],
'username' => [
'type' => 'VARCHAR',
'constraint' => '255',
'null' => true,
],
'first_name' => [
'type' => 'VARCHAR',
'constraint' => '255',
'null' => true,
],
'last_name' => [
'type' => 'VARCHAR',
'constraint' => '255',
'null' => true,
],
'is_verified' => [
'type' => 'TINYINT',
'constraint' => 1,
'default' => 0,
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
'updated_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->createTable('telegram_accounts');
}
public function down()
{
$this->forge->dropTable('telegram_accounts');
}
}

View File

@@ -0,0 +1,53 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateStudentParentsTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
'student_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
],
'parent_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
],
'relationship' => [
'type' => 'ENUM',
'constraint' => ['AYAH', 'IBU', 'WALI'],
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
'updated_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->addKey(['student_id', 'parent_id']);
$this->forge->addForeignKey('student_id', 'students', 'id', 'CASCADE', 'CASCADE');
$this->forge->addForeignKey('parent_id', 'parents', 'id', 'CASCADE', 'CASCADE');
$this->forge->createTable('student_parents');
}
public function down()
{
$this->forge->dropTable('student_parents');
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class AddParentLinkCodeToStudentsTable extends Migration
{
public function up()
{
$fields = [
'parent_link_code' => [
'type' => 'VARCHAR',
'constraint' => '16',
'null' => true,
'unique' => true,
'after' => 'class_id',
],
];
$this->forge->addColumn('students', $fields);
}
public function down()
{
$this->forge->dropColumn('students', 'parent_link_code');
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class AddParentIdToTelegramAccountsTable extends Migration
{
public function up()
{
$this->forge->addColumn('telegram_accounts', [
'parent_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'null' => true,
'after' => 'is_verified',
],
]);
$this->forge->addForeignKey('parent_id', 'parents', 'id', 'CASCADE', 'SET NULL', 'telegram_accounts_parent_id_fk');
}
public function down()
{
$this->forge->dropForeignKey('telegram_accounts', 'telegram_accounts_parent_id_fk');
$this->forge->dropColumn('telegram_accounts', 'parent_id');
}
}

View File

@@ -0,0 +1,53 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateUsersTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
'name' => [
'type' => 'VARCHAR',
'constraint' => '255',
],
'email' => [
'type' => 'VARCHAR',
'constraint' => '255',
'unique' => true,
],
'password_hash' => [
'type' => 'VARCHAR',
'constraint' => '255',
],
'is_active' => [
'type' => 'TINYINT',
'constraint' => 1,
'default' => 1,
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
'updated_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->createTable('users');
}
public function down()
{
$this->forge->dropTable('users');
}
}

View File

@@ -0,0 +1,36 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateRolesTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
'role_code' => [
'type' => 'VARCHAR',
'constraint' => '50',
'unique' => true,
],
'role_name' => [
'type' => 'VARCHAR',
'constraint' => '100',
],
]);
$this->forge->addKey('id', true);
$this->forge->createTable('roles');
}
public function down()
{
$this->forge->dropTable('roles');
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateUserRolesTable extends Migration
{
public function up()
{
$this->forge->addField([
'user_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
],
'role_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
],
]);
$this->forge->addKey(['user_id', 'role_id'], true);
$this->forge->addForeignKey('user_id', 'users', 'id', 'CASCADE', 'CASCADE');
$this->forge->addForeignKey('role_id', 'roles', 'id', 'CASCADE', 'CASCADE');
$this->forge->createTable('user_roles');
}
public function down()
{
$this->forge->dropTable('user_roles');
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class AddUserIdToParentsTable extends Migration
{
public function up()
{
$this->forge->addColumn('parents', [
'user_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'null' => true,
'after' => 'id',
],
]);
$this->forge->addForeignKey('user_id', 'users', 'id', 'SET NULL', 'CASCADE', 'parents_user_id_fk');
}
public function down()
{
$this->forge->dropForeignKey('parents', 'parents_user_id_fk');
$this->forge->dropColumn('parents', 'user_id');
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class AddWaliUserIdToClassesTable extends Migration
{
public function up()
{
$this->forge->addColumn('classes', [
'wali_user_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'null' => true,
'after' => 'grade',
],
]);
$this->forge->addForeignKey('wali_user_id', 'users', 'id', 'SET NULL', 'CASCADE', 'classes_wali_user_id_fk');
}
public function down()
{
$this->forge->dropForeignKey('classes', 'classes_wali_user_id_fk');
$this->forge->dropColumn('classes', 'wali_user_id');
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class AddTeacherUserIdToSchedulesTable extends Migration
{
public function up()
{
$this->forge->addColumn('schedules', [
'teacher_user_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'null' => true,
'after' => 'teacher_name',
],
]);
$this->forge->addForeignKey('teacher_user_id', 'users', 'id', 'SET NULL', 'CASCADE', 'schedules_teacher_user_id_fk');
}
public function down()
{
$this->forge->dropForeignKey('schedules', 'schedules_teacher_user_id_fk');
$this->forge->dropColumn('schedules', 'teacher_user_id');
}
}

View File

@@ -0,0 +1,41 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class AddAttendanceDateAndUniqueToAttendanceSessionsTable extends Migration
{
public function up()
{
$this->forge->addColumn('attendance_sessions', [
'attendance_date' => [
'type' => 'DATE',
'null' => true,
'after' => 'schedule_id',
],
]);
$this->db->query('UPDATE attendance_sessions SET attendance_date = DATE(checkin_at) WHERE attendance_date IS NULL');
$this->forge->modifyColumn('attendance_sessions', [
'attendance_date' => [
'type' => 'DATE',
'null' => false,
'after' => 'schedule_id',
],
]);
$prefix = $this->db->DBPrefix;
$table = $this->db->escapeIdentifiers($prefix . 'attendance_sessions');
$this->db->query('ALTER TABLE ' . $table . ' ADD UNIQUE KEY unique_student_schedule_date (student_id, schedule_id, attendance_date)');
}
public function down()
{
$prefix = $this->db->DBPrefix;
$table = $this->db->escapeIdentifiers($prefix . 'attendance_sessions');
$this->db->query('ALTER TABLE ' . $table . ' DROP KEY unique_student_schedule_date');
$this->forge->dropColumn('attendance_sessions', 'attendance_date');
}
}

View File

@@ -0,0 +1,44 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateLessonSlotsTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
'slot_number' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
],
'start_time' => [
'type' => 'TIME',
],
'end_time' => [
'type' => 'TIME',
],
'is_active' => [
'type' => 'TINYINT',
'constraint' => 1,
'default' => 1,
],
]);
$this->forge->addKey('id', true);
$this->forge->addUniqueKey('slot_number');
$this->forge->createTable('lesson_slots');
}
public function down()
{
$this->forge->dropTable('lesson_slots');
}
}

View File

@@ -0,0 +1,38 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class AddLessonSlotIdAndUniqueToSchedulesTable extends Migration
{
public function up()
{
$this->forge->addColumn('schedules', [
'lesson_slot_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'null' => true,
'after' => 'teacher_user_id',
],
'is_active' => [
'type' => 'TINYINT',
'constraint' => 1,
'default' => 1,
'after' => 'room',
],
]);
$this->forge->addForeignKey('lesson_slot_id', 'lesson_slots', 'id', 'SET NULL', 'CASCADE', 'schedules_lesson_slot_id_fk');
$this->forge->addUniqueKey(['class_id', 'lesson_slot_id', 'day_of_week'], 'schedules_class_slot_day_unique');
}
public function down()
{
$this->forge->dropForeignKey('schedules', 'schedules_lesson_slot_id_fk');
$this->forge->dropKey('schedules', 'schedules_class_slot_day_unique');
$this->forge->dropColumn('schedules', 'lesson_slot_id');
$this->forge->dropColumn('schedules', 'is_active');
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class AddMajorToClassesTable extends Migration
{
public function up()
{
$this->forge->addColumn('classes', [
'major' => [
'type' => 'VARCHAR',
'constraint' => 50,
'null' => false,
'default' => 'IPA',
'after' => 'grade',
],
]);
}
public function down()
{
$this->forge->dropColumn('classes', 'major');
}
}

View File

@@ -0,0 +1,25 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class AddCodeToSubjectsTable extends Migration
{
public function up()
{
$this->forge->addColumn('subjects', [
'code' => [
'type' => 'VARCHAR',
'constraint' => 50,
'null' => true,
'after' => 'name',
],
]);
}
public function down()
{
$this->forge->dropColumn('subjects', 'code');
}
}

View File

@@ -0,0 +1,65 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class AddStudentFieldsForManagement extends Migration
{
public function up()
{
// Rename nis -> nisn (Dapodik compatible; unique index follows column rename)
$this->db->query('ALTER TABLE ' . $this->db->prefixTable('students') . ' CHANGE nis nisn VARCHAR(50) NOT NULL');
// Add gender (L/P)
$this->forge->addColumn('students', [
'gender' => [
'type' => 'VARCHAR',
'constraint' => 1,
'null' => true,
'after' => 'name',
],
]);
// Add is_active (default 1)
$this->forge->addColumn('students', [
'is_active' => [
'type' => 'TINYINT',
'constraint' => 1,
'default' => 1,
'after' => 'class_id',
],
]);
// Make class_id nullable (for unmapped / Dapodik sync)
$this->forge->dropForeignKey('students', 'students_class_id_foreign');
$this->forge->modifyColumn('students', [
'class_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'null' => true,
],
]);
$this->forge->addForeignKey('class_id', 'classes', 'id', 'SET NULL', 'CASCADE', 'students_class_id_foreign');
}
public function down()
{
$this->forge->dropForeignKey('students', 'students_class_id_foreign');
$this->forge->modifyColumn('students', [
'class_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'null' => false,
],
]);
$this->forge->addForeignKey('class_id', 'classes', 'id', 'CASCADE', 'CASCADE', 'students_class_id_foreign');
$this->forge->dropColumn('students', 'is_active');
$this->forge->dropColumn('students', 'gender');
$this->db->query('ALTER TABLE ' . $this->db->prefixTable('students') . ' CHANGE nisn nis VARCHAR(50) NOT NULL');
}
}

View File

@@ -0,0 +1,51 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateDapodikRombelMappingsTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
'dapodik_rombel' => [
'type' => 'VARCHAR',
'constraint' => 100,
],
'class_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'null' => true,
],
'last_seen_at' => [
'type' => 'DATETIME',
'null' => true,
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
'updated_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->addUniqueKey('dapodik_rombel');
$this->forge->addForeignKey('class_id', 'classes', 'id', 'SET NULL', 'CASCADE', 'dapodik_rombel_mappings_class_id_fk');
$this->forge->createTable('dapodik_rombel_mappings');
}
public function down()
{
$this->forge->dropTable('dapodik_rombel_mappings');
}
}

View File

@@ -0,0 +1,69 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateDapodikSyncJobsTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'BIGINT',
'constraint' => 20,
'unsigned' => true,
'auto_increment' => true,
],
'type' => [
'type' => 'VARCHAR',
'constraint' => 50,
'comment' => 'students|classes',
],
'total_rows' => [
'type' => 'INT',
'constraint' => 11,
'default' => 0,
],
'processed_rows' => [
'type' => 'INT',
'constraint' => 11,
'default' => 0,
],
'status' => [
'type' => 'VARCHAR',
'constraint' => 20,
'default' => 'pending',
'comment' => 'pending|running|completed|failed',
],
'message' => [
'type' => 'TEXT',
'null' => true,
],
'started_at' => [
'type' => 'DATETIME',
'null' => true,
],
'finished_at' => [
'type' => 'DATETIME',
'null' => true,
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
'updated_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->addKey('status');
$this->forge->createTable('dapodik_sync_jobs');
}
public function down()
{
$this->forge->dropTable('dapodik_sync_jobs');
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class AddDapodikIdToStudentsTable extends Migration
{
public function up()
{
// Add dapodik_id column (nullable, unique) to students
$this->forge->addColumn('students', [
'dapodik_id' => [
'type' => 'VARCHAR',
'constraint' => 64,
'null' => true,
'after' => 'id',
],
]);
// Add unique index on dapodik_id (for upsert)
$this->db->query('CREATE UNIQUE INDEX students_dapodik_id_unique ON ' . $this->db->prefixTable('students') . ' (dapodik_id)');
}
public function down()
{
// Drop unique index and column
$this->db->query('DROP INDEX students_dapodik_id_unique ON ' . $this->db->prefixTable('students'));
$this->forge->dropColumn('students', 'dapodik_id');
}
}

View File

@@ -0,0 +1,52 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateTeacherSubjectsTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
'teacher_user_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
],
'subject_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
'updated_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->addUniqueKey(['teacher_user_id', 'subject_id'], 'teacher_subjects_unique');
$this->forge->addForeignKey('teacher_user_id', 'users', 'id', 'CASCADE', 'CASCADE', 'teacher_subjects_teacher_fk');
$this->forge->addForeignKey('subject_id', 'subjects', 'id', 'CASCADE', 'CASCADE', 'teacher_subjects_subject_fk');
$this->forge->createTable('teacher_subjects');
}
public function down()
{
$this->forge->dropForeignKey('teacher_subjects', 'teacher_subjects_teacher_fk');
$this->forge->dropForeignKey('teacher_subjects', 'teacher_subjects_subject_fk');
$this->forge->dropTable('teacher_subjects');
}
}

View File

@@ -0,0 +1,31 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class AddFaceExternalIdToStudentsTable extends Migration
{
public function up()
{
// Add nullable face_external_id column for linking to external face-recognition ID
$this->forge->addColumn('students', [
'face_external_id' => [
'type' => 'VARCHAR',
'constraint' => 100,
'null' => true,
'after' => 'dapodik_id',
],
]);
// Unique index so one face ID hanya milik satu siswa
$this->forge->addUniqueKey('face_external_id', 'students_face_external_id_unique');
}
public function down()
{
$this->forge->dropKey('students', 'students_face_external_id_unique');
$this->forge->dropColumn('students', 'face_external_id');
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateStudentMobileAccountsTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
'student_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
],
'pin_hash' => [
'type' => 'VARCHAR',
'constraint' => 255,
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
'updated_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->addUniqueKey('student_id');
$this->forge->addForeignKey('student_id', 'students', 'id', 'CASCADE', 'CASCADE', 'student_mobile_accounts_student_fk');
$this->forge->createTable('student_mobile_accounts');
}
public function down()
{
$this->forge->dropTable('student_mobile_accounts');
}
}

View File

@@ -0,0 +1,50 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateViolationCategoriesTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
'code' => [
'type' => 'VARCHAR',
'constraint' => 10,
],
'name' => [
'type' => 'VARCHAR',
'constraint' => 100,
],
'description' => [
'type' => 'TEXT',
'null' => true,
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
'updated_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->addUniqueKey('code', 'violation_categories_code_unique');
$this->forge->createTable('violation_categories');
}
public function down()
{
$this->forge->dropTable('violation_categories');
}
}

View File

@@ -0,0 +1,67 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateViolationsTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
'category_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
],
'code' => [
'type' => 'VARCHAR',
'constraint' => 20,
'null' => true,
],
'title' => [
'type' => 'VARCHAR',
'constraint' => 255,
],
'description' => [
'type' => 'TEXT',
'null' => true,
],
'score' => [
'type' => 'INT',
'constraint' => 11,
'default' => 0,
],
'is_active' => [
'type' => 'TINYINT',
'constraint' => 1,
'default' => 1,
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
'updated_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->addForeignKey('category_id', 'violation_categories', 'id', 'CASCADE', 'CASCADE', 'violations_category_fk');
$this->forge->createTable('violations');
}
public function down()
{
$this->forge->dropForeignKey('violations', 'violations_category_fk');
$this->forge->dropTable('violations');
}
}

View File

@@ -0,0 +1,77 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateStudentViolationsTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
'student_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
],
'class_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'null' => true,
],
'violation_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
],
'reported_by_user_id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
],
'occurred_at' => [
'type' => 'DATETIME',
'null' => true,
],
'notes' => [
'type' => 'TEXT',
'null' => true,
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
'updated_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->addKey('student_id');
$this->forge->addKey('class_id');
$this->forge->addKey('occurred_at');
$this->forge->addForeignKey('student_id', 'students', 'id', 'CASCADE', 'CASCADE', 'student_violations_student_fk');
$this->forge->addForeignKey('class_id', 'classes', 'id', 'SET NULL', 'CASCADE', 'student_violations_class_fk');
$this->forge->addForeignKey('violation_id', 'violations', 'id', 'CASCADE', 'CASCADE', 'student_violations_violation_fk');
$this->forge->addForeignKey('reported_by_user_id', 'users', 'id', 'CASCADE', 'CASCADE', 'student_violations_reporter_fk');
$this->forge->createTable('student_violations');
}
public function down()
{
$this->forge->dropForeignKey('student_violations', 'student_violations_student_fk');
$this->forge->dropForeignKey('student_violations', 'student_violations_class_fk');
$this->forge->dropForeignKey('student_violations', 'student_violations_violation_fk');
$this->forge->dropForeignKey('student_violations', 'student_violations_reporter_fk');
$this->forge->dropTable('student_violations');
}
}

View File

@@ -0,0 +1,146 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
/**
* Seed awal master pelanggaran berdasarkan tabel tata tertib
* yang kamu kirim (kategori AI + tindak pidana).
*
* Catatan: migration ini hanya menambah data jika belum ada
* (dicek berdasarkan code kategori + title pelanggaran).
*/
class SeedViolationsFromPolicy extends Migration
{
public function up()
{
$db = \Config\Database::connect();
// 1) Pastikan kategori ada
$categories = [
'A' => ['name' => 'KETERLAMBATAN & KEHADIRAN'],
'B' => ['name' => 'PAKAIAN'],
'C' => ['name' => 'KEPRIBADIAN'],
'D' => ['name' => 'KETERTIBAN'],
'E' => ['name' => 'MEROKOK'],
'F' => ['name' => 'PORNOGRAFI'],
'G' => ['name' => 'SENJATA TAJAM'],
'H' => ['name' => 'NAPZA DAN / MINUMAN KERAS'],
'I' => ['name' => 'BERKELAHI / TAWURAN'],
'J' => ['name' => 'TINDAK PIDANA HUKUM'],
];
$catIds = [];
foreach ($categories as $code => $cfg) {
$row = $db->table('violation_categories')->where('code', $code)->get()->getRowArray();
if (! $row) {
$db->table('violation_categories')->insert([
'code' => $code,
'name' => $cfg['name'],
'description' => null,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
]);
$catIds[$code] = (int) $db->insertID();
} else {
$catIds[$code] = (int) $row['id'];
}
}
// Helper untuk insert jika belum ada (berdasarkan title)
$insertViolation = function (string $code, string $title, int $score, ?string $description = null) use ($db, $catIds): void {
if (! isset($catIds[$code])) {
return;
}
$exists = $db->table('violations')
->where('category_id', $catIds[$code])
->where('title', $title)
->countAllResults();
if ($exists > 0) {
return;
}
$db->table('violations')->insert([
'category_id' => $catIds[$code],
'code' => null,
'title' => $title,
'description' => $description,
'score' => $score,
'is_active' => 1,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
]);
};
// 2) Seed pelanggaran per kategori (ringkas dari tabel yang kamu kirim)
// A — Keterlambatan & Kehadiran
$insertViolation('A', 'Terlambat (dipulangkan dicatat tidak hadir tanpa keterangan)', 5);
$insertViolation('A', 'Tidak masuk tanpa keterangan', 5);
$insertViolation('A', 'Tidak masuk dengan membuat keterangan palsu', 10);
$insertViolation('A', 'Tidak mengikuti jam pelajaran tertentu', 5);
$insertViolation('A', 'Keluar saat pelajaran berlangsung dan tidak kembali sampai pulang', 5);
$insertViolation('A', 'Tidak ikut upacara bendera', 5);
$insertViolation('A', 'Meninggalkan pelajaran atau sekolah dengan izin palsu', 10);
// B — Pakaian
$insertViolation('B', 'Memakai seragam tidak sesuai aturan (teguran 1)', 2);
$insertViolation('B', 'Memakai seragam tidak sesuai aturan (teguran 2 + surat pernyataan 1)', 2);
$insertViolation('B', 'Memakai seragam tidak sesuai aturan (teguran 3 + sanksi sekolah)', 2);
$insertViolation('B', 'Tidak memakai seragam sekolah sesuai jadwal', 3);
// C — Kepribadian
$insertViolation('C', 'Berhias berlebihan', 5);
$insertViolation('C', 'Siswa putra memakai gelang, kalung, anting', 10);
$insertViolation('C', 'Memakai tindik di wajah atau tubuh lain (siswi)', 10);
$insertViolation('C', 'Memakai tato / atribut tidak wajar bagi pelajar', 20);
$insertViolation('C', 'Berduaan/bermesraan/pacaran (tindak asusila, melanggar kesopanan)', 50);
$insertViolation('C', 'Melawan kepala sekolah/guru/karyawan dengan ancaman', 75);
$insertViolation('C', 'Melawan kepala sekolah/guru/karyawan dengan pemukulan', 100);
$insertViolation('C', 'Intimidasi / bullying dengan kekerasan', 75);
$insertViolation('C', 'Tindakan tidak menyenangkan sesama siswa', 15);
$insertViolation('C', 'Mengaktifkan HP saat KBM berlangsung', 5);
$insertViolation('C', 'Mencemarkan nama kepala sekolah/guru/karyawan/sekolah', 50);
$insertViolation('C', 'Diketahui hamil / menikah', 100);
// D — Ketertiban
$insertViolation('D', 'Mengotori / mencoret benda milik sekolah/guru/karyawan/teman/lingkungan', 15);
$insertViolation('D', 'Merusak atau mengambil barang milik sekolah/guru/karyawan/teman', 50);
$insertViolation('D', 'Membawa/menggunakan benda tak terkait KBM tanpa izin', 15);
$insertViolation('D', 'Memakai sandal/sepatu sandal saat pelajaran tanpa izin', 5);
$insertViolation('D', 'Melompat pagar sekolah untuk keluar/masuk', 20);
$insertViolation('D', 'Tidak membuang sampah pada tempatnya', 3);
$insertViolation('D', 'Merusak tanaman dengan sengaja', 5);
// E — Merokok
$insertViolation('E', 'Membawa rokok ke sekolah', 20);
$insertViolation('E', 'Menghisap rokok di sekolah', 25);
// F — Pornografi
$insertViolation('F', 'Memiliki/membawa/mempergunakan media berkonten pornografi/kekerasan', 65);
$insertViolation('F', 'Memperjualbelikan media berkonten pornografi/kekerasan', 75);
// G — Senjata tajam
$insertViolation('G', 'Membawa senjata tajam/api/bahan peledak tanpa izin', 100);
$insertViolation('G', 'Memperjualbelikan senjata tajam/api/bahan peledak', 100);
$insertViolation('G', 'Menggunakan senjata tajam/api/bahan peledak untuk mengancam/melukai', 100);
// H — NAPZA / minuman keras
$insertViolation('H', 'Menggunakan napza dan/atau minuman terlarang', 100);
$insertViolation('H', 'Membawa napza dan/atau minuman terlarang', 100);
$insertViolation('H', 'Mengedarkan/memperjualbelikan napza/minuman keras', 100);
// I — Berkelahi / tawuran
$insertViolation('I', 'Indikasi / berkelahi / tawuran dengan siswa sekolah lain', 100);
$insertViolation('I', 'Berkelahi antar siswa', 100);
// J — Tindak pidana hukum lain
$insertViolation('J', 'Tersangkut tindak pidana lainnya', 10);
}
public function down()
{
// Tidak perlu menghapus data seed; biarkan tetap ada.
}
}

View File

@@ -0,0 +1,65 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateDisciplineLevelsTable extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
'min_score' => [
'type' => 'INT',
'constraint' => 11,
'default' => 0,
],
'max_score' => [
'type' => 'INT',
'constraint' => 11,
'null' => true, // null = tak terbatas (>= min_score)
],
'title' => [
'type' => 'VARCHAR',
'constraint' => 100,
],
'school_action' => [
'type' => 'TEXT',
'null' => true,
],
'executor' => [
'type' => 'VARCHAR',
'constraint' => 150,
'null' => true,
],
'is_active' => [
'type' => 'TINYINT',
'constraint' => 1,
'default' => 1,
],
'created_at' => [
'type' => 'DATETIME',
'null' => true,
],
'updated_at' => [
'type' => 'DATETIME',
'null' => true,
],
]);
$this->forge->addKey('id', true);
$this->forge->createTable('discipline_levels');
}
public function down()
{
$this->forge->dropTable('discipline_levels');
}
}

View File

@@ -0,0 +1,76 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
/**
* Seed awal level disiplin berdasarkan rentang poin dan tindakan sekolah.
*/
class SeedDisciplineLevelsFromPolicy extends Migration
{
public function up()
{
$db = \Config\Database::connect();
$levels = [
[
'min_score' => 1,
'max_score' => 40,
'title' => 'Level 1',
'school_action'=> "Berkomunikasi dengan orang tua/wali siswa.\nTeguran tertulis dan surat perjanjian pertama.",
'executor' => 'Wali kelas',
],
[
'min_score' => 41,
'max_score' => 70,
'title' => 'Level 2',
'school_action'=> "Memberi bimbingan dan perhatian.\nTeguran tertulis dan surat perjanjian kedua.",
'executor' => 'Wali kelas dan BK',
],
[
'min_score' => 71,
'max_score' => 99,
'title' => 'Level 3',
'school_action'=> "Berkomunikasi dengan orang tua/wali siswa.\nMemberi bimbingan dan perhatian.\nSurat perjanjian tertulis bermaterai.\nSkorsing maksimal 3 hari efektif, diketahui Kepala Sekolah.",
'executor' => 'Wali kelas, BK, wakasek kesiswaan, diketahui Kepala Sekolah',
],
[
'min_score' => 100,
'max_score' => null,
'title' => 'Level 4',
'school_action'=> "Berkomunikasi dengan orang tua/wali siswa.\nMemberi bimbingan dan perhatian.\nDikembalikan kepada orang tua secara sepihak.",
'executor' => 'Pleno guru',
],
];
foreach ($levels as $lvl) {
// Cegah duplikat berdasarkan min_score & max_score
$exists = $db->table('discipline_levels')
->where('min_score', $lvl['min_score'])
->where('max_score', $lvl['max_score'])
->countAllResults();
if ($exists > 0) {
continue;
}
$db->table('discipline_levels')->insert([
'min_score' => $lvl['min_score'],
'max_score' => $lvl['max_score'],
'title' => $lvl['title'],
'school_action'=> $lvl['school_action'],
'executor' => $lvl['executor'],
'is_active' => 1,
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
]);
}
}
public function down()
{
// Tidak menghapus data; biarkan tetap ada.
}
}

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