Skip to content
Merged

Dev #20

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,15 @@ DB_NAME="database"
DB_PORT="3306"
DB_PREFIX="prefix_"

# Mail (leave MAIL_HOST empty to use PHP mail())
MAIL_HOST=""
MAIL_PORT="587"
MAIL_USER=""
MAIL_PASS=""
MAIL_ENCRYPTION="tls"
MAIL_FROM=""
MAIL_FROM_NAME=""

# Google API Key
GOOGLE_AUTH_CLIENT_ID=""
GOOGLE_AUTH_CLIENT_SECRET=""
Expand Down
69 changes: 56 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

- **MVC Architecture:** Clean separation of concerns with models, views, and controllers to organize code logically.
- **Core Components:** Includes essential libraries for handling sessions, database connections, request processing, and URL routing.
- **Secure by Default:** Twig auto-escaping, CSRF tokens, hardened sessions, and strict route validation out of the box.
- **Modern Frontend Build:** Tailwind CSS 4 + daisyUI bundled with Vite, with automatic cache busting.
- **Migration System:** Built-in system for managing database schema changes and versioning.
- **Installer:** Interactive installer for quick setup, including `.env` generation, Composer installation, and database migration execution.
- **Easy to Install and Configure:** Minimal setup required for developers to get started quickly.
Expand All @@ -20,32 +22,51 @@
- PHP 8+
- A web server (e.g., Apache, Nginx)
- MySQL
- Node.js 20+ and npm (only for building frontend assets)

## Installation

1. Clone the repository:

```bash
git clone https://github.com/yourusername/PHPapp.git
git clone https://github.com/and-ri/phpapp.git
```

2. Navigate to the project directory:

```bash
cd PHPapp
cd phpapp
```

3. Install dependencies:
3. Install dependencies and build frontend assets:

```bash
composer install
npm install
npm run build
```

4. Run the installer:
Open `http://yourdomain.com/installer.php` in your browser and follow the on-screen instructions to set up the database and configuration.

5. Done!
5. Done! For security, delete `installer.php` from the `www` directory after installation (it refuses to run again while `.env` exists, but removing it entirely is safer).

## Frontend Assets

Frontend sources live in `static/css/style.css` and `static/js/app.js` and are bundled by Vite (Tailwind CSS 4 + daisyUI) into `www/assets/`:

```bash
npm run dev # rebuild automatically on changes (vite build --watch)
npm run build # one-off production build
```

Templates reference the built assets through `$this->staticfile->getAssetUri('css/app.css')`, which appends a cache-busting `?v=<timestamp>` parameter. The built files in `www/assets/` are committed to the repository, so remember to run `npm run build` before committing frontend changes.

## Templating and Security

- Twig **auto-escaping is enabled**: any variable printed with `{{ ... }}` is HTML-escaped. Pass trusted HTML (e.g. output of another controller) through `$this->view->raw($html)` — `Load::controller()` already does this for you.
- Every form should include the CSRF field with `{{ csrf }}` and validate it with `$this->session->validateToken($this->request->post['csrf'])` (see `app/controller/catalog/csrf_protection.php` for a complete example).
- Request data (`$this->request->get/post/cookie`) is raw. Escape at the output layer: Twig handles HTML, and use `$this->db->escape()` or `$this->db->execute($sql, $params)` (prepared statements) for SQL.

## Core Components

Expand All @@ -58,27 +79,49 @@
### Libraries

- **app.php**: Manages the application lifecycle, including initialization and configuration.
- **db.php**: Provides methods for database queries and connection handling.
- **cache.php**: Simple file-based cache with optional TTL (`get`, `set`, `delete`, `deleteAll`).
- **db.php**: Provides methods for database queries and connection handling, including prepared statements via `execute()`.
- **env.php**: Handles environment variables and configuration settings.
- **flash.php**: One-time session messages for the POST -> redirect -> GET pattern.
- **google_auth.php**: Handles the Google authentication process for the application.
- **language.php**: Loads and manages language files for multi-language support.
- **load.php**: Loads models and controllers dynamically.
- **mail.php**: Sends email via SMTP or PHP `mail()` using PHPMailer (configured through `.env`).
- **pagination.php**: Provides simple pagination functionality.
- **request.php**: Handles incoming HTTP requests.
- **response.php**: Manages HTTP responses and headers.
- **session.php**: Facilitates session management (start, get, set, remove, etc.).
- **staticfile.php**: Serves static files (CSS, JS, images).
- **session.php**: Facilitates session management (start, get, set, remove, etc.) and CSRF tokens.
- **staticfile.php**: Serves static files (CSS, JS, images) and generates cache-busted URIs for built assets.
- **upload.php**: Stores uploaded files safely (finfo MIME check, extension allowlist, random names).
- **url.php**: Generates URLs and manages routing.
- **validator.php**: Rule-based input validation (`required|email|min:8|...`) with per-field error messages.
- **log.php**: Provides centralized logging functionality using Monolog.
- **meta.php**: Manages SEO metadata including page titles, descriptions, Open Graph tags, and robots directives using the Melbahja/Seo package.

### New Features
## Migrations

Create a migration by copying `migrations/template.php` to a new file (e.g. `migrations/2026_07_04_create_users.php`). A migration returns an anonymous class with `up()` and `down()` methods:

```php
return new class {
public function up($db) {
$db->query("CREATE TABLE ...");
}

public function down($db) {
$db->query("DROP TABLE ...");
}
};
```

Then run:

- **Migration System:** Manage database schema changes with ease. Use `php migrate.php migrate` to apply migrations, `php migrate.php rollback` to undo the last migration, and `php migrate.php status` to check migration status.
- **Interactive Installer:** Quickly set up your application by providing database and web configuration details in a user-friendly web installer.
- **Centralized Logging:** Monitor application events, errors, and debugging information using the integrated Monolog-based logging system.
- **SEO Management:** Easily manage page metadata, title tags, Open Graph properties, and other SEO essentials using the integrated meta.php library powered by Melbahja/Seo package.
```bash
php migrate.php migrate # apply pending migrations
php migrate.php rollback # undo the last migration
php migrate.php status # show applied and pending migrations
```

## License

This project is licensed under the MIT License.
This project is licensed under the MIT License.
21 changes: 16 additions & 5 deletions app/controller/catalog/csrf_protection.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,16 @@ public function index() {
$this->data['action'] = $this->url->link('catalog/csrf_protection');

if ($this->request->server['REQUEST_METHOD'] == 'POST' && $this->validate()) {
$this->data['success'] = $this->language->get('text_success');
} else {
$this->data['error'] = isset($this->error['csrf_token']) ? $this->error['csrf_token'] : '';
$this->data['email'] = isset($this->request->post['email']) ? $this->request->post['email'] : '';
// POST -> redirect -> GET: the message survives the redirect in a flash
$this->flash->set('success', $this->language->get('text_success'));

$this->response->redirect($this->data['action']);
}

$this->data['success'] = $this->flash->get('success');
$this->data['error'] = implode(' ', $this->error);
$this->data['email'] = isset($this->request->post['email']) ? $this->request->post['email'] : '';

$this->data['header'] = $this->load->controller('common/header');
$this->data['footer'] = $this->load->controller('common/footer');

Expand All @@ -29,6 +33,13 @@ protected function validate() {
$this->error['csrf_token'] = $this->language->get('error_csrf_token');
}

if (!$this->validator->validate($this->request->post, array(
'email' => 'required|email',
'password' => 'required|min:8'
))) {
$this->error = array_merge($this->error, $this->validator->errors());
}

return !$this->error;
}
}
}
4 changes: 3 additions & 1 deletion app/language/en/catalog/csrf_protection.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
'entry_email' => 'Email',
'entry_password' => 'Password',
'button_submit' => 'Submit',
'error_csrf_token' => 'Invalid CSRF token',
'error_csrf_token' => 'Invalid CSRF token.',
'error_validation_email' => 'Please enter a valid email address.',
'error_validation_min' => 'The %field% must be at least %param% characters.',
'text_success' => 'Success! CSRF token is valid',
'text_help' => 'This form is protected by CSRF protection. To submit the form, you need to provide a valid CSRF token. The token is generated when the form is loaded and is stored in the session. When the form is submitted, the token is validated. If the token is invalid, the form submission is rejected.',
];
5 changes: 3 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
"vlucas/phpdotenv": "^5.6",
"google/apiclient": "^2.0",
"monolog/monolog": "^3.9",
"melbahja/seo": "^2.1"
"melbahja/seo": "^2.1",
"phpmailer/phpmailer": "^7.1"
},
"repositories": [
{
Expand All @@ -28,4 +29,4 @@
"config": {
"vendor-dir": "core/vendor"
}
}
}
Loading
Loading