recreate project

This commit is contained in:
root
2026-02-10 22:11:06 -05:00
commit 663c0cdbda
10149 changed files with 1379710 additions and 0 deletions
+1247
View File
File diff suppressed because it is too large Load Diff
View File
@@ -0,0 +1,41 @@
<?php
// 2025-09-10-031001_CreateEmailTemplates.php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
use CodeIgniter\Database\RawSql;
class CreateEmailTemplates extends Migration
{
protected $DBGroup = 'default';
public function up()
{
$this->forge->addField([
'id' => ['type'=>'INT','unsigned'=>true,'auto_increment'=>true],
'template_key' => ['type'=>'VARCHAR','constraint'=>64,'null'=>false],
'name' => ['type'=>'VARCHAR','constraint'=>100,'null'=>false],
'subject' => ['type'=>'VARCHAR','constraint'=>255,'null'=>false],
'body' => ['type'=>'MEDIUMTEXT','null'=>false],
'is_active' => ['type'=>'TINYINT','constraint'=>1,'default'=>1,'null'=>false],
'created_at' => ['type'=>'DATETIME','null'=>false,'default'=>new RawSql('CURRENT_TIMESTAMP')],
'updated_at' => ['type'=>'DATETIME','null'=>false,'default'=>new RawSql('CURRENT_TIMESTAMP')],
]);
$this->forge->addKey('id', true);
$this->forge->addUniqueKey('template_key');
$this->forge->createTable('email_templates', true, [
'ENGINE'=>'InnoDB','DEFAULT CHARSET'=>'utf8mb4','COLLATE'=>'utf8mb4_unicode_ci',
]);
// Add ON UPDATE for updated_at after table creation
$this->db->query("ALTER TABLE `email_templates`
MODIFY `updated_at` DATETIME NOT NULL
DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP");
}
public function down()
{
$this->forge->dropTable('email_templates', true);
}
}
@@ -0,0 +1,47 @@
<?php
// 2025-09-10-031010_CreateFamilies.php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
use CodeIgniter\Database\RawSql;
class CreateFamilies extends Migration
{
protected $DBGroup = 'default';
public function up()
{
$this->forge->addField([
'id' => ['type'=>'INT','unsigned'=>true,'auto_increment'=>true],
'family_code' => ['type'=>'VARCHAR','constraint'=>32,'null'=>true],
'household_name' => ['type'=>'VARCHAR','constraint'=>120,'null'=>true],
'address_line1' => ['type'=>'VARCHAR','constraint'=>150,'null'=>true],
'address_line2' => ['type'=>'VARCHAR','constraint'=>150,'null'=>true],
'city' => ['type'=>'VARCHAR','constraint'=>80,'null'=>true],
'state' => ['type'=>'VARCHAR','constraint'=>40,'null'=>true],
'postal_code' => ['type'=>'VARCHAR','constraint'=>20,'null'=>true],
'country' => ['type'=>'VARCHAR','constraint'=>2,'null'=>true],
'primary_phone' => ['type'=>'VARCHAR','constraint'=>40,'null'=>true],
'preferred_lang' => ['type'=>'VARCHAR','constraint'=>10,'default'=>'en','null'=>false],
'preferred_contact_method' => ['type'=>'ENUM','constraint'=>['email','sms','phone'],'default'=>'email','null'=>false],
'is_active' => ['type'=>'TINYINT','constraint'=>1,'default'=>1,'null'=>false],
'created_at' => ['type'=>'DATETIME','null'=>false,'default'=>new RawSql('CURRENT_TIMESTAMP')],
'updated_at' => ['type'=>'DATETIME','null'=>false,'default'=>new RawSql('CURRENT_TIMESTAMP')],
]);
$this->forge->addKey('id', true);
$this->forge->addUniqueKey('family_code');
$this->forge->createTable('families', true, [
'ENGINE'=>'InnoDB','DEFAULT CHARSET'=>'utf8mb4','COLLATE'=>'utf8mb4_unicode_ci',
]);
$this->db->query("ALTER TABLE `families`
MODIFY `updated_at` DATETIME NOT NULL
DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP");
}
public function down()
{
$this->forge->dropTable('families', true);
}
}
@@ -0,0 +1,39 @@
<?php
// 2025-09-10-031020_CreateFamilyStudents.php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateFamilyStudents extends Migration
{
protected $DBGroup = 'default';
public function up()
{
if (! $this->db->tableExists('families') || ! $this->db->tableExists('students')) {
throw new \RuntimeException('CreateFamilyStudents requires families and students tables to exist.');
}
$this->forge->addField([
'id' => ['type'=>'INT','unsigned'=>true,'auto_increment'=>true],
'family_id' => ['type'=>'INT','unsigned'=>true,'null'=>false],
'student_id' => ['type'=>'INT','unsigned'=>true,'null'=>false],
'is_primary_home' => ['type'=>'TINYINT','constraint'=>1,'default'=>1],
'notes' => ['type'=>'VARCHAR','constraint'=>255,'null'=>true],
]);
$this->forge->addKey('id', true);
$this->forge->addUniqueKey(['family_id','student_id'], 'uq_family_student');
$this->forge->addKey('student_id'); // no name param
$this->forge->addForeignKey('family_id','families','id','CASCADE','CASCADE','fk_fs_family');
$this->forge->addForeignKey('student_id','students','id','CASCADE','CASCADE','fk_fs_student');
$this->forge->createTable('family_students', true, [
'ENGINE'=>'InnoDB','DEFAULT CHARSET'=>'utf8mb4','COLLATE'=>'utf8mb4_unicode_ci',
]);
}
public function down()
{
$this->forge->dropTable('family_students', true);
}
}
@@ -0,0 +1,38 @@
<?php
// 2025-09-10-031030_CreateFamilyCommPrefs.php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateFamilyCommPrefs extends Migration
{
protected $DBGroup = 'default';
public function up()
{
if (! $this->db->tableExists('families')) {
throw new \RuntimeException('CreateFamilyCommPrefs requires families table to exist.');
}
$this->forge->addField([
'id' => ['type'=>'INT','unsigned'=>true,'auto_increment'=>true],
'family_id' => ['type'=>'INT','unsigned'=>true,'null'=>false],
'category' => ['type'=>'ENUM','constraint'=>['attendance','grade','behavior','general'],'null'=>false],
'via_email' => ['type'=>'TINYINT','constraint'=>1,'default'=>1],
'via_sms' => ['type'=>'TINYINT','constraint'=>1,'default'=>0],
'cc_all_guardians' => ['type'=>'TINYINT','constraint'=>1,'default'=>1],
]);
$this->forge->addKey('id', true);
$this->forge->addUniqueKey(['family_id','category'], 'uq_family_category');
$this->forge->addForeignKey('family_id','families','id','CASCADE','CASCADE','fk_fcp_family');
$this->forge->createTable('family_comm_prefs', true, [
'ENGINE'=>'InnoDB','DEFAULT CHARSET'=>'utf8mb4','COLLATE'=>'utf8mb4_unicode_ci',
]);
}
public function down()
{
$this->forge->dropTable('family_comm_prefs', true);
}
}
@@ -0,0 +1,51 @@
<?php
// 2025-09-10-031040_CreateCommunicationLogs.php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
use CodeIgniter\Database\RawSql;
class CreateCommunicationLogs extends Migration
{
protected $DBGroup = 'default';
public function up()
{
if (! $this->db->tableExists('families')) {
throw new \RuntimeException('CreateCommunicationLogs requires families table to exist.');
}
$this->forge->addField([
'id' => ['type'=>'BIGINT','unsigned'=>true,'auto_increment'=>true],
'student_id' => ['type'=>'INT','unsigned'=>true,'null'=>false],
'family_id' => ['type'=>'INT','unsigned'=>true,'null'=>true], // SET NULL on delete
'student_name' => ['type'=>'VARCHAR','constraint'=>150,'null'=>false],
'template_key' => ['type'=>'VARCHAR','constraint'=>64,'null'=>false],
'subject' => ['type'=>'VARCHAR','constraint'=>255,'null'=>false],
'body' => ['type'=>'MEDIUMTEXT','null'=>false],
'recipients' => ['type'=>'TEXT','null'=>false],
'cc' => ['type'=>'TEXT','null'=>true],
'bcc' => ['type'=>'TEXT','null'=>true],
'attachments' => ['type'=>'TEXT','null'=>true],
'status' => ['type'=>'ENUM','constraint'=>['sent','failed'],'null'=>false],
'error_message' => ['type'=>'TEXT','null'=>true],
'sent_by' => ['type'=>'INT','unsigned'=>true,'null'=>true],
'metadata' => ['type'=>'JSON','null'=>true],
'created_at' => ['type'=>'DATETIME','null'=>false,'default'=>new RawSql('CURRENT_TIMESTAMP')],
]);
$this->forge->addKey('id', true);
$this->forge->addKey('student_id');
$this->forge->addKey('family_id');
$this->forge->addKey('template_key');
$this->forge->addForeignKey('family_id','families','id','SET NULL','CASCADE','fk_comm_family');
$this->forge->createTable('communication_logs', true, [
'ENGINE'=>'InnoDB','DEFAULT CHARSET'=>'utf8mb4','COLLATE'=>'utf8mb4_unicode_ci',
]);
}
public function down()
{
$this->forge->dropTable('communication_logs', true);
}
}
@@ -0,0 +1,97 @@
<?php
// app/Database/Migrations/2025-09-10-031050_CreateFamilyGuardians.php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class CreateFamilyGuardians extends Migration
{
protected $DBGroup = 'default';
public function up()
{
$dbName = $this->db->getDatabase();
// Find exact table names (handles Users/Families casing)
$usersRow = $this->db->query(
"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = ? AND LOWER(TABLE_NAME) = 'users' LIMIT 1",
[$dbName]
)->getFirstRow();
$familiesRow = $this->db->query(
"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = ? AND LOWER(TABLE_NAME) = 'families' LIMIT 1",
[$dbName]
)->getFirstRow();
if (!$usersRow || !$familiesRow) {
throw new \RuntimeException("Required tables not found: users or families in {$dbName}.");
}
$usersTable = $usersRow->TABLE_NAME;
$familiesTable = $familiesRow->TABLE_NAME;
// Make sure parents are InnoDB (required for FKs)
foreach ([$usersTable, $familiesTable] as $t) {
$eng = $this->db->query(
"SELECT ENGINE FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA=? AND TABLE_NAME=?",
[$dbName, $t]
)->getFirstRow();
if (!$eng || strcasecmp($eng->ENGINE ?? '', 'InnoDB') !== 0) {
$this->db->query("ALTER TABLE `{$t}` ENGINE=InnoDB");
}
}
// Match child column types to parent id types exactly
$usersIdType = $this->db->query(
"SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA=? AND TABLE_NAME=? AND COLUMN_NAME='id' LIMIT 1",
[$dbName, $usersTable]
)->getFirstRow()->COLUMN_TYPE ?? null;
$familiesIdType = $this->db->query(
"SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA=? AND TABLE_NAME=? AND COLUMN_NAME='id' LIMIT 1",
[$dbName, $familiesTable]
)->getFirstRow()->COLUMN_TYPE ?? null;
if (!$usersIdType || !$familiesIdType) {
throw new \RuntimeException("Could not read id types from {$usersTable} / {$familiesTable}.");
}
// Clean slate in case a broken table exists
$this->db->query("DROP TABLE IF EXISTS `family_guardians`");
// Create with perfectly matching FK column types
$sql = "
CREATE TABLE `family_guardians` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`family_id` {$familiesIdType} NOT NULL,
`user_id` {$usersIdType} NOT NULL,
`relation` VARCHAR(32) DEFAULT NULL,
`is_primary` TINYINT(1) DEFAULT 0,
`receive_emails` TINYINT(1) DEFAULT 1,
`receive_sms` TINYINT(1) DEFAULT 0,
`custody_notes` VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uq_family_user` (`family_id`,`user_id`),
KEY `idx_fg_family` (`family_id`),
KEY `idx_fg_user` (`user_id`),
CONSTRAINT `fk_fg_family`
FOREIGN KEY (`family_id`) REFERENCES `{$familiesTable}` (`id`)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_fg_user`
FOREIGN KEY (`user_id`) REFERENCES `{$usersTable}` (`id`)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB
DEFAULT CHARSET=utf8mb4
COLLATE=utf8mb4_unicode_ci;
";
$this->db->query($sql);
}
public function down()
{
$this->db->query("DROP TABLE IF EXISTS `family_guardians`");
}
}
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+9
View File
@@ -0,0 +1,9 @@
<?php
// In app/Config/Filters.php add the alias:
public array $aliases = [
'csrf' => \CodeIgniter\Filters\CSRF::class,
'toolbar' => \CodeIgniter\Filters\DebugToolbar::class,
'honeypot' => \CodeIgniter\Filters\Honeypot::class,
'authFilter' => \App\Filters\AuthFilter::class,
'apiDocsAuth' => \App\Filters\ApiDocsAuthFilter::class,
];
+642
View File
@@ -0,0 +1,642 @@
yes
# Implementation Documentation
## Al Rahma Sunday School Mobile App - Flutter Implementation
This document describes the complete implementation of the Al Rahma Sunday School mobile application built with Flutter for iOS and Android platforms.
---
## Project Overview
**Project Name:** Al Rahma Sunday School Mobile App
**Platform:** Flutter (iOS & Android)
**Language:** Dart
**State Management:** Provider
**API Integration:** RESTful API with JWT Authentication
**Architecture:** Service-Oriented Architecture with Provider Pattern
---
## Project Structure
```
alrahma_phone_app/
├── lib/
│ ├── core/
│ │ ├── config/
│ │ │ └── app_config.dart # App configuration and constants
│ │ ├── models/
│ │ │ ├── api_response.dart # API response wrapper models
│ │ │ └── user_model.dart # User data model
│ │ ├── providers/
│ │ │ └── auth_provider.dart # Authentication state management
│ │ ├── router/
│ │ │ └── app_router.dart # App navigation routing
│ │ ├── services/
│ │ │ ├── api_service.dart # HTTP client with JWT authentication
│ │ │ ├── auth_service.dart # Authentication business logic
│ │ │ └── storage_service.dart # Secure storage and preferences
│ │ └── theme/
│ │ └── app_theme.dart # Material Design 3 theme
│ ├── features/
│ │ ├── auth/
│ │ │ └── screens/
│ │ │ ├── login_screen.dart # Login screen with validation
│ │ │ └── register_screen.dart # Registration screen
│ │ ├── dashboard/
│ │ │ └── screens/
│ │ │ └── dashboard_screen.dart # Main dashboard with quick actions
│ │ └── splash/
│ │ └── screens/
│ │ └── splash_screen.dart # Splash/loading screen
│ └── main.dart # App entry point
├── android/ # Android platform configuration
├── ios/ # iOS platform configuration
├── assets/
│ ├── images/ # Image assets
│ └── icons/ # Icon assets
├── pubspec.yaml # Dependencies and project config
└── README.md # Project documentation
```
---
## Core Implementation
### 1. Configuration (`lib/core/config/`)
#### `app_config.dart`
- **Base URL Configuration:** API endpoint configuration
- **API Timeout Settings:** Request timeout configuration (30 seconds)
- **Token Storage Keys:** Secure storage key constants
- **App Metadata:** App name and version information
**Key Features:**
- Centralized configuration management
- Easy environment switching (dev/staging/production)
- Constants for API paths and keys
---
### 2. Services Layer (`lib/core/services/`)
#### `api_service.dart` - HTTP Client Service
**Implementation Details:**
- Built on Dio HTTP client with interceptors
- **JWT Authentication:** Automatic token injection via `Authorization: Bearer <token>` header
- **Request Interceptors:** Automatically adds authentication token and timezone headers
- **Error Interceptors:** Handles 401 unauthorized responses and clears tokens
- **Response Logging:** Pretty logging in debug mode using `pretty_dio_logger`
- **Error Handling:** Custom `ApiException` class with status codes and error messages
**Methods Implemented:**
- `get()` - GET requests with query parameters
- `post()` - POST requests with body data
- `put()` - PUT requests for updates
- `delete()` - DELETE requests
**Features:**
- Automatic token refresh handling
- Timezone support via `X-Timezone` header
- Request/response interceptors
- Comprehensive error handling
#### `storage_service.dart` - Local Storage Service
**Implementation Details:**
- **Secure Storage:** Uses `flutter_secure_storage` for sensitive data (JWT tokens)
- **Preferences Storage:** Uses `shared_preferences` for user data and settings
- **Token Management:** Secure storage for authentication tokens
- **User Data Persistence:** JSON serialization for user profile data
- **Timezone Storage:** User timezone preference storage
**Methods:**
- `saveToken()` / `getToken()` / `deleteToken()` - Token management
- `saveUserData()` / `getUserData()` / `deleteUserData()` - User data management
- `saveTimezone()` / `getTimezone()` - Timezone management
- `clearAll()` - Complete data clearing on logout
#### `auth_service.dart` - Authentication Service
**Implementation Details:**
- **Login:** Email/password authentication with JWT token retrieval
- **Registration:** New user account creation
- **Profile Management:** Get and update user profile
- **Token Management:** Automatic token storage on successful login
- **Logout:** Complete session clearing
**API Endpoints Integrated:**
- `POST /api/v1/login` - User authentication
- `POST /api/v1/register` - User registration
- `GET /api/v1/profile` - Get user profile
- `PUT /api/v1/profile` - Update user profile
**Response Handling:**
- Uses `ApiResponse<T>` wrapper for consistent response handling
- Success/error state management
- User data parsing and storage
---
### 3. Models (`lib/core/models/`)
#### `api_response.dart`
**Models:**
- `ApiResponse<T>` - Generic wrapper for API responses
- `success` (bool) - Response status
- `data` (T?) - Response data
- `message` (String?) - Response message
- `errors` (dynamic) - Validation errors
- `PaginatedResponse<T>` - Paginated list responses
- `data` (List<T>) - List of items
- `pagination` (PaginationInfo) - Pagination metadata
- `PaginationInfo` - Pagination metadata
- `currentPage`, `perPage`, `total`, `totalPages`
- Helper methods: `hasNextPage`, `hasPreviousPage`
#### `user_model.dart`
**User Model:**
- `User` class with properties:
- `id`, `firstname`, `lastname`, `name`, `email`, `cellphone`
- `roles` (UserRoles object) or `rolesList` (List<String>)
- Helper properties: `fullName`, `initials`
- Role checks: `isParent`, `isTeacher`, `isAdmin`
- `UserRoles` class:
- Boolean flags: `parent`, `teacher`, `admin`
- `LoginResponse` class:
- `token` (String) - JWT token
- `user` (User) - User information
**JSON Serialization:**
- `fromJson()` factory constructors
- `toJson()` methods for data persistence
---
### 4. State Management (`lib/core/providers/`)
#### `auth_provider.dart` - Authentication Provider
**State Variables:**
- `_user` (User?) - Current logged-in user
- `_isLoading` (bool) - Loading state indicator
- `_isAuthenticated` (bool) - Authentication status
**Methods:**
- `checkAuthStatus()` - Checks for existing authentication on app start
- `login()` - Handles login flow with state updates
- `register()` - Handles registration flow
- `logout()` - Clears authentication state
- `refreshProfile()` - Refreshes user profile data
**Features:**
- Reactive state management with `ChangeNotifier`
- Automatic state updates on authentication changes
- Loading state management for UI feedback
---
### 5. Navigation (`lib/core/router/`)
#### `app_router.dart`
**Routes Defined:**
- `/` (splash) - Splash screen
- `/login` - Login screen
- `/register` - Registration screen
- `/dashboard` - Main dashboard
**Implementation:**
- `generateRoute()` - Route generator function
- Named route navigation
- Material page transitions
---
### 6. Theme (`lib/core/theme/`)
#### `app_theme.dart`
**Theme Configuration:**
- **Material Design 3** implementation
- **Light Theme:**
- Primary color: Blue (#2196F3)
- Secondary color: Cyan (#03A9F4)
- Background: Light gray (#FAFAFA)
- **Dark Theme:**
- Primary color: Blue (#2196F3)
- Dark background: #121212
- Surface color: #1E1E1E
**Components Styled:**
- AppBar with elevation and colors
- Cards with rounded corners (12px radius)
- Elevated buttons with padding and rounded corners
- Input fields with focused states and error styling
- Consistent color scheme throughout
**Features:**
- System theme mode support (auto light/dark)
- Consistent spacing and typography
- Material 3 design language
---
## Features Implementation
### 1. Splash Screen (`lib/features/splash/screens/splash_screen.dart`)
**Functionality:**
- Displays app branding and loading indicator
- Checks authentication status on app launch
- Automatically navigates to:
- Dashboard if user is authenticated
- Login screen if not authenticated
- 2-second delay for smooth transition
**UI Elements:**
- App icon (school icon)
- App name: "Al Rahma Sunday School"
- Loading spinner
---
### 2. Authentication Screens
#### Login Screen (`lib/features/auth/screens/login_screen.dart`)
**Features:**
- Email and password input fields
- Form validation:
- Email format validation
- Required field validation
- Password visibility toggle
- Loading state during authentication
- Error handling with user-friendly messages
- Navigation to registration screen
- Automatic navigation to dashboard on success
**UI Components:**
- Material Design inputs
- Elevated button with loading state
- Error snackbar notifications
#### Registration Screen (`lib/features/auth/screens/register_screen.dart`)
**Features:**
- Complete registration form:
- First name
- Last name
- Email
- Password (with strength validation)
- Confirm password (with matching validation)
- Form validation:
- All fields required
- Email format validation
- Password minimum 8 characters
- Password confirmation matching
- Password visibility toggles
- Loading state during registration
- Success/error feedback
- Navigation back to login on success
---
### 3. Dashboard Screen (`lib/features/dashboard/screens/dashboard_screen.dart`)
**Features:**
- User profile card:
- User avatar with initials
- Full name display
- Email address
- Quick actions grid:
- Students management
- Messages
- Events
- Homework
- Payments
- Notifications
- Logout functionality
- Responsive grid layout (2 columns)
**UI Components:**
- Material cards with elevation
- Circular avatar with initials
- Icon-based action cards
- Color-coded action categories
**Future Enhancements:**
- Each quick action card is ready for navigation implementation
- Placeholder functionality for "Coming soon" features
---
## Platform Configuration
### Android Configuration
#### Files Created:
1. **`android/app/build.gradle`**
- Application ID: `com.alrahma.alrahma_app`
- Min SDK: 21 (Android 5.0)
- Target SDK: 34 (Android 14)
- Kotlin support
- Flutter integration
2. **`android/app/src/main/AndroidManifest.xml`**
- Internet permission
- Main activity configuration
- Launch configuration
- App label: "Al Rahma"
3. **`android/app/src/main/kotlin/com/alrahma/alrahma_app/MainActivity.kt`**
- Flutter activity integration
- Kotlin implementation
4. **`android/app/src/main/res/values/styles.xml`**
- Launch theme configuration
- Normal theme configuration
5. **`android/app/src/main/res/drawable/launch_background.xml`**
- Launch screen background
- App icon centering
6. **`android/build.gradle`**
- Kotlin version: 1.9.0
- Android Gradle Plugin: 8.1.0
- Repository configuration
7. **`android/settings.gradle`**
- Flutter plugin loader
- Project configuration
8. **`android/gradle.properties`**
- JVM arguments
- AndroidX enablement
- Jetifier enablement
---
### iOS Configuration
#### Files Created:
1. **`ios/Runner/Info.plist`**
- Bundle identifier: `com.alrahma.alrahmaApp`
- Display name: "Al Rahma"
- App Transport Security configuration
- Supported orientations
- Launch screen configuration
2. **`ios/Runner/AppDelegate.swift`**
- Swift implementation
- Flutter plugin registration
- Application lifecycle management
3. **`ios/Podfile`**
- iOS deployment target: 12.0
- CocoaPods configuration
- Flutter integration
- Framework settings
4. **`ios/Runner.xcodeproj/project.pbxproj`**
- Xcode project configuration
- Build settings
- Swift version: 5.0
- Debug/Release/Profile configurations
---
## Dependencies
### Core Dependencies:
- **flutter:** SDK
- **provider:** ^6.1.1 - State management
- **dio:** ^5.4.0 - HTTP client
- **pretty_dio_logger:** ^1.3.1 - Request/response logging
- **shared_preferences:** ^2.2.2 - Local preferences storage
- **flutter_secure_storage:** ^9.0.0 - Secure token storage
- **json_annotation:** ^4.8.1 - JSON serialization annotations
- **intl:** ^0.18.1 - Internationalization
- **timezone:** ^0.9.2 - Timezone handling
- **connectivity_plus:** ^5.0.2 - Network connectivity checking
### UI Dependencies:
- **cupertino_icons:** ^1.0.6 - iOS-style icons
- **flutter_svg:** ^2.0.9 - SVG image support
- **cached_network_image:** ^3.3.0 - Network image caching
### Dev Dependencies:
- **flutter_test:** Testing framework
- **flutter_lints:** ^3.0.1 - Linting rules
- **build_runner:** ^2.4.7 - Code generation
- **json_serializable:** ^6.7.1 - JSON code generation
---
## Security Features
### 1. JWT Token Management
- Secure token storage using `flutter_secure_storage`
- Automatic token injection in API requests
- Token expiration handling (401 response)
- Automatic logout on token expiration
### 2. Secure Storage
- Sensitive data (tokens) stored in secure storage
- User data stored in encrypted preferences
- Complete data clearing on logout
### 3. API Security
- HTTPS support (configured in Info.plist)
- Authorization headers for all protected requests
- Request/response validation
---
## Error Handling
### 1. API Error Handling
- Custom `ApiException` class
- HTTP status code handling:
- 400: Bad Request
- 401: Unauthorized (automatic logout)
- 403: Forbidden
- 404: Not Found
- 422: Validation Error
- 500: Server Error
- Validation error parsing
- User-friendly error messages
### 2. Network Error Handling
- Network connectivity checking
- Timeout handling (30 seconds)
- Offline state management
### 3. UI Error Feedback
- Snackbar notifications for errors
- Loading states during async operations
- Form validation feedback
---
## API Integration
### Implemented Endpoints:
1. **Authentication:**
- `POST /api/v1/login` - User login
- `POST /api/v1/register` - User registration
2. **Profile:**
- `GET /api/v1/profile` - Get user profile
- `PUT /api/v1/profile` - Update user profile
### Ready for Implementation:
Based on `API_DOCUMENTATION.md`, the following endpoints are ready to be integrated:
- Messaging system
- Students management
- Parents management
- Classes management
- Attendance tracking
- Scores & Grades
- Payments & Invoices
- Notifications
- Events & Calendar
- Dashboard data
- Homework & Assignments
- Quizzes & Exams
- And 50+ additional endpoints
---
## Code Quality
### Linting:
- Flutter lints package configured
- Analysis options with strict rules:
- Prefer const constructors
- Avoid print statements
- Prefer single quotes
- Require trailing commas
### Code Organization:
- Feature-based folder structure
- Separation of concerns (services, models, providers, UI)
- Reusable components
- Consistent naming conventions
### Best Practices:
- Null safety enabled
- Type-safe API responses
- Error handling at all levels
- Loading states for async operations
- Form validation
- Secure storage for sensitive data
---
## Testing Readiness
### Structure Ready For:
- Unit tests for services
- Widget tests for screens
- Integration tests for flows
- Provider tests for state management
### Test Files Location:
- `test/` directory (to be created)
- Service tests
- Model tests
- Provider tests
- Widget tests
---
## Build Configuration
### Android Build:
- **APK:** `flutter build apk --release`
- **App Bundle:** `flutter build appbundle --release`
- **Debug:** `flutter run`
### iOS Build:
- **IPA:** `flutter build ios --release`
- **Xcode:** Open `ios/Runner.xcworkspace`
### Environment Configuration:
- Update `lib/core/config/app_config.dart` with production API URL
- Configure signing certificates for release builds
- Update bundle identifiers if needed
---
## Next Steps / Future Enhancements
### Immediate:
1. Update API base URL in `app_config.dart`
2. Test authentication flow
3. Add remaining feature screens
4. Implement messaging system
5. Add student management features
### Short-term:
1. Implement push notifications
2. Add offline data caching
3. Implement image upload functionality
4. Add localization support
5. Implement deep linking
### Long-term:
1. Add biometric authentication
2. Implement advanced analytics
3. Add social features
4. Implement real-time updates
5. Add advanced reporting features
---
## File Summary
### Total Files Created: 30+
**Core Files:**
- 8 service/model files
- 3 provider/router/theme files
- 1 main entry point
**Feature Files:**
- 4 screen implementations
- Organized by feature modules
**Configuration Files:**
- 8 Android configuration files
- 4 iOS configuration files
- 2 asset directories
- Project configuration files
**Documentation:**
- README.md
- IMPLEMENTATION.md (this file)
- API_DOCUMENTATION.md (reference)
---
## Conclusion
A complete Flutter mobile application foundation has been implemented with:
- ✅ Complete authentication system
- ✅ Secure API integration
- ✅ Professional UI/UX
- ✅ State management
- ✅ Platform-specific configurations
- ✅ Error handling
- ✅ Security best practices
- ✅ Scalable architecture
The app is ready for feature expansion and can be built for both iOS and Android platforms.
---
**Last Updated:** 2025-01-15
**Version:** 1.0.0
**Status:** Production Ready (Foundation Complete)
+22
View File
@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2014-2019 British Columbia Institute of Technology
Copyright (c) 2019-2024 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.
+106
View File
@@ -0,0 +1,106 @@
# Current Software Architecture of `alrahma_sunday_school`
<p align="center">
<img src="/image/system_architecture.png" alt="software-architecture" width="1000"/>
</p>
# 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.1 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.
> - If you are still using PHP 7.4 or 8.0, you should upgrade immediately.
> - The end of life date for PHP 8.1 will be December 31, 2025.
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
## Slip Printer Configuration
The late-slip printer can be configured via `.env`. The controller supports both uppercase `PRINTER_*` keys and dotted `printer.*` keys.
- `PRINTER_MODE` or `printer.mode`: `network` (default), `usb`, or `windows`
- Special: `disabled`/`off`/`none` skips device printing (useful in test)
- `PRINTER_HOST` / `PRINTER_PORT` or `printer.host` / `printer.port`: Network printer TCP settings
- `PRINTER_USB_VID` / `PRINTER_USB_PID` or `printer.usb.vid` / `printer.usb.pid`: USB printer identifiers (Linux/Mac)
- `PRINTER_WINDOWS_NAME` or `printer.windows.name`: Windows printer share/port name (Windows only)
- `PRINTER_CHARS_PER_LINE` or `printer.chars_per_line`: Characters per line (80mm paper ≈ 4856)
- `PRINTER_FEED_LINES` or `printer.feed_lines`: Number of trailing blank lines before cut
Notes:
- When `PRINTER_MODE=windows` is set on a non-Windows OS, the app falls back to `network` mode.
- USB mode on Linux/Mac requires both VID and PID values.
## Testing
The PHPUnit suite expects a real database connection so it can apply migrations and seed data from `tests/_support/Database`. Tests will use the `tests` database group defined in `app/Config/Database.php`, which already points to `localhost` and the `u280815660_school` schema.
Before running `./vendor/bin/phpunit` or `php spark test`, copy `env` to `.env.testing` (or `.env`) and set the matching environment variables:
```
database.tests.hostname = localhost
database.tests.database = your_test_database
database.tests.username = your_username
database.tests.password = your_password
database.tests.DBDriver = MySQLi
database.tests.DBPrefix =
```
That ensures the `CIUnitTestCase` base class can connect, run migrations, and tear down data between tests. Once configured, run the suite with `./vendor/bin/phpunit` or `php spark test --testsuite=App` to validate the API.
+32
View File
@@ -0,0 +1,32 @@
Al Rahma Sunday School — API Docs Pack
=================================================
Generated: 2025-11-07T21:01:43.815073
WHAT'S INCLUDED
---------------
- app/Controllers/Api/*.php (API controllers)
- app/Controllers/{DocsController, ApiDocsController}
- app/Filters/ApiDocsAuthFilter.php
- app/Views/docs/{index.php, swagger_ui.php, swagger_ui_public.php}
- public/docs/openapi/*.yaml (separate specs + master.yaml)
- ROUTES_SNIPPET.php (add to app/Config/Routes.php)
- FILTERS_SNIPPET.php (add alias to app/Config/Filters.php)
INSTALL
-------
1) Unzip into your project root.
2) Merge routes:
- Open app/Config/Routes.php and paste the contents of ROUTES_SNIPPET.php
3) Add filter alias:
- Open app/Config/Filters.php and add the 'apiDocsAuth' alias from FILTERS_SNIPPET.php
4) Ensure your Models exist and match the controller expectations.
5) Set JWT secret in .env:
JWT_SECRET=your_super_secret_key
6) Visit:
- /docs (landing)
- /docs/api (secured, admin only)
- /docs/api/public (public read-only)
7) API base path:
- /api/v1/... (see YAMLs for full paths)
Enjoy!
+62
View File
@@ -0,0 +1,62 @@
<?php
// Add this group to app/Config/Routes.php
$routes->group('api/v1', ['namespace' => 'App\Controllers\Api'], static function($routes) {
// Assignments
$routes->get('assignments', 'AssignmentController::index');
$routes->post('assignments', 'AssignmentController::store');
$routes->get('assignments/(:num)', 'AssignmentController::show/$1');
$routes->put('assignments/(:num)', 'AssignmentController::update/$1');
$routes->delete('assignments/(:num)', 'AssignmentController::delete/$1');
$routes->get('assignments/student/(:num)', 'AssignmentController::student/$1');
// Attendance
$routes->get('attendance', 'AttendanceController::index');
$routes->post('attendance', 'AttendanceController::store');
$routes->get('attendance/(:num)', 'AttendanceController::show/$1');
$routes->put('attendance/(:num)', 'AttendanceController::update/$1');
$routes->delete('attendance/(:num)', 'AttendanceController::delete/$1');
$routes->get('attendance/student/(:num)', 'AttendanceController::student/$1');
// Attendance Tracking
$routes->post('attendance-tracking/record', 'AttendanceTrackingController::record');
$routes->get('attendance-tracking/violations', 'AttendanceTrackingController::violations');
$routes->get('attendance-tracking/student/(:num)', 'AttendanceTrackingController::student/$1');
// Authorized Users
$routes->get('authorized-users', 'AuthorizedUsersController::index');
$routes->post('authorized-users', 'AuthorizedUsersController::store');
$routes->get('authorized-users/(:num)', 'AuthorizedUsersController::show/$1');
$routes->delete('authorized-users/(:num)', 'AuthorizedUsersController::delete/$1');
// Broadcast Email
$routes->post('broadcast-email/send', 'BroadcastEmailController::send');
$routes->get('broadcast-email/parents', 'BroadcastEmailController::parents');
// Calendar
$routes->get('calendar', 'CalendarController::index');
$routes->post('calendar', 'CalendarController::store');
$routes->get('calendar/(:num)', 'CalendarController::show/$1');
$routes->put('calendar/(:num)', 'CalendarController::update/$1');
$routes->delete('calendar/(:num)', 'CalendarController::delete/$1');
// Classes
$routes->get('classes', 'ClassController::index');
$routes->get('classes/(:num)', 'ClassController::show/$1');
$routes->get('classes/(:num)/students', 'ClassController::students/$1');
// Class Preparation
$routes->get('class-preparation', 'ClassPreparationController::index');
$routes->get('class-preparation/(:num)', 'ClassPreparationController::show/$1');
$routes->post('class-preparation/calculate', 'ClassPreparationController::calculate');
// Communications
$routes->get('communications', 'CommunicationController::index');
$routes->post('communications/send', 'CommunicationController::send');
$routes->get('communications/conversation', 'CommunicationController::conversation');
$routes->delete('communications/(:num)', 'CommunicationController::delete/$1');
});
// API Docs routes
$routes->get('docs', 'App\Controllers\DocsController::index');
$routes->get('docs/api', 'App\Controllers\ApiDocsController::index', ['filter' => 'apiDocsAuth']);
$routes->get('docs/api/public', 'App\Controllers\ApiDocsController::public');
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
@@ -0,0 +1,46 @@
<?php
namespace App\Commands;
use App\Libraries\AttendanceAutoPublish as AutoPublishLib;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
class AttendanceAutoPublishCommand extends BaseCommand
{
protected $group = 'Attendance';
protected $name = 'attendance:auto-publish';
protected $description = 'Auto-publish attendance days per "second Sunday backward" rule.';
public function run(array $params)
{
$db = db_connect();
$zone = AutoPublishLib::tz();
$now = new \DateTimeImmutable('now', $zone);
$nowStr = $now->format('Y-m-d H:i:s');
$cutoffDate = AutoPublishLib::secondSundayBackwardDate($now);
$builder = $db->table('attendance_day');
$builder->where('status', 'submitted')
->groupStart()
->where('auto_publish_at <=', $nowStr)
->orGroupStart()
->where('auto_publish_at IS NULL', null, false)
->where('date <=', $cutoffDate)
->groupEnd()
->groupEnd();
$count = $builder->countAllResults(false); // keep the WHEREs
if ($count > 0) {
$builder->update([
'status' => 'published',
'published_by' => 0, // system
'published_at' => $nowStr,
'updated_at' => $nowStr,
]);
}
CLI::write("Auto-publish checked at {$nowStr} (TZ: {$zone->getName()}). Published rows: {$count}.");
}
}
+35
View File
@@ -0,0 +1,35 @@
<?php
namespace App\Commands;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use App\Models\UserModel;
use App\Services\NotificationService;
class CheckMissedPayments extends BaseCommand
{
protected $group = 'Payments';
protected $name = 'payments:check-missed';
protected $description = 'Checks for users who missed payments and sends reminders.';
public function run(array $params)
{
$userModel = new UserModel();
// Fetch users who missed payment (you need to implement this query)
$missedUsers = $userModel->getUsersWithMissedPayments();
foreach ($missedUsers as $user) {
NotificationService::toUser(
$user['id'],
'Payment Missed',
'You have a missed payment. Please pay to avoid penalty.',
['in_app', 'email', 'sms']
);
CLI::write("Reminder sent to {$user['email']}", 'yellow');
}
CLI::write("Finished checking missed payments.", 'green');
}
}
@@ -0,0 +1,38 @@
<?php
namespace App\Commands;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use App\Models\NotificationModel;
class CleanupExpiredNotifications extends BaseCommand
{
protected $group = 'Maintenance';
protected $name = 'notifications:cleanup';
protected $description = 'Deletes expired notifications from the database.';
public function run(array $params)
{
$model = new NotificationModel();
// Fetch expired notifications
$expired = $model->where('expires_at IS NOT NULL')
->where('expires_at < NOW()')
->findAll();
if (empty($expired)) {
CLI::write(" No expired notifications found to soft delete.", 'yellow');
return;
}
$count = 0;
foreach ($expired as $note) {
$model->delete($note['id']); // Soft delete
$count++;
}
CLI::write("✅ Soft-deleted {$count} expired notifications.", 'green');
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace App\Commands;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use App\Models\PasswordResetRequestModel;
use CodeIgniter\I18n\Time;
class CleanupPasswordResets extends BaseCommand
{
protected $group = 'Maintenance';
protected $name = 'cleanup:password-resets';
protected $description = 'Delete password reset requests older than 30 days';
public function run(array $params)
{
$model = new PasswordResetRequestModel();
$threshold = Time::now()->subDays(30)->toDateTimeString();
$count = $model->where('requested_at <', $threshold)->delete();
CLI::write("Deleted $count old password reset request(s).", 'green');
}
}
/*
Add this cron job to run every 24hrs
0 0 * * * /usr/bin/php /path/to/project/public/index.php cleanup:password-resets >> /path/to/project/writable/logs/cleanup.log 2>&1
*/
+232
View File
@@ -0,0 +1,232 @@
<?php
namespace App\Commands;
use App\Models\ConfigurationModel;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use DateTime;
use DateTimeZone;
class ConfigUpdate extends BaseCommand
{
protected $group = 'Maintenance';
protected $name = 'config:update';
protected $description = 'Run a configuration update task (weekly cron).';
protected $arguments = [];
protected $usage = 'php spark config:update [task] [--task task|-t task] [--dry] [--force] [--tz=<timezone>]';
protected $options = [
'task' => 'Task name (or pass as first positional arg)',
't' => 'Short form of --task',
'dry' => 'Dry run (no DB writes)',
'force' => 'Ignore lock and run anyway',
'tz' => 'Timezone (default: configured school timezone)',
];
/** @var ConfigurationModel */
protected $configModel;
/** Map of available task names -> handler methods. */
protected array $tasks = [
'update_date_age_reference' => 'taskUpdateDateAgeReference',
'enable_attendance_on' => 'taskEnableAttendanceOn',
'enable_attendance_off' => 'taskEnableAttendanceOff',
'set_semester_spring' => 'taskSetSemesterSpring',
'set_semester_fall' => 'taskSetSemesterFall',
];
/**
* Set enable_attendance = 1
*/
protected function taskEnableAttendanceOn(bool $dry, DateTimeZone $tz): bool
{
return $this->setConfig('enable_attendance', '1', $dry);
}
/**
* Set enable_attendance = 0
*/
protected function taskEnableAttendanceOff(bool $dry, DateTimeZone $tz): bool
{
return $this->setConfig('enable_attendance', '0', $dry);
}
protected function taskUpdateDateAgeReference(bool $dry, DateTimeZone $tz): bool
{
$now = new DateTime('now', $tz);
$isJune1 = ($now->format('n') === '6' && $now->format('j') === '1');
$forced = (CLI::getOption('force') !== null);
if (!$isJune1 && !$forced) {
CLI::write(
"Today is {$now->format('Y-m-d')} (not June 1) — skipping. Use --force to override.",
'yellow'
);
return true; // no-op, not an error
}
$year = (int) $now->format('Y');
$value = sprintf('%04d-12-31', $year);
CLI::write("Set date_age_reference = {$value}" . ($dry ? ' [DRY]' : ''), 'light_gray');
if ($dry) return true;
// Use your model method
$ok = (bool) $this->configModel->setConfigValueByKey('date_age_reference', $value);
if ($ok) {
CLI::write("date_age_reference updated to {$value}", 'green');
} else {
CLI::error("Failed to update date_age_reference");
}
return $ok;
}
protected function taskSetSemesterSpring(bool $dry, DateTimeZone $tz): bool
{
$now = new DateTime('now', $tz);
$isFeb1 = ($now->format('n') === '2' && $now->format('j') === '1');
$forced = (CLI::getOption('force') !== null);
if (!$isFeb1 && !$forced) {
CLI::write(
"Today is {$now->format('Y-m-d')} (not Feb 1) — skipping. Use --force to override.",
'yellow'
);
return true; // no-op is success
}
CLI::write("Set semester = Spring" . ($dry ? ' [DRY]' : ''), 'light_gray');
if ($dry) return true;
return (bool) $this->configModel->setConfigValueByKey('semester', 'Spring');
}
protected function taskSetSemesterFall(bool $dry, DateTimeZone $tz): bool
{
$now = new DateTime('now', $tz);
$isJun1 = ($now->format('n') === '6' && $now->format('j') === '1');
$forced = (CLI::getOption('force') !== null);
if (!$isJun1 && !$forced) {
CLI::write(
"Today is {$now->format('Y-m-d')} (not Jun 1) — skipping. Use --force to override.",
'yellow'
);
return true;
}
CLI::write("Set semester = Fall" . ($dry ? ' [DRY]' : ''), 'light_gray');
if ($dry) return true;
return (bool) $this->configModel->setConfigValueByKey('semester', 'Fall');
}
public function run(array $params)
{
$this->configModel = model(ConfigurationModel::class);
$tz = $this->getOptionString('tz', $params) ?? ((string)(config('School')->attendance['timezone'] ?? 'UTC'));
$task = $this->getOptionString('task', $params, 't');
// Fallback: first positional arg (php spark config:update enable_attendance_on)
if (!$task && !empty($params) && strpos($params[0], '-') !== 0) {
$task = trim($params[0]);
}
$dry = $this->hasFlag('dry', $params);
$force = $this->hasFlag('force', $params);
$dtz = new DateTimeZone($tz);
if ($task === '' || !isset($this->tasks[$task])) {
CLI::error('Invalid or missing --task. Available: ' . implode(', ', array_keys($this->tasks)));
return;
}
// Per-task lock
$lockFile = sys_get_temp_dir() . DIRECTORY_SEPARATOR . "ci4_config_update_{$task}.lock";
$fp = @fopen($lockFile, 'c+');
if (!$fp) {
CLI::error("Unable to open lock file: $lockFile");
return;
}
if (!$force && !flock($fp, LOCK_EX | LOCK_NB)) {
CLI::error("Task '$task' is already running (lock held). Use --force to override.");
fclose($fp);
return;
}
try {
$method = $this->tasks[$task];
CLI::write("Running task: {$task}" . ($dry ? ' [DRY RUN]' : ''), 'yellow');
$ok = $this->{$method}($dry, $dtz);
if ($ok === true) {
CLI::write("Task '{$task}' finished successfully.", 'green');
} else {
CLI::error("Task '{$task}' finished with warnings or no changes.");
}
} catch (\Throwable $e) {
CLI::error("Task '{$task}' failed: " . $e->getMessage());
} finally {
try {
flock($fp, LOCK_UN);
fclose($fp);
@unlink($lockFile);
} catch (\Throwable $e) {
}
}
}
/** Accepts --name=value, --name value, -s value, or scans $params. */
private function getOptionString(string $name, array $params, ?string $short = null): ?string
{
$v = CLI::getOption($name);
if (is_string($v) && $v !== '') return trim($v);
if ($short) {
$v = CLI::getOption($short);
if (is_string($v) && $v !== '') return trim($v);
}
foreach ($params as $i => $p) {
if (strpos($p, "--{$name}=") === 0) return trim(substr($p, strlen($name) + 3));
if ($short && strpos($p, "-{$short}=") === 0) return trim(substr($p, strlen($short) + 2));
if ($p === "--{$name}" || ($short && $p === "-{$short}")) {
return $params[$i + 1] ?? null;
}
}
return null;
}
/** True if flag present as --name or -s (no value needed). */
private function hasFlag(string $name, array $params, ?string $short = null): bool
{
if (CLI::getOption($name) !== null) return true;
if ($short && CLI::getOption($short) !== null) return true;
foreach ($params as $p) {
if ($p === "--{$name}" || ($short && $p === "-{$short}")) return true;
}
return false;
}
/* ------------------------- Helpers ------------------------- */
protected function setConfig(string $key, string $value, bool $dry): bool
{
// show current value
$current = $this->configModel->where('config_key', $key)->first()['config_value'] ?? '<NULL>';
CLI::write("{$key}: current={$current}", 'light_gray');
CLI::write("Set {$key} = {$value}" . ($dry ? ' [DRY]' : ''), 'light_gray');
if ($dry) return true;
// ✅ use your model function
$ok = (bool) $this->configModel->setConfigValueByKey($key, $value);
// read-back to verify whats persisted
$after = $this->configModel->where('config_key', $key)->first()['config_value'] ?? '<NULL>';
CLI::write("{$key}: after={$after}", $ok ? 'green' : 'red');
return $ok && ($after === $value);
}
}
+105
View File
@@ -0,0 +1,105 @@
<?php
namespace App\Commands;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use CodeIgniter\Events\Events;
use CodeIgniter\I18n\Time;
class DeleteInactiveUsers extends BaseCommand
{
protected $group = 'Maintenance';
protected $name = 'users:delete-inactive-users';
protected $description = 'Delete users that are inactive and created more than 15 minutes ago, along with their entries in the parents table and user_roles table if applicable.';
public function run(array $params)
{
$db = \Config\Database::connect();
try {
CLI::write('Running deletion of inactive users...', 'yellow');
$cutoffTime = Time::now()->subMinutes(15)->toDateTimeString();
CLI::write("Cutoff time for deletion: $cutoffTime", 'blue');
log_message('debug', 'Cutoff time for deletion: ' . $cutoffTime);
// ─────────────────────────────────────────────────────
// 1Fetch inactive users older than 15 min
// ─────────────────────────────────────────────────────
$users = $db->table('users')
->select('id, firstname, lastname, email, created_at')
->where('status', 'Inactive')
->where('created_at <', $cutoffTime)
->get()
->getResultArray();
if (empty($users)) {
CLI::write('No inactive users found to delete.', 'yellow');
$this->purgeOrphanedUserRoles($db);
return;
}
CLI::write('Found ' . count($users) . ' users for deletion.', 'green');
// collect IDs
$userIds = array_column($users, 'id');
// ─────────────────────────────────────────────────────
// 2Transaction: delete parents → user_roles → users
// ─────────────────────────────────────────────────────
$db->transStart();
// 2-a Delete any secondary-parent rows tied to these users
$parentsBuilder = $db->table('parents');
$deletedParents = $parentsBuilder->whereIn('firstparent_id', $userIds)->delete();
CLI::write("Deleted $deletedParents associated second-parent record(s).", 'blue');
log_message('info', "Deleted $deletedParents rows from parents table.");
// 2-b Delete user_roles rows
$db->table('user_roles')->whereIn('user_id', $userIds)->delete();
CLI::write('Deleted related user_roles rows.', 'blue');
// 2-c Delete users
$db->table('users')->whereIn('id', $userIds)->delete();
CLI::write('Deleted users: ' . implode(', ', $userIds), 'green');
$db->transComplete();
if (!$db->transStatus()) {
CLI::write('Transaction failed; rolled back.', 'red');
return;
}
// Purge any stray user_role rows left behind (defensive)
$this->purgeOrphanedUserRoles($db);
$msg = 'Deleted ' . count($users) . " inactive users plus $deletedParents parents rows.";
CLI::write($msg, 'green');
log_message('info', $msg);
} catch (\Throwable $e) {
CLI::write('Error deleting inactive users: ' . $e->getMessage(), 'red');
log_message('error', 'Error deleting inactive users: ' . $e->getMessage());
}
}
/**
* Remove user_roles rows that point to non-existent users.
*/
private function purgeOrphanedUserRoles(\CodeIgniter\Database\BaseConnection $db): void
{
$orphaned = $db->table('user_roles')
->whereNotIn('user_id', function ($q) use ($db) {
$q->select('id')->from('users');
})
->delete();
if ($orphaned) {
CLI::write("Deleted $orphaned orphaned user_roles rows.", 'green');
log_message('info', "Deleted $orphaned orphaned user_roles rows.");
} else {
CLI::write('No orphaned user_roles rows found.', 'yellow');
}
}
}
+93
View File
@@ -0,0 +1,93 @@
<?php
namespace App\Commands;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use Config\Database;
class RecalculateAttendance extends BaseCommand
{
protected $group = 'Attendance';
protected $name = 'attendance:recalculate-summary';
protected $description = 'Recalculates the attendance summary records (total absences, etc.) from the raw attendance data.';
public function run(array $params)
{
$db = Database::connect();
CLI::write('Starting attendance summary recalculation...', 'yellow');
// 1. Truncate the attendance_record table
try {
$db->table('attendance_record')->truncate();
CLI::write('Successfully truncated attendance_record table.', 'green');
} catch (\Throwable $e) {
CLI::error('Failed to truncate attendance_record table: ' . $e->getMessage());
return;
}
// 2. Get all attendance data
$attendanceData = $db->table('attendance_data')
->orderBy('student_id', 'ASC')
->orderBy('school_year', 'ASC')
->orderBy('semester', 'ASC')
->get()->getResultArray();
if (empty($attendanceData)) {
CLI::write('No attendance data found to process.', 'yellow');
return;
}
$summary = [];
// 3. Process the data
foreach ($attendanceData as $row) {
$studentId = $row['student_id'];
$schoolYear = $row['school_year'];
$semester = $row['semester'];
$status = strtolower($row['status']);
$key = "{$studentId}-{$schoolYear}-{$semester}";
if (!isset($summary[$key])) {
$summary[$key] = [
'student_id' => $studentId,
'school_year' => $schoolYear,
'semester' => $semester,
'class_section_id' => $row['class_section_id'],
'school_id' => $row['school_id'],
'total_presence' => 0,
'total_absence' => 0,
'total_late' => 0,
'total_attendance' => 0,
'created_at' => utc_now(),
'updated_at' => utc_now(),
];
}
$summary[$key]['total_attendance']++;
if ($status === 'present') {
$summary[$key]['total_presence']++;
} elseif ($status === 'absent') {
$summary[$key]['total_absence']++;
} elseif ($status === 'late') {
$summary[$key]['total_late']++;
}
}
// 4. Insert the new summary records
if (!empty($summary)) {
$builder = $db->table('attendance_record');
try {
$builder->insertBatch(array_values($summary));
CLI::write('Successfully inserted ' . count($summary) . ' summary records.', 'green');
} catch (\Throwable $e) {
CLI::error('Failed to insert summary records: ' . $e->getMessage());
return;
}
}
CLI::write('Attendance summary recalculation finished.', 'green');
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace App\Commands;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use App\Models\AttendanceDataModel;
use App\Models\UserModel;
use App\Services\NotificationService;
class SendAbsenteesSummary extends BaseCommand
{
protected $group = 'Attendance';
protected $name = 'attendance:absentees-summary';
protected $description = 'Sends daily attendance summaries to parents.';
public function run(array $params)
{
$attendanceModel = new AttendanceDataModel();
$userModel = new UserModel();
// Fetch todays absent records (replace with your logic)
$absentRecords = $attendanceModel->getTodayAbsentees();
foreach ($absentRecords as $record) {
// Get parent user ID
$parent = $userModel->find($record['parent_id']);
if (!$parent) continue;
NotificationService::toUser(
$parent['id'],
'Daily Attendance Update',
"{$record['student_name']} was marked absent on {$record['date']}.",
['in_app', 'email']
);
CLI::write("Sent summary to parent: {$parent['email']}", 'yellow');
}
CLI::write("Attendance summary completed.", 'green');
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace App\Commands;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use App\Models\AttendanceDataModel;
use App\Models\UserModel;
use App\Services\NotificationService;
class SendLatesSummary extends BaseCommand
{
protected $group = 'Attendance';
protected $name = 'attendance:lates-summary';
protected $description = 'Sends daily attendance summaries to parents.';
public function run(array $params)
{
$attendanceModel = new AttendanceDataModel();
$userModel = new UserModel();
// Fetch todays late records (replace with your logic)
$lateRecords = $attendanceModel->getTodayLates();
foreach ($lateRecords as $record) {
// Get parent user ID
$parent = $userModel->find($record['parent_id']);
if (!$parent) continue;
NotificationService::toUser(
$parent['id'],
'Daily Attendance Update',
"{$record['student_name']} was marked late on {$record['date']}.",
['in_app', 'email']
);
CLI::write("Sent summary to parent: {$parent['email']}", 'yellow');
}
CLI::write("Attendance summary completed.", 'green');
}
}
@@ -0,0 +1,372 @@
<?php
namespace App\Commands;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use App\Models\ConfigurationModel;
use App\Models\InvoiceModel;
use App\Models\PaymentModel;
use App\Models\PaymentNotificationLogModel;
use App\Models\UserModel;
use App\Models\UserRoleModel;
use App\Models\FamilyGuardianModel;
use App\Services\EmailService;
use App\Services\NotificationService;
class SendMonthlyPaymentNotifications extends BaseCommand
{
protected $group = 'Payments';
protected $name = 'payments:monthly-reminder';
protected $description = 'Send monthly payment reminders on the first Saturday of every month.';
protected EmailService $emailService;
protected ConfigurationModel $configModel;
protected InvoiceModel $invoiceModel;
protected PaymentModel $paymentModel;
protected PaymentNotificationLogModel $logModel;
protected UserModel $userModel;
protected FamilyGuardianModel $familyGuardianModel;
public function run(array $params)
{
// Lazy init to avoid BaseCommand constructor issues during discovery
$this->emailService = new EmailService();
$this->configModel = new ConfigurationModel();
$this->invoiceModel = new InvoiceModel();
$this->paymentModel = new PaymentModel();
$this->logModel = new PaymentNotificationLogModel();
$this->userModel = new UserModel();
$this->familyGuardianModel = new FamilyGuardianModel();
// Parse params: --force, --email=addr, --type=no_payment|installment
$force = false;
$targetEmail = null;
$targetType = null;
foreach ($params as $p) {
if ($p === '--force') { $force = true; continue; }
if (strpos($p, '--email=') === 0) { $targetEmail = trim(substr($p, 8)); continue; }
if (strpos($p, '--type=') === 0) { $targetType = trim(substr($p, 7)); continue; }
}
// Also support CI4 options parser
$optEmail = CLI::getOption('email');
if ($optEmail !== null) $targetEmail = $optEmail;
$optType = CLI::getOption('type');
if ($optType !== null) $targetType = $optType;
if (CLI::getOption('force') !== null) $force = true;
$tzName = (string) (config('School')->attendance['timezone'] ?? 'UTC');
$tz = new \DateTimeZone($tzName);
$now = new \DateTime('now', $tz);
$year = (int) $now->format('Y');
$month = (int) $now->format('n');
if (!$targetEmail && !$force && !$this->isFirstSaturday($now)) {
CLI::write('Not the first Saturday of the month. Use --force to override.', 'yellow');
return;
}
$schoolYear = (string) ($this->configModel->getConfig('school_year') ?? $year);
// Targeted test mode: only send to a specific email
if ($targetEmail) {
if (!filter_var($targetEmail, FILTER_VALIDATE_EMAIL)) {
CLI::write('Invalid --email provided', 'red');
return;
}
$userRow = $this->userModel->where('email', $targetEmail)->first();
$parentId = (int)($userRow['id'] ?? 0);
$invRows = $parentId ? $this->invoiceModel->getAllInvoicesByUserIds([$parentId], $schoolYear) : [];
$totalBalance = 0.0;
$latestInvoiceId = null;
foreach ($invRows as $ir) {
$totalBalance += (float)($ir['balance'] ?? 0);
if ($latestInvoiceId === null) {
$latestInvoiceId = (int) ($ir['id'] ?? 0);
}
}
$type = in_array($targetType, ['no_payment','installment'], true) ? $targetType : 'no_payment';
$ccEmail = $parentId ? $this->getSecondaryGuardianEmail($parentId) : null;
[$subject, $body] = $this->composeEmail($parentId ?: 0, $schoolYear, $type, $totalBalance, $now);
$sentOk = $this->emailService->send($targetEmail, $subject, $body, 'finance');
if ($sentOk && $ccEmail && strcasecmp($ccEmail, $targetEmail) !== 0) {
$this->emailService->send($ccEmail, $subject, $body, 'finance');
}
// Upsert log for this month
$existing = $this->logModel->where('parent_id', $parentId)
->where('period_year', $year)
->where('period_month', $month)
->where('type', $type)
->first();
$payload = [
'parent_id' => $parentId,
'invoice_id' => $latestInvoiceId,
'school_year' => $schoolYear,
'period_year' => $year,
'period_month' => $month,
'type' => $type,
'to_email' => $targetEmail,
'cc_email' => $ccEmail,
'head_fa_notified' => 0,
'subject' => $subject,
'body' => $body,
'status' => $sentOk ? 'sent' : 'failed',
'error_message' => $sentOk ? null : 'Email send failed (see logs)',
'balance_snapshot' => $totalBalance,
'sent_at' => $now->format('Y-m-d H:i:s'),
];
if ($existing) {
$this->logModel->update($existing['id'], $payload);
} else {
$this->logModel->insert($payload);
}
CLI::write(($sentOk ? 'Sent' : 'Failed') . " test reminder to {$targetEmail}", $sentOk ? 'green' : 'red');
return;
}
// Get all parents with invoices for the current school year
$db = \Config\Database::connect();
$rows = $db->table('invoices')
->select('parent_id')
->where('school_year', $schoolYear)
->groupBy('parent_id')
->get()
->getResultArray();
$parentIds = array_values(array_unique(array_map(static fn($r) => (int) $r['parent_id'], $rows)));
if (empty($parentIds)) {
CLI::write('No invoices found for current school year. Nothing to do.', 'yellow');
return;
}
$sentCount = 0;
foreach ($parentIds as $parentId) {
// Compute total balance across invoices for this year
$invRows = $this->invoiceModel->getAllInvoicesByUserIds([$parentId], $schoolYear);
$totalBalance = 0.0;
$latestInvoiceId = null;
foreach ($invRows as $ir) {
$totalBalance += (float)($ir['balance'] ?? 0);
if ($latestInvoiceId === null) {
$latestInvoiceId = (int) ($ir['id'] ?? 0);
}
}
if ($totalBalance <= 0.0) {
continue; // up to date
}
// Determine if parent has any payments this school year
$hasPayments = $db->table('payments')
->where('parent_id', $parentId)
->where('school_year', $schoolYear)
->countAllResults() > 0;
$type = $hasPayments ? 'installment' : 'no_payment';
// Idempotency guard: skip if already sent this period for this type
if ($this->logModel->existsForPeriod($parentId, $year, $month, $type)) {
continue;
}
// Recipient emails: primary guardian (current parent), CC second guardian in same family
$toEmail = $this->getUserEmail($parentId);
$ccEmail = $this->getSecondaryGuardianEmail($parentId);
if (!$toEmail) {
// Log failed attempt due to missing email and continue
$this->logModel->insert([
'parent_id' => $parentId,
'invoice_id' => $latestInvoiceId,
'school_year' => $schoolYear,
'period_year' => $year,
'period_month' => $month,
'type' => $type,
'to_email' => null,
'cc_email' => $ccEmail,
'subject' => 'Monthly Tuition Reminder',
'body' => null,
'status' => 'failed',
'error_message' => 'No primary email on file',
'balance_snapshot' => $totalBalance,
]);
CLI::write("Skipped parent {$parentId} due to missing email", 'yellow');
continue;
}
// Compose email
[$subject, $body] = $this->composeEmail($parentId, $schoolYear, $type, $totalBalance, $now);
$sentOk = $this->emailService->send($toEmail, $subject, $body, 'finance');
if ($sentOk && $ccEmail && strcasecmp($ccEmail, $toEmail) !== 0) {
// Send a separate copy to the secondary guardian
$this->emailService->send($ccEmail, $subject, $body, 'finance');
}
// Notify Head of Finance (in-app)
$headFaUsers = $this->getHeadOfFinanceUsers();
foreach ($headFaUsers as $u) {
NotificationService::toUser((int)$u['id'], 'Payment Reminder Sent',
sprintf('A %s reminder was sent to parent #%d (balance: $%0.2f).', $type, $parentId, $totalBalance),
['in_app']
);
}
$this->logModel->insert([
'parent_id' => $parentId,
'invoice_id' => $latestInvoiceId,
'school_year' => $schoolYear,
'period_year' => $year,
'period_month' => $month,
'type' => $type,
'to_email' => $toEmail,
'cc_email' => $ccEmail,
'head_fa_notified' => !empty($headFaUsers) ? 1 : 0,
'subject' => $subject,
'body' => $body,
'status' => $sentOk ? 'sent' : 'failed',
'error_message' => $sentOk ? null : 'Email send failed (see logs)',
'balance_snapshot' => $totalBalance,
'sent_at' => $now->format('Y-m-d H:i:s'),
]);
if ($sentOk) {
$sentCount++;
CLI::write("Reminder sent to {$toEmail}" . ($ccEmail ? ", CC {$ccEmail}" : ''), 'green');
} else {
CLI::write("Failed to send to {$toEmail}", 'red');
}
}
// Summary to head of finance (in-app broadcast)
$headFaUsers = $this->getHeadOfFinanceUsers();
foreach ($headFaUsers as $u) {
NotificationService::toUser((int)$u['id'], 'Monthly Payment Reminders Summary',
sprintf('Total reminders sent this run: %d (School Year: %s).', $sentCount, $schoolYear),
['in_app']
);
}
CLI::write("Done. Total sent: {$sentCount}", 'green');
}
private function isFirstSaturday(\DateTimeInterface $dt): bool
{
// Saturday = 6 (PHP: 0 Sun .. 6 Sat)
$isSaturday = ((int)$dt->format('w')) === 6;
$isFirstWeek = ((int)$dt->format('j')) <= 7;
return $isSaturday && $isFirstWeek;
}
private function getUserEmail(int $userId): ?string
{
$u = $this->userModel->select('email')->find($userId);
$email = $u['email'] ?? null;
return $email && filter_var($email, FILTER_VALIDATE_EMAIL) ? $email : null;
}
private function getSecondaryGuardianEmail(int $primaryGuardianUserId): ?string
{
// Find family of primary guardian
$row = $this->familyGuardianModel->where('user_id', $primaryGuardianUserId)->first();
if (!$row || empty($row['family_id'])) {
return null;
}
$familyId = (int)$row['family_id'];
$others = $this->familyGuardianModel
->where('family_id', $familyId)
->where('user_id !=', $primaryGuardianUserId)
->where('receive_emails', 1)
->findAll();
foreach ($others as $g) {
$email = $this->getUserEmail((int)$g['user_id']);
if ($email) return $email;
}
return null;
}
private function composeEmail(int $parentId, string $schoolYear, string $type, float $balance, \DateTimeInterface $now): array
{
$parent = $this->userModel->find($parentId) ?: [];
$parentName = trim(($parent['firstname'] ?? '') . ' ' . ($parent['lastname'] ?? ''));
$monthYear = $now->format('F Y');
$subject = sprintf('Monthly Tuition Reminder — %s', $schoolYear);
$greeting = $parentName !== '' ? "Dear {$parentName}," : 'Dear Parent,';
$balanceFmt = '$' . number_format($balance, 2);
if ($type === 'no_payment') {
$intro = "We noticed there are outstanding tuition charges for {$schoolYear} but no payment has been recorded yet.";
} else {
$intro = "This is your monthly installment reminder for {$schoolYear}.";
}
// Compute remaining and max installments similar to Manual Payment UI
$installmentEndRaw = (string)$this->configModel->getConfig('installment_date');
$tz = new \DateTimeZone($tzName);
$today = new \DateTimeImmutable('today', $tz);
$end = null; try { if ($installmentEndRaw) { $end = new \DateTimeImmutable($installmentEndRaw, $tz); } } catch (\Throwable $e) { $end = null; }
$remMonths = 0;
if ($end) {
$y = (int)$end->format('Y') - (int)$today->format('Y');
$m = (int)$end->format('n') - (int)$today->format('n');
$remMonths = $y * 12 + $m;
if ((int)$end->format('j') > (int)$today->format('j')) $remMonths += 1;
if ($remMonths < 0) $remMonths = 0;
}
$remainingInst = max(1, $remMonths);
$maxInst = max(($remMonths ?: 0), ($balance > 0 ? 2 : 0));
$instDueFmt = '$' . number_format($remainingInst > 0 ? ($balance / $remainingInst) : 0, 2);
$bodyHtml = <<<HTML
<div style="font-family:Arial,Helvetica,sans-serif; font-size:14px; color:#212529; line-height:1.5;">
<h2 style="margin:0 0 10px; font-size:18px;">Monthly Tuition Reminder</h2>
<p>{$greeting}</p>
<p>{$intro}</p>
<p><strong>Current Outstanding Balance:</strong> {$balanceFmt}</p>
<ul>
<li><strong>Remaining installments:</strong> {$remainingInst}</li>
<li><strong>Suggested installment this month:</strong> {$instDueFmt}</li>
<li><strong>Maximum installments available:</strong> {$maxInst}</li>
</ul>
<p>
As a friendly reminder, our tuition installments are due at the beginning of each month.
You can review your invoice and payment options by logging in to your parent portal.
</p>
<p>
If you have any questions or need to arrange a different plan, please reply to this email.
</p>
<p>Thank you for your prompt attention.</p>
<p><em>Reminder Period:</em> {$monthYear}</p>
</div>
HTML;
$body = view('emails/_wrap_layout', [
'title' => 'Monthly Tuition Reminder',
'body_html' => $bodyHtml,
], ['saveData' => true]);
return [$subject, $body];
}
private function getHeadOfFinanceUsers(): array
{
// Try the explicit role label used in the UI first
$heads = $this->userModel->getUsersByRole('head of department (finance)');
if (!empty($heads)) return $heads;
// fallback to accountant role if needed
$acct = $this->userModel->getUsersByRole('accountant');
return $acct ?: [];
}
}
@@ -0,0 +1,150 @@
<?php
namespace App\Commands;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use App\Models\ConfigurationModel;
use App\Models\InvoiceModel;
use App\Models\PaymentNotificationLogModel;
use App\Models\UserModel;
use App\Models\FamilyGuardianModel;
use App\Services\EmailService;
class SendTestPaymentNotification extends BaseCommand
{
protected $group = 'Payments';
protected $name = 'payments:send-test';
protected $description = 'Send a single test non-payment or installment reminder to a specific email.';
public function run(array $params)
{
$email = CLI::getOption('email');
$type = CLI::getOption('type') ?? 'no_payment';
if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
CLI::write('Usage: php spark payments:send-test --email=addr@example.com [--type=no_payment|installment]', 'yellow');
return;
}
$config = new ConfigurationModel();
$user = new UserModel();
$invoice= new InvoiceModel();
$logs = new PaymentNotificationLogModel();
$fam = new FamilyGuardianModel();
$mailer = new EmailService();
$tzName = (string) (config('School')->attendance['timezone'] ?? 'UTC');
$tz = new \DateTimeZone($tzName);
$now = new \DateTime('now', $tz);
$year = (int)$now->format('Y');
$month= (int)$now->format('n');
$schoolYear = (string) ($config->getConfig('school_year') ?? $year);
$userRow = $user->where('email', $email)->first();
$parentId = (int)($userRow['id'] ?? 0);
$invRows = $parentId ? $invoice->getAllInvoicesByUserIds([$parentId], $schoolYear) : [];
$totalBalance = 0.0; $latestInvoiceId = null;
foreach ($invRows as $ir) {
$totalBalance += (float)($ir['balance'] ?? 0);
if ($latestInvoiceId === null) $latestInvoiceId = (int)($ir['id'] ?? 0);
}
// Secondary guardian if available
$ccEmail = null;
if ($parentId) {
$row = $fam->where('user_id', $parentId)->first();
if ($row && !empty($row['family_id'])) {
$others = $fam->where('family_id', (int)$row['family_id'])
->where('user_id !=', $parentId)
->where('receive_emails', 1)->findAll();
foreach ($others as $g) {
$ccEmail = $user->select('email')->find((int)$g['user_id'])['email'] ?? null;
if ($ccEmail && filter_var($ccEmail, FILTER_VALIDATE_EMAIL)) break;
$ccEmail = null;
}
}
}
// Compose body (reuse layout)
$parentName = trim(($userRow['firstname'] ?? '') . ' ' . ($userRow['lastname'] ?? ''));
$monthYear = $now->format('F Y');
$subject = sprintf('Monthly Tuition Reminder — %s', $schoolYear);
$greeting = $parentName !== '' ? "Dear {$parentName}," : 'Dear Parent,';
$balanceFmt = '$' . number_format($totalBalance, 2);
$intro = ($type === 'no_payment')
? "We noticed there are outstanding tuition charges for {$schoolYear} but no payment has been recorded yet."
: "This is your monthly installment reminder for {$schoolYear}.";
$bodyHtml = <<<HTML
<div style="font-family:Arial,Helvetica,sans-serif; font-size:14px; color:#212529; line-height:1.5;">
<h2 style="margin:0 0 10px; font-size:18px;">Monthly Tuition Reminder (Test)</h2>
<p>{$greeting}</p>
<p>{$intro}</p>
<p><strong>Current Outstanding Balance:</strong> {$balanceFmt}</p>
<p>
As a friendly reminder, our tuition installments are due at the beginning of each month.
You can review your invoice and payment options by logging in to your parent portal.
</p>
<p>Thank you for your prompt attention.</p>
<p><em>Reminder Period:</em> {$monthYear}</p>
</div>
HTML;
// Compute remaining and max installments similar to Manual Payment UI
$installmentEndRaw = (string)$config->getConfig('installment_date');
$tz = new \DateTimeZone($tzName);
$today = new \DateTimeImmutable('today', $tz);
$end = null; try { if ($installmentEndRaw) { $end = new \DateTimeImmutable($installmentEndRaw, $tz); } } catch (\Throwable $e) { $end = null; }
$remMonths = 0;
if ($end) {
$y = (int)$end->format('Y') - (int)$today->format('Y');
$m = (int)$end->format('n') - (int)$today->format('n');
$remMonths = $y * 12 + $m;
if ((int)$end->format('j') > (int)$today->format('j')) $remMonths += 1;
if ($remMonths < 0) $remMonths = 0;
}
$remainingInst = max(1, $remMonths);
$maxInst = max(($remMonths ?: 0), ($totalBalance > 0 ? 2 : 0));
$instDueFmt = '$' . number_format($remainingInst > 0 ? ($totalBalance / $remainingInst) : 0, 2);
$bodyHtml .= "<ul>"
. "<li><strong>Remaining installments:</strong> {$remainingInst}</li>"
. "<li><strong>Suggested installment this month:</strong> {$instDueFmt}</li>"
. "<li><strong>Maximum installments available:</strong> {$maxInst}</li>"
. "</ul>";
$body = view('emails/_wrap_layout', [ 'title' => 'Monthly Tuition Reminder', 'body_html' => $bodyHtml ], ['saveData' => true]);
$ok = $mailer->send($email, $subject, $body, 'finance');
if ($ok && $ccEmail && strcasecmp($ccEmail, $email) !== 0) {
$mailer->send($ccEmail, $subject, $body, 'finance');
}
$existing = $logs->where('parent_id', $parentId)
->where('period_year', $year)
->where('period_month', $month)
->where('type', $type)
->first();
$payload = [
'parent_id' => $parentId,
'invoice_id' => $latestInvoiceId,
'school_year' => $schoolYear,
'period_year' => $year,
'period_month' => $month,
'type' => $type,
'to_email' => $email,
'cc_email' => $ccEmail,
'head_fa_notified' => 0,
'subject' => $subject,
'body' => $body,
'status' => $ok ? 'sent' : 'failed',
'error_message' => $ok ? null : 'Email send failed (see logs)',
'balance_snapshot' => $totalBalance,
'sent_at' => $now->format('Y-m-d H:i:s'),
];
if ($existing) $logs->update($existing['id'], $payload); else $logs->insert($payload);
CLI::write(($ok ? 'Sent' : 'Failed') . " test reminder to {$email}", $ok ? 'green' : 'red');
}
}
+232
View File
@@ -0,0 +1,232 @@
<?php
namespace App\Commands;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use App\Models\PayPalPaymentModel;
use App\Models\PaymentModel;
use App\Models\UserModel;
use App\Models\ConfigurationModel;
use App\Models\InvoiceModel;
use App\Models\StudentModel;
use App\Models\EnrollmentModel;
class SyncPaypalPayments extends BaseCommand
{
protected $group = 'Payments';
protected $name = 'payments:sync-paypal';
protected $description = 'Sync PayPal payments to internal payments table from paypal_payments';
protected $configModel;
protected $semester;
protected $schoolYear;
protected $paypalModel;
protected $paymentModel;
protected $userModel;
protected $invoiceModel;
protected $studentModel;
protected $enrollmentModel;
public function __construct()
{
$this->configModel = new ConfigurationModel();
$this->paypalModel = new PayPalPaymentModel();
$this->paymentModel = new PaymentModel();
$this->userModel = new UserModel();
$this->invoiceModel = new InvoiceModel();
$this->studentModel = new StudentModel();
$this->enrollmentModel = new EnrollmentModel();
$this->semester = $this->configModel->getConfig('semester');
$this->schoolYear = $this->configModel->getConfig('school_year');
}
public function run(array $params)
{
$dryRun = CLI::getOption('dry-run');
$reportOnly = CLI::getOption('report-only');
$mode = $reportOnly ? 'REPORT-ONLY' : ($dryRun ? 'DRY-RUN' : 'LIVE');
$paypalEntries = $this->paypalModel
->where('status', 'COMPLETED')
->where('synced', 0)
->where('sync_attempts <', 3)
->where('transaction_id IS NOT NULL')
->findAll();
$syncedCount = 0;
$failed = [];
foreach ($paypalEntries as $entry) {
$parentId = null;
$invoiceId = 0;
$users = $this->userModel->getUsersBySchoolId($entry['parent_school_id']);
$user = $users[0] ?? null;
// Always increment sync_attempts unless report-only
if (!$reportOnly) {
$this->paypalModel->update($entry['id'], [
'sync_attempts' => $entry['sync_attempts'] + 1
]);
}
if ($user) {
$parentId = $user['id'];
$invoice = $this->invoiceModel->getInvoicesByParentId($parentId, $this->schoolYear);
if (!$reportOnly && !$dryRun) {
if ($invoice) {
$invoiceId = $invoice['id'];
$success = $this->processPayment(
$invoiceId,
$entry['amount'],
'PayPal',
null,
$entry['transaction_id'],
date('Y-m-d', strtotime($entry['created_at'])),
$this->schoolYear,
$this->semester
);
if (!$success) {
$failed[] = $entry['transaction_id'];
continue;
}
} else {
$this->paymentModel->insert([
'parent_id' => $parentId,
'invoice_id' => 0,
'total_amount' => $entry['amount'],
'paid_amount' => $entry['amount'],
'balance' => 0.00,
'number_of_installments' => 1,
'transaction_id' => $entry['transaction_id'],
'payment_method' => 'PayPal',
'payment_date' => date('Y-m-d', strtotime($entry['created_at'])),
'school_year' => $this->schoolYear,
'semester' => $this->semester,
'status' => 'Completed',
'updated_by' => null,
]);
}
// Mark as synced only in LIVE mode
$this->paypalModel->update($entry['id'], ['synced' => 1]);
}
$syncedCount++;
} else {
log_message('error', "[PAYPAL SYNC FAILED] No user found for parent_school_id: {$entry['parent_school_id']}");
$failed[] = $entry['transaction_id'];
}
}
// === Logging ===
log_message('info', "[$mode] PAYPAL SYNC: $syncedCount processed.");
if (!empty($failed)) {
log_message('error', "[$mode] PAYPAL SYNC Failed: " . implode(', ', $failed));
}
// === CLI Output ===
CLI::write("[$mode] $syncedCount PayPal payments processed.", 'green');
if (!empty($failed)) {
CLI::error("[$mode] Failed transactions: " . implode(', ', $failed));
}
// === Email Report: Only if there's any update ===
if ($syncedCount > 0 || !empty($failed)) {
helper('email');
$email = \Config\Services::email();
$email->setTo('support@alrahmaisgl.org');
$email->setFrom('no-parentsreply@alrahmaisgl.org', 'PayPal Sync Report');
$email->setSubject("[$mode] PayPal Sync Report - " . date('Y-m-d H:i'));
$body = "PayPal Sync Mode: $mode\n\n";
$body .= "$syncedCount PayPal payments processed.\n\n";
if (!empty($failed)) {
$body .= count($failed) . " failed transactions:\n";
$body .= implode("\n", $failed);
} else {
$body .= "No failed transactions.\n";
}
$email->setMessage(nl2br($body));
if ($email->send()) {
CLI::write("[$mode] Email report sent successfully.", 'yellow');
} else {
CLI::error("[$mode] Failed to send email report.");
log_message('error', 'Email send error: ' . $email->printDebugger(['headers']));
}
} else {
log_message('info', "[$mode] No PayPal sync updates. Email not sent.");
CLI::write("[$mode] No changes to report. Email not sent.", 'blue');
}
}
private function processPayment($invoiceId, $amount, $paymentMethod, $checkFile = null, $transactionId = null, $paymentDate = null, $schoolYear = null, $semester = null)
{
$invoice = $this->invoiceModel->find($invoiceId);
if (!$invoice) {
return false;
}
$transactionId = $transactionId ?? 'INV-' . $invoiceId . '-' . time();
$paymentDate = $paymentDate ?? date('Y-m-d');
$newPaid = $invoice['paid_amount'] + $amount;
$newBalance = $invoice['balance'] - $amount;
$invoiceUpdateData = [
'paid_amount' => $newPaid,
'balance' => $newBalance,
'status' => ($newBalance <= 0) ? 'Paid' : $invoice['status'],
];
if (!$this->invoiceModel->update($invoiceId, $invoiceUpdateData)) {
return false;
}
$this->paymentModel->insert([
'parent_id' => $invoice['parent_id'],
'invoice_id' => $invoiceId,
'total_amount' => $invoice['total_amount'],
'paid_amount' => $amount,
'balance' => $newBalance,
'number_of_installments' => 1,
'transaction_id' => $transactionId,
'payment_method' => $paymentMethod,
'payment_date' => $paymentDate,
'status' => ($newBalance <= 0) ? 'Full' : 'Partial',
'check_file' => $checkFile,
'updated_by' => null, // Avoid using session()->get() in CLI
'school_year' => $schoolYear,
'semester' => $semester
]);
$this->updateEnrollmentStatusIfPaid($invoiceId, $schoolYear);
return true;
}
private function updateEnrollmentStatusIfPaid($invoiceId, $schoolYear)
{
$invoice = $this->invoiceModel->find($invoiceId);
if (!$invoice || $invoice['balance'] > 0) {
return;
}
$students = $this->studentModel->where('parent_id', $invoice['parent_id'])
->where('school_year', $schoolYear)
->findAll();
foreach ($students as $student) {
$this->enrollmentModel->set(['enrollment_status' => 'enrolled'])
->where('student_id', $student['id'])
->update();
}
}
}
+15
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
*/
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Api extends BaseConfig
{
public string $baseURL;
public int $timeout;
public array $defaultHeaders;
public function __construct()
{
parent::__construct();
$this->baseURL = rtrim((string) env('API_BASE_URL', ''), '/');
$this->timeout = (int) env('API_TIMEOUT', 10);
$this->defaultHeaders = [
'Accept' => 'application/json',
];
$token = env('API_BEARER_TOKEN');
if ($token) {
$this->defaultHeaders['Authorization'] = 'Bearer ' . $token;
}
}
}
?>
+218
View File
@@ -0,0 +1,218 @@
<?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., https://test.alrahmaisgl.org/
*/
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 'https://test.alrahmaisgl.org/', 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 = '';
/**
* --------------------------------------------------------------------------
* 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;
public $sessionDriver = 'CodeIgniter\Session\Handlers\DatabaseHandler';
public $sessionSavePath = 'ci_sessions';
// app/Config/App.php
public string $cookiePrefix = '__Host-'; // applies to all cookies set via CI Cookie helper
public string $cookieDomain = ''; // REQUIRED (no Domain for __Host-)
public string $cookiePath = '/';
public bool $cookieSecure = true;
public string $cookieSameSite = 'Lax'; // you can keep Lax; Strict may break some flows
// Sessions (also in App.php)
public string $sessionCookieName = '__Host-ci_session';
public bool $sessionRegenerateDestroy = true;
}
+103
View File
@@ -0,0 +1,103 @@
<?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.
*
* @immutable
*/
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 '/app' and '/system' directories 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.
*
* Prototype:
* $psr4 = [
* 'CodeIgniter' => SYSTEMPATH,
* 'App' => APPPATH
* ];
*
* @var array<string, list<string>|string>
*/
public $psr4 = [
'App' => APPPATH, // To ensure your App namespace is correctly set
APP_NAMESPACE => APPPATH, // For custom app namespace
'Config' => APPPATH . 'Config',
];
/**
* -------------------------------------------------------------------
* 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 = ['url', 'form', 'pbkdf2', 'document', 'time', 'api'];
}
+35
View File
@@ -0,0 +1,35 @@
<?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);
error_reporting(-1);
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);
+23
View File
@@ -0,0 +1,23 @@
<?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.
*/
ini_set('display_errors', '0');
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED);
/*
|--------------------------------------------------------------------------
| 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);
+38
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);
+20
View File
@@ -0,0 +1,20 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class CURLRequest extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* 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;
}
+171
View File
@@ -0,0 +1,171 @@
<?php
namespace Config;
use CodeIgniter\Cache\CacheInterface;
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';
/**
* --------------------------------------------------------------------------
* Cache Directory Path
* --------------------------------------------------------------------------
*
* The path to where cache files should be stored, if using a file-based
* system.
*
* @deprecated Use the driver-specific variant under $file
*/
public string $storePath = WRITEPATH . 'cache/';
/**
* --------------------------------------------------------------------------
* 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;
/**
* --------------------------------------------------------------------------
* 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<string, int|string|null>
*/
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<string, bool|int|string>
*/
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<string, int|string|null>
*/
public array $redis = [
'host' => '127.0.0.1',
'password' => null,
'port' => 6379,
'timeout' => 0,
'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 = [
'dummy' => DummyHandler::class,
'file' => FileHandler::class,
'memcached' => MemcachedHandler::class,
'predis' => PredisHandler::class,
'redis' => RedisHandler::class,
'wincache' => WincacheHandler::class,
];
}
+33
View File
@@ -0,0 +1,33 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseService;
class Commands extends BaseService
{
public static function init()
{
// Register all custom commands
$commands = [
\App\Commands\AttendanceAutoPublishCommand::class,
\App\Commands\CheckMissedPayments::class,
\App\Commands\CleanupExpiredNotifications::class,
\App\Commands\CleanupPasswordResets::class,
\App\Commands\ConfigUpdate::class,
\App\Commands\DeleteInactiveUsers::class,
\App\Commands\SendAbsenteesSummary::class,
\App\Commands\SendLatesSummary::class,
\App\Commands\SendMonthlyPaymentNotifications::class,
\App\Commands\SendTestPaymentNotification::class,
\App\Commands\SyncPaypalPayments::class,
\App\Commands\RecalculateAttendance::class,
];
foreach ($commands as $command) {
if (class_exists($command)) {
\CodeIgniter\CLI\Commands::addCommand(new $command());
}
}
}
}
+94
View File
@@ -0,0 +1,94 @@
<?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
/**
* @deprecated Use \CodeIgniter\Events\Events::PRIORITY_LOW instead.
*/
define('EVENT_PRIORITY_LOW', 200);
/**
* @deprecated Use \CodeIgniter\Events\Events::PRIORITY_NORMAL instead.
*/
define('EVENT_PRIORITY_NORMAL', 100);
/**
* @deprecated Use \CodeIgniter\Events\Events::PRIORITY_HIGH instead.
*/
define('EVENT_PRIORITY_HIGH', 10);
+176
View File
@@ -0,0 +1,176 @@
<?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;
/**
* 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;
// -------------------------------------------------------------------------
// Sources allowed
// 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';
/**
* Lists allowed stylesheets' URLs.
*
* @var list<string>|string
*/
public $styleSrc = '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;
/**
* 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 tag for style
*/
public string $styleNonceTag = '{csp-style-nonce}';
/**
* Nonce tag for script
*/
public string $scriptNonceTag = '{csp-script-nonce}';
/**
* Replace nonce tag automatically
*/
public bool $autoNonce = true;
}
+107
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.
*
* @phpstan-var 'None'|'Lax'|'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
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 apps
/**
* 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' => true, // Enable for mobile apps using cookies/auth
/**
* 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', 'Accept', 'X-Requested-With', 'X-Timezone'],
/**
* 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', 'PATCH', 'OPTIONS'],
/**
* 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,
];
}
+51
View File
@@ -0,0 +1,51 @@
<?php
namespace Config;
use CodeIgniter\Database\Config;
class Database extends Config
{
public string $filesPath = APPPATH . 'Database' . DIRECTORY_SEPARATOR;
public string $defaultGroup = 'default';
public array $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => 'u280815660_melabidi',
'password' => '>tNxlRzP/W8',
'database' => 'u280815660_school',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => (ENVIRONMENT !== 'development'),
'charset' => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
];
public array $tests = [
'DSN' => '',
'hostname' => 'localhost',
'username' => 'u280815660_melabidi',
'password' => '>tNxlRzP/W8',
'database' => 'u280815660_school',
'DBDriver' => 'MySQLi',
'DBPrefix' => 'db_',
'pConnect' => false,
'DBDebug' => true,
'charset' => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
];
}
+46
View File
@@ -0,0 +1,46 @@
<?php
namespace Config;
/**
* @immutable
*/
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;
}
+26
View File
@@ -0,0 +1,26 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Email extends BaseConfig
{
public string $protocol = 'smtp';
public string $SMTPHost = 'smtp.gmail.com';
public string $SMTPUser = 'alrahma.sunday.school@gmail.com';
public string $SMTPPass = 'psnp emdq dykw ypul'; // Consider using ENV()
public int $SMTPPort = 465;
public string $SMTPCrypto = 'ssl'; // ✅ Correct for port 465
public bool $SMTPAuth = true;
public int $SMTPTimeout = 5;
public bool $SMTPKeepAlive = true;
public string $charset = 'UTF-8';
public string $mailType = 'html';
public bool $wordWrap = true;
public string $newline = "\r\n";
public string $CRLF = "\r\n";
}
+92
View File
@@ -0,0 +1,92 @@
<?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 = '';
/**
* --------------------------------------------------------------------------
* 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';
}
+123
View File
@@ -0,0 +1,123 @@
<?php
namespace Config;
use CodeIgniter\Events\Events;
use CodeIgniter\Exceptions\FrameworkException;
use CodeIgniter\HotReloader\HotReloader;
use App\Listeners\SchoolEventListener;
use App\Listeners\AttendanceConsequenceListener;
use App\Listeners\WhatsappInviteListener;
use App\Listeners\BelowSixtyEmailListener;
// Create an instance so we can use $this->emailService like your other handlers
$waListener = new WhatsappInviteListener(service('emailService'));
$listener = new SchoolEventListener();
/*
* --------------------------------------------------------------------
* 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 () {
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');
Services::toolbar()->respond();
// Hot Reload route - for framework use on the hot reloader.
if (ENVIRONMENT === 'development') {
Services::routes()->get('__hot-reload', static function () {
(new HotReloader())->run();
});
}
}
});
// Register the delete unverified user event
Events::on('delete_unverified_user', function ($user) {
(new SchoolEventListener())->handleDeleteUnverifiedUser($user);
});
// User Events
Events::on('userRegistered', [$listener, 'handleStudentRegistered']);
Events::on('userProfileUpdated', [$listener, 'handleUserProfileUpdated']);
Events::on('userDeactivated', [$listener, 'handleUserDeactivated']);
// Students enrollment Events
Events::on('studentRegistered', [$listener, 'handleStudentRegistered']);
Events::on('admissionUnderReview', [$listener, 'handleAdmissionUnderReview']);
Events::on('paymentPending', [$listener, 'handlePaymentPending']);
Events::on('studentEnrolled', [$listener, 'handleStudentEnrolled']);
Events::on('withdrawUnderReview', [$listener, 'handleWithdrawUnderReview']);
Events::on('refundPending', [$listener, 'handleRefundPending']);
Events::on('withdrawn', [$listener, 'handleWithdrawn']);
Events::on('waitlist', [$listener, 'handleWaitlist']);
Events::on('denied', [$listener, 'handleDenied']);
// Score Events
Events::on('scoresPosted', [$listener, 'handleScoresPosted']);
Events::on('finalScoreReleased', [$listener, 'handleFinalScoreReleased']);
// Attendance Events
Events::on('studentMarkedAbsent', [$listener, 'handleStudentMarkedAbsent']);
// Payment Events
Events::on('paymentReceived', [$listener, 'handlePaymentReceived']);
Events::on('paymentMissed', [$listener, 'handlePaymentMissed']);
// Schedule and Messaging
Events::on('classScheduleUpdated', [$listener, 'handleClassScheduleUpdated']);
Events::on('newMessageReceived', [$listener, 'handleNewMessageReceived']);
Events::on('systemAnnouncementPosted', [$listener, 'handleSystemAnnouncementPosted']);
// Account registration
Events::on('user_registered', [$listener, 'handleNewAccountAdded']);
//Custom Notification
Events::on('customNotification', [$listener, 'handleCustomNotification']);
//Extra charge
Events::on('extraCharge', [$listener, 'handleExtraCharge']);
Events::on('attendance.follow_up', [AttendanceConsequenceListener::class, 'followUp']);
Events::on('attendance.final_warning', [AttendanceConsequenceListener::class, 'finalWarning']);
Events::on('attendance.dismissal', [AttendanceConsequenceListener::class, 'dismissal']);
Events::on('below60.email', [BelowSixtyEmailListener::class, 'handle']);
//Whatsapp Event listener
Events::on('whatsapp_invites.send', [$waListener, 'handle']);
+108
View File
@@ -0,0 +1,108 @@
<?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 = [];
/**
* --------------------------------------------------------------------------
* LOG DEPRECATIONS INSTEAD OF THROWING?
* --------------------------------------------------------------------------
* By default, CodeIgniter converts deprecations into exceptions. Also,
* starting in PHP 8.1 will cause a lot of deprecated usage warnings.
* Use this option to temporarily cease the warnings and instead log those.
* 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);
}
}
+30
View File
@@ -0,0 +1,30 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Enable/disable backward compatibility breaking features.
*/
class Feature extends BaseConfig
{
/**
* Enable multiple filters for a route or not.
*
* If you enable this:
* - CodeIgniter\CodeIgniter::handleRequest() uses:
* - CodeIgniter\Filters\Filters::enableFilters(), instead of enableFilter()
* - CodeIgniter\CodeIgniter::tryToRouteIt() uses:
* - CodeIgniter\Router\Router::getFilters(), instead of getFilter()
* - CodeIgniter\Router\Router::handle() uses:
* - property $filtersInfo, instead of $filterInfo
* - CodeIgniter\Router\RouteCollection::getFiltersForRoute(), instead of getFilterForRoute()
*/
public bool $multipleFilters = false;
/**
* Use improved new auto routing instead of the default legacy version.
*/
public bool $autoRoutesImproved = false;
}
+118
View File
@@ -0,0 +1,118 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Filters\CSRF;
use CodeIgniter\Filters\DebugToolbar;
use CodeIgniter\Filters\Honeypot;
use CodeIgniter\Filters\InvalidChars;
use CodeIgniter\Filters\SecureHeaders;
class Filters extends BaseConfig
{
/**
* 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,
'auth' => \App\Filters\AuthFilter::class, // Define the alias for your auth filter
'apiAuth' => \App\Filters\ApiAuthFilter::class, // JWT-based API authentication
'cleanupScheduler' => \App\Filters\CleanupScheduler::class,
'permission' => \App\Filters\PermissionFilter::class,
'timezone' => \App\Filters\TimezoneFilter::class,
];
/**
* List of filter aliases that are always
* applied before and after every request.
*
* @var array<string, array<string, array<string, string>>>|array<string, list<string>>
*/
public array $globals = [
'before' => [
'timezone',
'csrf' => ['except' => [
// Webhooks / integrations
'api/paypal-webhook',
'index.php/api/paypal-webhook',
// WhatsApp membership management (legacy allowances retained)
'whatsapp/update-membership',
'index.php/whatsapp/update-membership',
// Attendance management AJAX saves
'attendance/update',
'index.php/attendance/update',
// Late slip preview/print from admin attendance page
'slips/preview',
'index.php/slips/preview',
'slips/print',
'index.php/slips/print',
// ✅ Parent attendance AJAX conflict check (added)
'api/parent/report-attendance/check',
'index.php/api/parent/report-attendance/check',
// API auth endpoints (no CSRF)
'api/login',
'index.php/api/login',
'api/register',
'index.php/api/register',
// API routes (no CSRF, handled by JWT)
'api/*',
'index.php/api/*',
// Badge PDF generation posts (handled by auth; allow multiple submits without reload)
'badge',
'index.php/badge',
]],
],
'after' => [
'toolbar',
'cleanupScheduler' => ['except' => ['cleanup/*']],
],
];
/**
* 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 = [
];
}
+12
View File
@@ -0,0 +1,12 @@
<?php
namespace Config;
use CodeIgniter\Config\ForeignCharacters as BaseForeignCharacters;
/**
* @immutable
*/
class ForeignCharacters extends BaseForeignCharacters
{
}
+77
View File
@@ -0,0 +1,77 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Format\FormatterInterface;
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,
];
/**
* A Factory method to return the appropriate formatter for the given mime type.
*
* @return FormatterInterface
*
* @deprecated This is an alias of `\CodeIgniter\Format\Format::getFormatter`. Use that instead.
*/
public function getFormatter(string $mime)
{
return Services::format()->getFormatter($mime);
}
}
+42
View File
@@ -0,0 +1,42 @@
<?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, string>
*/
public array $views = [
'make:cell' => 'CodeIgniter\Commands\Generators\Views\cell.tpl.php',
'make:cell_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
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';
}
+31
View File
@@ -0,0 +1,31 @@
<?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.
*/
public string $libraryPath = '/usr/local/bin/convert';
/**
* The available handler classes.
*
* @var array<string, string>
*/
public array $handlers = [
'gd' => GDHandler::class,
'imagick' => ImageMagickHandler::class,
];
}
+71
View File
@@ -0,0 +1,71 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use Kint\Parser\ConstructablePluginInterface;
use Kint\Renderer\AbstractRenderer;
use Kint\Renderer\Rich\TabPluginInterface;
use Kint\Renderer\Rich\ValuePluginInterface;
class Kint extends BaseConfig
{
/**
* Optional custom parser plugins.
*
* @var list<class-string<ConstructablePluginInterface>|ConstructablePluginInterface>|null
*/
public ?array $plugins = null;
/**
* Maximum depth for rendering arrays/objects.
*/
public int $maxDepth = 6;
/**
* Whether to show where the dump was called from.
*/
public bool $displayCalledFrom = true;
/**
* Expand all dump trees by default.
*/
public bool $expanded = false;
/**
* CSS theme for RichRenderer (web output).
*/
public string $richTheme = 'aante-light.css';
/**
* Whether to load the rich folder with Kint assets.
*/
public bool $richFolder = false;
/**
* Enable Kint debugging system-wide.
*
* Set to false for production.
*/
public bool $enabled = false;
/**
* Enable CLI color output (ANSI).
*/
public bool $cliColors = true;
/**
* Force UTF-8 output in CLI.
*/
public bool $cliForceUTF8 = true;
/**
* Let Kint auto-detect the terminal width.
*/
public bool $cliDetectWidth = true;
/**
* Minimum width (in characters) for CLI output.
*/
public int $cliMinWidth = 40;
}
+151
View File
@@ -0,0 +1,151 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Log\Handlers\FileHandler;
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;
public $threshold = 4;
/**
* --------------------------------------------------------------------------
* 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, 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,
// ],
];
}
+50
View File
@@ -0,0 +1,50 @@
<?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_';
}
+536
View File
@@ -0,0 +1,536 @@
<?php
namespace Config;
/**
* Mimes
*
* 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.
*
* @immutable
*/
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',
],
];
/**
* 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;
}
}
+84
View File
@@ -0,0 +1,84 @@
<?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.
*
* @immutable
*/
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
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.
*
* @immutable
*/
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;
}
+39
View File
@@ -0,0 +1,39 @@
<?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',
'custom_pagination' => 'App\Views\pagination\custom_pagination', // Register custom template
];
/**
* --------------------------------------------------------------------------
* Items Per Page
* --------------------------------------------------------------------------
*
* The default number of results shown in a single page.
*/
public int $perPage = 20;
}
+75
View File
@@ -0,0 +1,75 @@
<?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.
*/
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';
}
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class PaypalConfig extends BaseConfig
{
// PayPal API Credentials
public $paypalClientId = 'YOUR_PAYPAL_CLIENT_ID';
public $paypalSecret = 'YOUR_PAYPAL_SECRET';
public $paypalMode = 'sandbox'; // Change to 'live' when moving to production
}
+28
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',
];
}
+17
View File
@@ -0,0 +1,17 @@
<?php
namespace App\Config;
use CodeIgniter\Config\BaseConfig;
class Roles extends BaseConfig
{
/** Default roles (lowercase) used if a roles table is not available */
public array $roles = [
'administrator', 'principal', 'vice_principal', 'admin',
'head of department (communication)',
'head of department (information technology)',
'head of department (education)'
];
}
File diff suppressed because it is too large Load Diff
+114
View File
@@ -0,0 +1,114 @@
<?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
{
/**
* 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',
];
/**
* The default namespace to use for Controllers when no other
* namespace has been specified.
*
* Default: 'App\Controllers'
*/
public string $defaultNamespace = 'App\Controllers';
/**
* The default controller to use when no other controller has been
* specified.
*
* Default: 'Home'
*/
public string $defaultController = 'Home';
/**
* The default method to call on the controller when no other
* method has been set in the route.
*
* Default: 'index'
*/
public string $defaultMethod = 'index';
/**
* Whether to translate dashes in URIs 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, will enable the use of the 'prioritize' option
* when defining routes.
*
* Default: false
*/
public bool $prioritize = false;
/**
* Map of URI segments and namespaces. For Auto Routing (Improved).
*
* 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 = [];
}
+23
View File
@@ -0,0 +1,23 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class School extends BaseConfig
{
/**
* Attendance-related settings.
* Access via: config('School')->attendance['timezone']
*/
public array $attendance = [
// School-local timezone used for auto-publish calculations
'timezone' => 'America/New_York',
// Strategy label (for reference; your code uses the helper library)
'autopublish_strategy' => 'second_sunday_after',
// Optional toggles you might use later:
// 'require_reason_on_reopen' => true,
];
}
+105
View File
@@ -0,0 +1,105 @@
<?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.
*/
public bool $redirect = true;
/**
* --------------------------------------------------------------------------
* CSRF SameSite
* --------------------------------------------------------------------------
*
* Setting for CSRF SameSite cookie token.
*
* Allowed values are: None - Lax - Strict - ''.
*
* Defaults to `Lax` as recommended in this link:
*
* @see https://portswigger.net/web-security/csrf/samesite-cookies
*
* @deprecated `Config\Cookie` $samesite property is used.
*/
public string $samesite = 'Lax';
// app/Config/Security.php
public string $csrfCookieName = '__Host-csrf';
}
+183
View File
@@ -0,0 +1,183 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseService;
use App\Services\SemesterScoreService;
use App\Models\SemesterScoreModel;
use App\Models\ConfigurationModel;
use App\Services\Calculators\HomeworkCalculator;
use App\Services\Calculators\QuizCalculator;
use App\Services\Calculators\ProjectCalculator;
use App\Services\Calculators\AttendanceCalculator;
use App\Models\HomeworkModel;
use App\Models\QuizModel;
use App\Models\ProjectModel;
use App\Models\AttendanceRecordModel;
use App\Models\CalendarModel;
use PHPMailer\PHPMailer\PHPMailer;
/**
* 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
{
/**
* Override CI Email service to enforce a global Reply-To.
*/
public static function email(array $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('email', $config);
}
$config = $config ?? config('Email');
$email = new \CodeIgniter\Email\Email($config);
try {
$rtEmail = env('MAIL_DEFAULT_REPLY_TO');
$rtNameRaw = env('MAIL_DEFAULT_REPLY_TO_NAME');
$rtName = 'Al Rahma Sunday School';
if (is_string($rtNameRaw)) {
$rtNameRaw = trim($rtNameRaw);
if ($rtNameRaw !== '' && !preg_match('/^no[- ]?repl(?:y|ay)$/i', $rtNameRaw)) {
$rtName = $rtNameRaw;
}
}
if ($rtEmail) {
$email->setReplyTo($rtEmail, $rtName);
}
} catch (\Throwable $e) {
// Ignore; ensure service is still usable even if headers not yet setable
}
return $email;
}
public static function PHPMailer(bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('PHPMailer');
}
$mail = new PHPMailer(true);
// Set up your PHPMailer configuration
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com'; // Your SMTP host
$mail->SMTPAuth = true;
$mail->Username = 'alrahma.sunday.school@gmail.com'; // Your email
$mail->Password = 'psnp emdq dykw ypul'; // Your email password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail->Port = 465;
$mail->Timeout = 10; // ⏱ 10-second timeout max
$mail->SMTPKeepAlive = false; // Prevent hanging connections
$mail->SMTPDebug = 0; // Set to 2 temporarily for debugging
$mail->SMTPDebug = 2; // You can set it to 1, 2, or 3 for increasing verbosity
$mail->Debugoutput = 'html'; // You can output it to 'html' or 'error_log'
return $mail;
}
/**
* Build (or fetch a shared) SemesterScoreService instance.
*
* Usage:
* $svc = service('semesterScoreService'); // shared
* $svc = \Config\Services::semesterScoreService(); // shared
* $svc = \Config\Services::semesterScoreService(false); // NEW instance (not shared)
*/
public static function semesterScoreService(bool $getShared = true): SemesterScoreService
{
if ($getShared) {
return static::getSharedInstance('semesterScoreService');
}
// Core models
$scoreModel = new SemesterScoreModel();
$configModel = new ConfigurationModel();
// Calculators (inject their models)
$homeworkCalc = new HomeworkCalculator(new HomeworkModel());
$quizCalc = new QuizCalculator(new QuizModel());
$projectCalc = new ProjectCalculator(new ProjectModel());
$attendanceCalc = new AttendanceCalculator(
new AttendanceRecordModel(),
new ConfigurationModel(),
new CalendarModel()
);
// If you later add Midterm/Final/Participation calculators, plug them in here.
return new SemesterScoreService(
$scoreModel,
$configModel,
$homeworkCalc,
$quizCalc,
$projectCalc,
$attendanceCalc
);
}
public static function roleService($getShared = true)
{
if ($getShared) {
return static::getSharedInstance('roleService');
}
return new \App\Services\RoleService();
}
public static function emailService($getShared = true)
{
if ($getShared) {
return static::getSharedInstance('emailService');
}
// Replace with your real EmailService class + constructor args
return new \App\Services\EmailService();
}
/**
* TimeService shared builder (timezone detection + conversions).
*/
public static function timeService(bool $getShared = true): \App\Services\TimeService
{
if ($getShared) {
return static::getSharedInstance('timeService');
}
return new \App\Services\TimeService();
}
/**
* Shared API client for outbound HTTP to external services.
*/
public static function apiClient(bool $getShared = true): \App\Services\ApiClient
{
if ($getShared) {
return static::getSharedInstance('apiClient');
}
$apiConfig = config('Api');
$options = [
'baseURI' => $apiConfig->baseURL ?: null,
'timeout' => $apiConfig->timeout,
'headers' => $apiConfig->defaultHeaders,
];
// Remove null/empty values that may cause issues
$options = array_filter($options, static function ($v) {
return $v !== null && $v !== '';
});
$http = static::curlrequest($options);
return new \App\Services\ApiClient($http, $apiConfig);
}
}
+104
View File
@@ -0,0 +1,104 @@
<?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\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';
public string $cookieDomain = ''; // Leave blank for localhost
public bool $cookieSecure = false; // Set to false if not using HTTPS
/**
* --------------------------------------------------------------------------
* 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 = 86400;
/**
* --------------------------------------------------------------------------
* 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;
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace Config;
class SessionTimeout
{
// Session timeout in seconds (12 hours)
public const TIMEOUT_DURATION = 43200;
// Warning threshold in seconds (5 minutes before timeout)
public const WARNING_THRESHOLD = 42900;
// Server-side check interval (in seconds)
public const CHECK_INTERVAL = 300; // 5 minutes
// Client-side check interval (in milliseconds)
public const CLIENT_CHECK_INTERVAL = 60000; // 1 minute
}
+179
View File
@@ -0,0 +1,179 @@
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Style extends BaseConfig
{
// Accent color palettes (used as the app primary color in management views)
public $stylePalettes = [
'blue' => [
'primary' => '#4da3ff',
'primary_hover' => '#1d7eff',
'thead_bg' => '#f0f7ff',
'thead_border' => 'rgba(29, 126, 255, 0.25)',
],
'green' => [
'primary' => '#22c55e',
'primary_hover' => '#16a34a',
'thead_bg' => '#ecfdf5',
'thead_border' => 'rgba(22, 163, 74, 0.25)',
],
'purple' => [
'primary' => '#8b5cf6',
'primary_hover' => '#7c3aed',
'thead_bg' => '#f5f3ff',
'thead_border' => 'rgba(124, 58, 237, 0.25)',
],
'orange' => [
'primary' => '#f59e0b',
'primary_hover' => '#d97706',
'thead_bg' => '#fff7ed',
'thead_border' => 'rgba(217, 119, 6, 0.25)',
],
// Additional accents
'red' => [
'primary' => '#ef4444',
'primary_hover' => '#dc2626',
'thead_bg' => '#fef2f2',
'thead_border' => 'rgba(220, 38, 38, 0.25)',
],
'teal' => [
'primary' => '#14b8a6',
'primary_hover' => '#0d9488',
'thead_bg' => '#f0fdfa',
'thead_border' => 'rgba(13, 148, 136, 0.25)',
],
'cyan' => [
'primary' => '#06b6d4',
'primary_hover' => '#0891b2',
'thead_bg' => '#ecfeff',
'thead_border' => 'rgba(8, 145, 178, 0.25)',
],
'rose' => [
'primary' => '#f43f5e',
'primary_hover' => '#e11d48',
'thead_bg' => '#fff1f2',
'thead_border' => 'rgba(225, 29, 72, 0.25)',
],
'indigo' => [
'primary' => '#6366f1',
'primary_hover' => '#4f46e5',
'thead_bg' => '#eef2ff',
'thead_border' => 'rgba(79, 70, 229, 0.25)',
],
'slate' => [
'primary' => '#64748b',
'primary_hover' => '#475569',
'thead_bg' => '#f1f5f9',
'thead_border' => 'rgba(71, 85, 105, 0.25)',
],
'amber' => [
'primary' => '#f59e0b',
'primary_hover' => '#b45309',
'thead_bg' => '#fffbeb',
'thead_border' => 'rgba(180, 83, 9, 0.25)',
],
'lime' => [
'primary' => '#84cc16',
'primary_hover' => '#4d7c0f',
'thead_bg' => '#f7fee7',
'thead_border' => 'rgba(77, 124, 15, 0.25)',
],
'fuchsia' => [
'primary' => '#d946ef',
'primary_hover' => '#a21caf',
'thead_bg' => '#fdf4ff',
'thead_border' => 'rgba(162, 28, 175, 0.25)',
],
'violet' => [
'primary' => '#7c3aed',
'primary_hover' => '#5b21b6',
'thead_bg' => '#f5f3ff',
'thead_border' => 'rgba(91, 33, 182, 0.25)',
],
'ocean' => [
'primary' => '#0284c7',
'primary_hover' => '#0c4a6e',
'thead_bg' => '#e0f2fe',
'thead_border' => 'rgba(12, 74, 110, 0.25)',
],
'copper' => [
'primary' => '#b45309',
'primary_hover' => '#7c2d12',
'thead_bg' => '#fff7ed',
'thead_border' => 'rgba(124, 45, 18, 0.25)',
],
'gold' => [
'primary' => '#ca8a04',
'primary_hover' => '#92400e',
'thead_bg' => '#fefce8',
'thead_border' => 'rgba(146, 64, 14, 0.25)',
],
'mint' => [
'primary' => '#10b981',
'primary_hover' => '#047857',
'thead_bg' => '#ecfdf3',
'thead_border' => 'rgba(4, 120, 87, 0.25)',
],
'sky' => [
'primary' => '#38bdf8',
'primary_hover' => '#0284c7',
'thead_bg' => '#f0f9ff',
'thead_border' => 'rgba(2, 132, 199, 0.25)',
],
'berry' => [
'primary' => '#be185d',
'primary_hover' => '#9d174d',
'thead_bg' => '#fff1f2',
'thead_border' => 'rgba(157, 23, 77, 0.25)',
],
'peacock' => [
'primary' => '#0f766e',
'primary_hover' => '#115e59',
'thead_bg' => '#f0fdfa',
'thead_border' => 'rgba(17, 94, 89, 0.25)',
],
'espresso' => [
'primary' => '#6f4e37',
'primary_hover' => '#5b3a29',
'thead_bg' => '#f5f0eb',
'thead_border' => 'rgba(91, 58, 41, 0.25)',
],
];
// Menu color palettes (top management navbar + header area)
// mode: impacts whether we render navbar-light or navbar-dark for toggler/contrast
public $menuPalettes = [
'white' => [ 'bg' => '#ffffff', 'text' => '#334155', 'mode' => 'light' ],
'light' => [ 'bg' => '#f8fafc', 'text' => '#334155', 'mode' => 'light' ],
'brand' => [ 'bg' => '#1d7eff', 'text' => '#ffffff', 'mode' => 'dark' ],
'dark' => [ 'bg' => '#0f172a', 'text' => '#e2e8f0', 'mode' => 'dark' ],
// Additional menu color sets
'sky' => [ 'bg' => '#0ea5e9', 'text' => '#ffffff', 'mode' => 'dark' ],
'emerald' => [ 'bg' => '#059669', 'text' => '#ffffff', 'mode' => 'dark' ],
'teal' => [ 'bg' => '#0f766e', 'text' => '#e2e8f0', 'mode' => 'dark' ],
'navy' => [ 'bg' => '#0b2a4a', 'text' => '#e2e8f0', 'mode' => 'dark' ],
'slate' => [ 'bg' => '#f1f5f9', 'text' => '#334155', 'mode' => 'light' ],
'graphite' => [ 'bg' => '#111827', 'text' => '#f3f4f6', 'mode' => 'dark' ],
'sand' => [ 'bg' => '#fafaf9', 'text' => '#374151', 'mode' => 'light' ],
'rose' => [ 'bg' => '#be123c', 'text' => '#ffffff', 'mode' => 'dark' ],
'amber' => [ 'bg' => '#b45309', 'text' => '#ffffff', 'mode' => 'dark' ],
'moss' => [ 'bg' => '#4d7c0f', 'text' => '#fefce8', 'mode' => 'dark' ],
'plum' => [ 'bg' => '#6d28d9', 'text' => '#f5f3ff', 'mode' => 'dark' ],
'ocean' => [ 'bg' => '#0c4a6e', 'text' => '#e0f2fe', 'mode' => 'dark' ],
'charcoal' => [ 'bg' => '#1f2937', 'text' => '#e5e7eb', 'mode' => 'dark' ],
'clay' => [ 'bg' => '#fef3c7', 'text' => '#78350f', 'mode' => 'light' ],
'gold' => [ 'bg' => '#92400e', 'text' => '#fffbeb', 'mode' => 'dark' ],
'mint' => [ 'bg' => '#047857', 'text' => '#ecfdf5', 'mode' => 'dark' ],
'sky' => [ 'bg' => '#0ea5e9', 'text' => '#e0f2fe', 'mode' => 'dark' ],
'berry' => [ 'bg' => '#9d174d', 'text' => '#fff1f2', 'mode' => 'dark' ],
'cocoa' => [ 'bg' => '#4b2f23', 'text' => '#f5f0eb', 'mode' => 'dark' ],
'parchment'=> [ 'bg' => '#fffbeb', 'text' => '#7c2d12', 'mode' => 'light' ],
];
// Default selections when no user choice exists
public $defaultStyle = 'blue';
public $defaultMenu = 'white';
}
+122
View File
@@ -0,0 +1,122 @@
<?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',
];
}
+252
View File
@@ -0,0 +1,252 @@
<?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',
'msnbot' => 'MSNBot',
'baiduspider' => 'Baiduspider',
'bingbot' => 'Bing',
'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',
];
}
+44
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
// --------------------------------------------------------------------
}
+62
View File
@@ -0,0 +1,62 @@
<?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 = [];
}
File diff suppressed because it is too large Load Diff
+214
View File
@@ -0,0 +1,214 @@
<?php
namespace App\Controllers;
use App\Models\ClassProgressReportModel;
use App\Models\ClassProgressAttachmentModel;
use App\Models\ClassSectionModel;
use App\Models\StudentClassModel;
use CodeIgniter\Exceptions\PageNotFoundException;
use CodeIgniter\HTTP\ResponseInterface;
class AdminProgressController extends BaseController
{
protected ClassProgressReportModel $reportModel;
protected ClassProgressAttachmentModel $attachmentModel;
protected ClassSectionModel $classSectionModel;
protected StudentClassModel $studentClassModel;
public function __construct()
{
helper(['url', 'form']);
$this->reportModel = new ClassProgressReportModel();
$this->attachmentModel = new ClassProgressAttachmentModel();
$this->classSectionModel = new ClassSectionModel();
$this->studentClassModel = new StudentClassModel();
}
public function index()
{
$filters = [
'from' => (string) $this->request->getGet('from'),
'to' => (string) $this->request->getGet('to'),
'class_section_id' => (string) $this->request->getGet('class_section_id'),
'status' => (string) $this->request->getGet('status'),
];
$builder = $this->reportModel
->select('class_progress_reports.*, cs.class_section_name, CONCAT(IFNULL(u.firstname, ""), " ", IFNULL(u.lastname, "")) AS teacher_name')
->join('classSection cs', 'cs.class_section_id = class_progress_reports.class_section_id', 'left')
->join('users u', 'u.id = class_progress_reports.teacher_id', 'left');
if ($filters['from']) {
$builder->where('week_start >=', $filters['from']);
}
if ($filters['to']) {
$builder->where('week_end <=', $filters['to']);
}
if ($filters['class_section_id']) {
$builder->where('class_progress_reports.class_section_id', (int) $filters['class_section_id']);
}
if ($filters['status']) {
$builder->where('class_progress_reports.status', $filters['status']);
}
$rows = $builder->orderBy('week_start', 'DESC')->get()->getResultArray();
$reportGroups = [];
foreach ($rows as $row) {
$row['status_label'] = ClassProgressController::STATUS_OPTIONS[$row['status']] ?? 'Unknown';
$key = ($row['week_start'] ?? '') . '_' . ($row['class_section_id'] ?? '');
if ($key === '_') {
continue;
}
if (! isset($reportGroups[$key])) {
$reportGroups[$key] = [
'week_start' => $row['week_start'],
'week_end' => $row['week_end'],
'class_section_name' => $row['class_section_name'] ?? '',
'reports' => [],
];
}
$reportGroups[$key]['reports'][$row['subject']] = $row;
}
$classSections = $this->classSectionModel->getClassSections();
$studentCounts = $this->studentClassModel->getStudentCountsBySection();
$filteredSections = array_values(array_filter($classSections, function ($section) use ($studentCounts) {
$sectionId = (int) ($section['class_section_id'] ?? 0);
return isset($studentCounts[$sectionId]) && $studentCounts[$sectionId] > 0;
}));
return view('admin/class_progress_list', [
'reportGroups' => $reportGroups,
'filters' => $filters,
'classSections' => $filteredSections,
'statusOptions' => ClassProgressController::STATUS_OPTIONS,
'subjectSections' => ClassProgressController::SUBJECT_SECTIONS,
]);
}
public function view($id)
{
$row = $this->reportModel
->select('class_progress_reports.*, cs.class_section_name, CONCAT(IFNULL(u.firstname, ""), " ", IFNULL(u.lastname, "")) AS teacher_name')
->join('classSection cs', 'cs.class_section_id = class_progress_reports.class_section_id', 'left')
->join('users u', 'u.id = class_progress_reports.teacher_id', 'left')
->find((int) $id);
if (! $row) {
throw new PageNotFoundException('Progress report not found.');
}
$row['status_label'] = ClassProgressController::STATUS_OPTIONS[$row['status']] ?? 'Unknown';
$row['flags'] = $this->decodeFlags($row['flags_json']);
$weeklyReports = $this->reportModel
->select('class_progress_reports.*')
->where('class_section_id', $row['class_section_id'])
->where('week_start', $row['week_start'])
->orderBy('subject', 'ASC')
->findAll();
$attachmentMap = $this->loadAttachmentsForReports(array_column($weeklyReports, 'id'));
foreach ($weeklyReports as &$report) {
$report['attachments'] = $attachmentMap[$report['id']] ?? [];
if (empty($report['attachments']) && ! empty($report['attachment_path'])) {
$report['attachments'][] = [
'id' => $report['id'],
'name' => basename((string) $report['attachment_path']),
'legacy' => true,
];
}
}
return view('admin/class_progress_view', [
'row' => $row,
'weeklyReports' => $weeklyReports,
'subjectSections' => ClassProgressController::SUBJECT_SECTIONS,
]);
}
public function attachment($id)
{
$row = $this->reportModel->find((int)$id);
if (! $row || empty($row['attachment_path'])) {
throw new PageNotFoundException('Attachment not found.');
}
$file = $this->resolveAttachmentFile($row);
if (! $file) {
throw new PageNotFoundException('Attachment missing.');
}
return $this->response->download($file, null)->setFileName(basename($file));
}
public function attachmentFile($id)
{
$attachment = $this->attachmentModel->find((int) $id);
if (! $attachment || empty($attachment['file_path'])) {
throw new PageNotFoundException('Attachment not found.');
}
$file = $this->resolveAttachmentPath($attachment['file_path']);
if (! $file) {
throw new PageNotFoundException('Attachment missing.');
}
$downloadName = $attachment['original_name'] ?: basename($file);
return $this->response->download($file, null)->setFileName($downloadName);
}
protected function resolveAttachmentFile(array $row): ?string
{
$path = trim((string) ($row['attachment_path'] ?? ''));
if ($path === '') {
return null;
}
return $this->resolveAttachmentPath($path);
}
protected function resolveAttachmentPath(string $path): ?string
{
$relative = preg_replace('#^writable/uploads/#', '', $path);
$absolute = WRITEPATH . 'uploads/' . ltrim($relative, '/');
return is_file($absolute) ? $absolute : null;
}
protected function loadAttachmentsForReports(array $reportIds): array
{
$reportIds = array_values(array_filter(array_map('intval', $reportIds)));
if (empty($reportIds)) {
return [];
}
$rows = $this->attachmentModel
->whereIn('report_id', $reportIds)
->orderBy('id', 'ASC')
->findAll();
$map = [];
foreach ($rows as $row) {
$reportId = (int) ($row['report_id'] ?? 0);
if ($reportId === 0) {
continue;
}
$map[$reportId][] = [
'id' => (int) $row['id'],
'name' => $row['original_name'] ?: basename((string) $row['file_path']),
];
}
return $map;
}
protected function decodeFlags(?string $json): array
{
if (! $json) {
return [];
}
$flags = json_decode($json, true);
return is_array($flags) ? $flags : [];
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
class ApiDocsController extends Controller
{
public function index()
{
return view('docs/swagger_ui');
}
public function public()
{
return view('docs/swagger_ui_public');
}
}
+614
View File
@@ -0,0 +1,614 @@
<?php
namespace App\Controllers;
use App\Models\LoginActivityModel;
use App\Models\UserModel;
use App\Models\UserRoleModel;
use CodeIgniter\Controller;
use CodeIgniter\Events\Events;
use App\Models\IpAttemptModel;
use App\Models\PasswordResetModel;
use CodeIgniter\I18n\Time;
use App\Models\RoleModel;
use App\Models\ConfigurationModel;
use App\Models\PreferencesModel;
require_once APPPATH . 'Helpers/pbkdf2_helper.php';
require_once APPPATH . 'Helpers/jwt_helper.php';
class AuthController extends Controller
{
protected $configModel;
protected $userModel;
protected $roleModel;
protected $schoolYear;
protected $semester;
protected $ipAttemptModel;
protected $loginActivityModel;
protected $preferencesModel;
public function __construct()
{
$this->userModel = new UserModel();
$this->roleModel = new RoleModel();
$this->configModel = new ConfigurationModel();
$this->ipAttemptModel = new IpAttemptModel();
$this->loginActivityModel = new LoginActivityModel();
$this->preferencesModel = new PreferencesModel();
$this->schoolYear = $this->configModel->getConfig('school_year');
$this->semester = $this->configModel->getConfig('semester');
}
public function setModel($model)
{
$this->userModel = $model;
}
private function scheduleEvent($userId)
{
// Schedule the event to run after 2 minutes (120 seconds)
Events::trigger('delete_unverified_user', $userId);
}
public function loginMask()
{
// Serve the login view directly here
return view('user/login'); // Adjust the view path as needed
}
public function login()
{
log_message('info', 'Processing login form submission.');
// Step 1: Get email, password, and IP from the request
$email = $this->request->getPost('email');
$password = $this->request->getPost('password');
$ip = $this->request->getIPAddress();
log_message('info', 'Login attempt from IP: ' . $ip . ' for email: ' . $email);
// Step 2: Check if the IP is blocked (too many failed attempts)
if ($this->isIpBlocked($ip)) {
return redirect()
->back()
->with('error', 'Too many failed attempts from your IP. Please try again later.')
->withInput(); // ✅ preserve email input
}
// Step 3: Look up user by email
$user = $this->getUserByEmail($email);
if ($user) {
// Step 4: Check if user is suspended
if ($this->checkIfUserSuspended($user)) {
return redirect()
->back()
->with('error', 'Account suspended. Please check your email to reset your password.')
->withInput(); // ✅ preserve email input
}
// Step 5: Verify password
if ($this->verifyPassword($password, $user['password'])) {
// Step 6: Login successful — reset failed attempts and log
$this->resetFailedAttempts($user['id']);
$this->logLoginAttempt($user['id'], $user['email'], $ip, $this->request->getUserAgent());
// ✅ Step 7: Call loginUser() to set session and redirect
return $this->loginUser($user);
} else {
// Step 8: Password mismatch — log failed attempt
$this->handleFailedLogin($user['id'], $user['email'], $ip);
return redirect()
->back()
->with('error', 'The email and password combination you entered is invalid. Please try again.')
->withInput(); // ✅ preserve email input
}
} else {
// Step 9: No user found — log IP-level attempt
$this->logIpAttempt($ip);
return redirect()
->back()
->with('error', 'The email and password combination you entered is invalid. Please try again.')
->withInput(); // ✅ preserve email input
}
}
// JSON API: POST /api/login
public function apiLogin()
{
$requestData = $this->request->getJSON(true);
if (!$requestData) {
// fallback to form vars
$requestData = [
'email' => $this->request->getPost('email'),
'password' => $this->request->getPost('password'),
];
}
$email = $requestData['email'] ?? '';
$password = $requestData['password'] ?? '';
$ip = $this->request->getIPAddress();
if (!$email || !$password) {
return $this->response->setStatusCode(400)->setJSON([
'status' => false,
'message' => 'Email and password are required.'
]);
}
if ($this->isIpBlocked($ip)) {
return $this->response->setStatusCode(429)->setJSON([
'status' => false,
'message' => 'Too many failed attempts from your IP. Please try again later.'
]);
}
$user = $this->getUserByEmail($email);
if (!$user) {
$this->logIpAttempt($ip);
return $this->response->setStatusCode(401)->setJSON([
'status' => false,
'message' => 'Invalid email or password.'
]);
}
if ($this->checkIfUserSuspended($user)) {
return $this->response->setStatusCode(403)->setJSON([
'status' => false,
'message' => 'Account suspended. Please reset your password.'
]);
}
if (!$this->verifyPassword($password, $user['password'])) {
$this->handleFailedLogin($user['id'], $user['email'], $ip);
return $this->response->setStatusCode(401)->setJSON([
'status' => false,
'message' => 'Invalid email or password.'
]);
}
// Success: reset attempts + log
$this->resetFailedAttempts($user['id']);
$this->logLoginAttempt($user['id'], $user['email'], $ip, $this->request->getUserAgent());
// Fetch roles
$userRoleModel = new UserRoleModel();
$rolesRows = $userRoleModel->select('roles.name')
->join('roles', 'roles.id = user_roles.role_id')
->where('user_roles.user_id', $user['id'])
->get()
->getResultArray();
$roleNames = array_column($rolesRows, 'name');
// Build roles map (object with keys per example)
$rolesMap = [];
foreach ($roleNames as $r) {
$rolesMap[$r] = true;
}
// Build JWT token
$now = time();
$exp = $now + 60 * 60 * 24; // 24h default
$payload = [
'sub' => (int) $user['id'],
'name' => trim(($user['firstname'] ?? '') . ' ' . ($user['lastname'] ?? '')),
'roles' => $roleNames,
'iat' => $now,
'exp' => $exp,
];
$secret = env('JWT_SECRET', 'change-me-in-env');
$token = jwt_encode($payload, $secret, 'HS256');
return $this->response->setJSON([
'status' => true,
'token' => $token,
'user' => [
'id' => (int) $user['id'],
'name' => $payload['name'],
'roles' => (object) $rolesMap,
],
]);
}
/**
* API Registration endpoint
* POST /api/v1/register
*/
public function apiRegister()
{
$requestData = $this->request->getJSON(true);
if (!$requestData) {
// fallback to form vars
$requestData = $this->request->getPost();
}
// Basic validation
$rules = [
'firstname' => 'required|min_length[2]|max_length[30]',
'lastname' => 'required|min_length[2]|max_length[30]',
'email' => 'required|valid_email|is_unique[users.email]',
'password' => 'required|min_length[8]',
'cellphone' => 'required|min_length[10]|max_length[20]',
];
$validation = \Config\Services::validation();
$validation->setRules($rules);
if (!$validation->run($requestData)) {
return $this->response->setStatusCode(422)->setJSON([
'status' => false,
'message' => 'Validation failed',
'errors' => $validation->getErrors(),
]);
}
// Check if email already exists
$existingUser = $this->userModel->where('email', $requestData['email'])->first();
if ($existingUser) {
return $this->response->setStatusCode(422)->setJSON([
'status' => false,
'message' => 'Email already registered',
]);
}
// Hash password
require_once APPPATH . 'Helpers/pbkdf2_helper.php';
$hashedPassword = pbkdf2_hash($requestData['password']);
// Prepare user data
$userData = [
'firstname' => $requestData['firstname'],
'lastname' => $requestData['lastname'],
'email' => $requestData['email'],
'password' => $hashedPassword,
'cellphone' => $requestData['cellphone'],
'gender' => $requestData['gender'] ?? null,
'address_street' => $requestData['address_street'] ?? null,
'city' => $requestData['city'] ?? null,
'state' => $requestData['state'] ?? null,
'zip' => $requestData['zip'] ?? null,
'school_year' => $this->configModel->getConfig('school_year'),
'semester' => $this->configModel->getConfig('semester'),
'status' => 'active',
'is_verified' => 0, // Require email verification
];
try {
$userId = $this->userModel->insert($userData);
if (!$userId) {
return $this->response->setStatusCode(500)->setJSON([
'status' => false,
'message' => 'Failed to create user account',
'errors' => $this->userModel->errors(),
]);
}
// Assign parent role if specified
$roleId = null;
if (isset($requestData['role']) && $requestData['role'] === 'parent') {
$role = $this->roleModel->where('name', 'parent')->first();
if ($role) {
$roleId = $role['id'];
$userRoleModel = new \App\Models\UserRoleModel();
$userRoleModel->insert([
'user_id' => $userId,
'role_id' => $roleId,
]);
}
}
// Generate JWT token
$now = time();
$exp = $now + 60 * 60 * 24; // 24h
$payload = [
'sub' => (int) $userId,
'name' => trim($userData['firstname'] . ' ' . $userData['lastname']),
'roles' => $roleId ? ['parent'] : [],
'iat' => $now,
'exp' => $exp,
];
$secret = env('JWT_SECRET', 'change-me-in-env');
$token = jwt_encode($payload, $secret, 'HS256');
return $this->response->setStatusCode(201)->setJSON([
'status' => true,
'message' => 'Registration successful. Please verify your email.',
'token' => $token,
'user' => [
'id' => (int) $userId,
'name' => $payload['name'],
'email' => $userData['email'],
'roles' => $payload['roles'],
],
]);
} catch (\Exception $e) {
log_message('error', 'Registration error: ' . $e->getMessage());
return $this->response->setStatusCode(500)->setJSON([
'status' => false,
'message' => 'Registration failed. Please try again.',
]);
}
}
private function verifyPassword($password, $storedHash)
{
if (!function_exists('pbkdf2_verify')) {
die('pbkdf2_verify() is NOT loaded');
}
return pbkdf2_verify($password, $storedHash);
}
private function handleFailedLogin($userId, $email, $ip)
{
// Get user data
$user = $this->userModel->find($userId);
$failedAttempts = $user['failed_attempts'] + 1;
$data = ['failed_attempts' => $failedAttempts, 'last_failed_at' => utc_now()];
// Check if the failed attempts have reached 3
if ($failedAttempts >= 3) {
// Suspend the account
$data['is_suspended'] = true;
// Set a warning message in session to inform the user
session()->setFlashdata('warning_message', 'Your account has been suspended due to multiple failed login attempts. A reset password email has been sent to your registered email address.');
// Send the password reset email
$this->sendPasswordResetEmail($email);
}
// Update the user record
$this->userModel->update($userId, $data);
// Log the IP attempt (track failed login attempts)
$this->logIpAttempt($ip);
}
private function isIpBlocked($ip)
{
$attempt = $this->ipAttemptModel->where('ip_address', $ip)->first();
return $attempt && $attempt['blocked_until'] > utc_now();
}
private function logIpAttempt($ip)
{
$now = utc_now();
$attempt = $this->ipAttemptModel->where('ip_address', $ip)->first();
if ($attempt) {
$attempts = $attempt['attempts'] + 1;
$blockedUntil = $attempts >= 10 ? date('Y-m-d H:i:s', strtotime('+24 hours')) : null;
$this->ipAttemptModel->update($attempt['id'], [
'attempts' => $attempts,
'last_attempt_at' => $now,
'blocked_until' => $blockedUntil
]);
} else {
$this->ipAttemptModel->insert([
'ip_address' => $ip,
'attempts' => 1,
'last_attempt_at' => $now
]);
}
}
private function logLoginAttempt($userId, $email, $ipAddress, $userAgent)
{
$this->loginActivityModel->insert([
'user_id' => $userId,
'email' => $email,
'login_time' => utc_now(),
'ip_address' => $ipAddress,
'user_agent' => $userAgent
]);
}
private function resetFailedAttempts($userId)
{
$this->userModel->update($userId, ['failed_attempts' => 0, 'last_failed_at' => null]);
}
public function logout()
{
// Get user ID and email from session
$userId = session()->get('user_id');
$email = session()->get('user_email');
// Log logout
$this->logLogout($userId, $email);
log_message('info', 'Session destroyed.');
// Destroy the session
session()->destroy();
// Redirect to the main login page
return redirect()->to(base_url('/'));
}
private function logLogout($userId, $email)
{
$this->loginActivityModel->where('user_id', $userId)
->where('logout_time', null)
->set('logout_time', utc_now())
->set('email', $email)
->update();
}
private function getUserByEmail($email)
{
return $this->userModel->where('email', $email)->first();
}
private function checkIfUserSuspended($user)
{
return $user['is_suspended'];
}
// This function is used to send ResetPassword email to the userwith suspended account.
private function sendPasswordResetEmail($email)
{
// Load the UserController
$userController = new \App\Controllers\View\UserController();
// First, attempt to find the user by their email
$userModel = new UserModel();
$user = $userModel->where('email', $email)->first();
if (!$user) {
log_message('error', 'User with email ' . $email . ' not found for password reset.');
return false;
}
// Generate a secure token for the password reset
helper('text');
$token = bin2hex(random_bytes(48));
// Calculate the expiration time for the token (1 hour from now)
$expires_at = Time::now()->addHours(1);
// Store the token in the password_resets table
$passwordResetModel = new PasswordResetModel();
$passwordResetModel->insert([
'email' => $email,
'token' => $token,
'created_at' => Time::now(),
'expires_at' => $expires_at,
]);
// Now, send the reset email using the generated token
$userController->sendResetEmail($email, $token); // Calling the original helper function to send the email
// Log and return success
log_message('info', 'Password reset email sent to ' . $email);
return true;
}
private function loginUser($user)
{
$userRoleModel = new UserRoleModel();
$roles = $userRoleModel->select('roles.name')
->join('roles', 'roles.id = user_roles.role_id')
->where('user_roles.user_id', $user['id'])
->get()
->getResultArray();
if (empty($roles)) {
log_message('error', 'No roles found for user ID: ' . $user['id']);
return redirect()->back()->with('error', 'Role not assigned. Please contact support.');
}
$roleNames = array_column($roles, 'name');
session()->set([
'user_id' => $user['id'],
'user_email' => $user['email'],
'user_name' => $user['firstname'] . ' ' . $user['lastname'],
'user_type' => $user['user_type'],
'is_logged_in' => true,
'login_time' => time(),
'roles' => $roleNames,
'semester' => $this->semester,
'school_year' => $this->schoolYear,
]);
$this->applyStylePreferences((int) $user['id']);
log_message('debug', 'Session after login: ' . print_r(session()->get(), true));
//dd('Login successful. Roles:', $roleNames, session()->get());
if (count($roleNames) === 1) {
// One role → set and redirect directly
session()->set('role', $roleNames[0]);
return $this->redirectToDashboard([$roleNames[0]]);
} else {
// Multiple roles → redirect to role selection view
return redirect()->to('/select-role');
}
}
private function applyStylePreferences(int $userId): void
{
if (!$userId) {
return;
}
$prefs = $this->preferencesModel->where('user_id', $userId)->first();
if (!$prefs) {
return;
}
$styleCfg = config('Style');
$styleColor = (string) ($prefs['style_color'] ?? '');
if ($styleColor !== '' && isset(($styleCfg->stylePalettes ?? [])[$styleColor])) {
session()->set('style_color', $styleColor);
}
$menuColor = (string) ($prefs['menu_color'] ?? '');
if ($menuColor === 'custom') {
$bg = (string) ($prefs['menu_custom_bg'] ?? '#0f172a');
$tx = (string) ($prefs['menu_custom_text'] ?? '#ffffff');
$mode = (string) ($prefs['menu_custom_mode'] ?? 'dark');
session()->set('menu_color', 'custom');
session()->set('menu_custom_bg', $bg);
session()->set('menu_custom_text', $tx);
session()->set('menu_custom_mode', $mode);
} elseif ($menuColor !== '' && isset(($styleCfg->menuPalettes ?? [])[$menuColor])) {
session()->set('menu_color', $menuColor);
}
}
private function redirectToDashboard(array $roles)
{
if (empty($roles)) {
log_message('error', 'Empty roles array passed to redirectToDashboard.');
return redirect()->to('/landing_page/guest_dashboard');
}
$roleModel = new RoleModel();
// Resolve all candidate roles (by name or slug), ordered by priority ASC
$rows = $roleModel->findByNamesOrSlugs($roles);
if (!empty($rows)) {
$route = $rows[0]['dashboard_route'] ?? '/landing_page/guest_dashboard';
log_message('debug', 'Redirecting user to: ' . $route);
return redirect()->to($route);
}
log_message('warning', 'No matching role found. Redirecting to guest dashboard.');
return redirect()->to('/landing_page/guest_dashboard');
}
public function setRole()
{
$selectedRole = $this->request->getPost('selected_role');
$availableRoles = session()->get('roles');
if (!$selectedRole || !in_array($selectedRole, $availableRoles)) {
return redirect()->to('/select-role')->with('error', 'Invalid role selected.');
}
session()->set('role', $selectedRole);
return $this->redirectToDashboard([$selectedRole]);
}
public function selectRole()
{
$roles = session()->get('roles');
if (!$roles || !is_array($roles)) {
return redirect()->to('/login')->with('error', 'No roles available.');
}
return view('auth/select_role', ['roles' => $roles]);
}
}

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