Difference between revisions for Users / Eo Ny / dev




← Previous edit
Next edit →

Additions:

Overview

The Http class (src/class/http.php) is a core component of the WackoWiki system responsible for handling HTTP request/response processing, session management, caching, and security features. This class acts as a bridge between the web server and the wiki engine.
File Location: src/class/http.php
Dependencies: Database class, Session classes, Utility classes (Ut), Diagnostics class (Diag)

Class Properties

Public Properties

Property Type Description
$tls_session bool Indicates if the current session uses HTTPS/TLS encryption
$request_uri string Normalized REQUEST_URI (e.g., 'PageOfNoReturn/show?a=1')
$ip string Client's real IP address (accounts for proxies)
$sess Session Reference to the Session object
$method string Current HTTP method/request type

Private Properties

Property Type Description
$db object Database connection reference
$tls_mark string Cookie name for TLS session marking
$page string Current page name being processed
$hash string SHA1 hash of the page name
$query string Encoded query string
$lang string Current language code
$file string Cache file path
$caching int Flag indicating if page should be cached (0 or 1)

Constructor

PHP


  • $db - Database object reference
  1. Stores database reference
  2. Extracts and normalizes REQUEST_URI
  3. Detects TLS/HTTPS session status
  4. Determines client's real IP address
  5. Sets up TLS mark cookie name
  6. Enforces TLS session upgrade if needed
PHP



Core Methods

Session Management

session($route): void

  • $route (int) - Routing flag:
  • Bit 2 ($route & 2): Enable static mode for files/freecap (disables replay prevention and ID regeneration)
  • Selects storage backend (file or database)
  • Configures cookie settings (security, path, httponly)
  • Binds IP and TLS validation
  • Recovers diagnostic logs from previous session
PHP



Caching System

check_cache($page, $method): void

  • $page (string) - Page name to cache
  • $method (string) - Request method/action (e.g., 'show', 'edit')
  • ✅ Enabled for GET requests only
  • ✅ Disabled for POST requests
  • ❌ Never cached for 'edit' or 'watch' methods
  • ✅ Only cached for anonymous users (no logged-in users)
PHP



store_cache(): void

  • Retrieves output buffer content
  • Saves to cache file with proper permissions
  • Records cache metadata in database
  • Only executes if caching flag is set and user is anonymous
PHP



invalidate_page($page): int

  • $page (string) - Page name to invalidate
  • Number of cache entries invalidated
  1. Finds all cached versions (different methods/languages)
  2. Touches files to past timestamp (faster than deletion)
  3. Removes entries from cache metadata table
  4. Returns count of invalidated caches
PHP



TLS/HTTPS Security

secure_base_url(): void

  • Ensures all subsequent URLs use HTTPS
  • Stores original HTTP URL for fallback
  • Called when TLS session is detected
PHP



ensure_tls($url): void

  • $url (string) - URL to secure
  • If not already HTTPS and TLS is enabled, forces HTTPS redirect
  • Handles both relative and absolute URLs
  • Converts relative URLs using current server name
PHP



IP Address Detection

real_ip(): string (Private)

  1. HTTP_X_CLUSTER_CLIENT_IP
  2. HTTP_X_FORWARDED_FOR (or custom header)
  3. HTTP_CLIENT_IP
  4. HTTP_X_REMOTE_ADDR
  5. REMOTE_ADDR (fallback)
  • Filters out private/reserved IP ranges
  • Respects configured reverse proxy addresses
  • Returns '0.0.0.0' as fallback
  • reverse_proxy_addresses - Comma/space-separated proxy IPs
  • reverse_proxy_header - Custom header name (default: X-Forwarded-For)
PHP



HTTPS Detection

tls_session(): bool (Private)

  • $_SERVER['HTTPS'] is 'on'
  • $_SERVER['SERVER_PORT'] is 443
  • $_SERVER['HTTP_X_FORWARDED_PROTO'] is 'https'
  • $_SERVER['HTTP_X_FORWARDED_SSL'] is 'on'
  • $_SERVER['HTTP_X_FORWARDED_PORT'] is 443

Security Headers

http_security_headers(): void

Header Purpose Config Key
Content-Security-Policy XSS/injection protection csp
Permissions-Policy Control browser features permissions_policy
Referrer-Policy Control referrer information referrer_policy
Strict-Transport-Security Force HTTPS Auto (TLS only)
X-Frame-Options Clickjacking protection Hardcoded: SAMEORIGIN
X-Content-Type-Options MIME sniffing prevention Hardcoded: nosniff
  • 0 - Disabled
  • 1 - Default policy (from csp.conf)
  • 2 - Custom policy (from csp_custom.conf)
PHP



HTTP Methods

redirect($url, $permanent = false): void

  • $url (string) - Target URL
  • $permanent (bool) - Use 301 (permanent) vs 302 (temporary)
  • Decodes & entities to prevent broken redirects
  • Only works if headers not yet sent
  • Uses output buffering to work anywhere in page processing
PHP



terminate(): void

  • Saves diagnostic logs to session flash data
  • Ends script execution
PHP



status($code): void

PHP


PHP



Caching Control

no_cache($client_only = true): void

  • $client_only (bool, default: TRUE)
  • TRUE: Disable browser cache only
  • FALSE: Disable both browser and server cache
  • Last-Modified: <current-time> (always fresh)
  • Cache-Control: no-store
PHP



cache_promisc(): void

  • Cache-Control: public
PHP



Language Negotiation

user_agent_language(): string

  • Follows RFC 9110 section 12.5.4 (HTTP Accept-Language)
  • Parses Accept-Language header with quality factors
  • Attempts exact match first, then language fallback
  • Falls back to default system language
	

  • Language code (e.g., 'en', 'en-US', 'de')

available_languages($subset = true): array

  • $subset (bool, default: TRUE)
  • TRUE: Only allowed languages
  • FALSE: All available languages
  • Scans LANG_DIR for language files
  • Filters by allowed_languages config if set
  • Caches result in session
  • System language always included
  • Associative array: ['en' => 'en', 'de' => 'de', ...]
PHP



File Serving

sendfile($path, $filename = null, $age = null): void

  • $path (string) - File path (or HTTP_XXX constant for error pages)
  • $filename (string, optional) - Custom download filename
  • $age (int, optional) - Cache age in days
  • HTTP range request support (partial file downloads)
  • ETag and Last-Modified conditional requests
  • Proper MIME type detection
  • Content-Security-Policy for special file types
  • Streaming for large files
  • GZip compression for text files
PHP


PHP



mime_type($path): string

  • MIME type string (e.g., 'application/pdf')
  • Default: 'application/octet-stream'
PHP



mime_types(): array (Private)

  • Reads from config/mime.types
  • Caches to cache/config/mime.types
  • Reloads if config is updated

Compression

gzip(): void

  • Manually implements gzip (not relying on zlib.output_compression)
  • Produces correct Content-Length header
  • Only compresses if:
PHP



Utility Methods

parse_str($str): array (Private)

  • Safely handles special characters in query/form data
  • Converts encoding properly
PHP



request_uri(): string (Private)

  • Removes base URL prefix
  • Removes spaces
  • Collapses multiple slashes
  • Removes .. path traversal attempts
  • Removes leading/trailing slashes

cut_prefix($prefix, $path): string (Private)


get_header_conf($file_name): string (Private)

  • csp.conf / csp_custom.conf
  • permissions_policy.conf / permissions_policy_custom.conf

Configuration Dependencies

Setting Type Purpose
base_url string Wiki's base URL
tls bool Enable HTTPS enforcement
cache bool Enable page caching
cache_ttl int Cache lifetime in seconds
session_store int 1=File, 0=Database
system_seed_hash string Session encryption seed
cookie_prefix string Session cookie prefix
cookie_path string Cookie path
allow_persistent_cookie bool Allow persistent login
session_length int Session lifetime in seconds
reverse_proxy_addresses string Comma/space-separated proxy IPs
reverse_proxy_header string Custom X-Forwarded header
language string Default language code
multilanguage bool Enable language negotiation
allowed_languages string Comma/space-separated allowed langs
enable_security_headers bool Send security headers
csp int CSP setting (0/1/2)
permissions_policy int Permissions-Policy setting (0/1/2)
referrer_policy int Referrer-Policy setting (0-8)

Constants Used

Constant Type Purpose
IN_WACKO bool Security check (exit if not defined)
CHMOD_SAFE int File permissions for cache files
CHMOD_FILE int File permissions for config cache
CACHE_PAGE_DIR string Page cache directory
CACHE_SESSION_DIR string Session cache directory
CACHE_CONFIG_DIR string Config cache directory
CONFIG_DIR string Configuration directory
LANG_DIR string Language files directory
DAYSECS int Seconds in a day (86400)
HTTP_404 string Path to 404 error page
HTTP_403 string Path to 403 error page

Workflow Examples

Example 1: Handling a GET Request

PHP

Example 2: Handling TLS/HTTPS Upgrade

PHP

Example 3: Invalidating Cache After Page Edit

PHP

Example 4: Serving a File

PHP



Security Considerations

1. IP Address Spoofing

  • Validates IPs against private ranges
  • Filters proxy-provided IPs appropriately
  • Configurable reverse proxy trust

2. Session Security

  • Binds sessions to IP address
  • Binds sessions to TLS status
  • Supports both file and database storage
  • HttpOnly cookies by default

3. TLS Enforcement

  • Automatic HTTPS upgrade when configured
  • Marks TLS sessions to prevent downgrade attacks
  • HSTS header support

4. Content Security

  • CSP headers to prevent XSS
  • X-Frame-Options to prevent clickjacking
  • X-Content-Type-Options to prevent MIME sniffing
  • Referrer-Policy control
  • Permissions-Policy for browser features

5. File Serving

  • Validates file existence and readability
  • Prevents directory traversal via realpath()
  • Rejects symbolic links
  • Special CSP for SVG and PDF files

6. Cache Security

  • Cached only for anonymous users
  • Disabled for sensitive operations (edit, watch)
  • Only GET requests cached

Performance Optimization

1. Page Caching

  • Stores full HTML output
  • TTL-based expiration
  • Language and method-aware caching
  • Conditional request support (304 Not Modified)

2. MIME Type Caching

  • Loads MIME types once and caches
  • Regenerates only when config changes

3. Session Options

  • File-based sessions for simple deployments
  • Database sessions for distributed systems

4. Compression

  • Manual gzip implementation
  • Proper Content-Length generation
  • Only compresses appropriate sizes

Debugging

PHP



Related Classes

  • Session Classes (SessionFileStore, SessionDbalStore) - Session management backends
  • Database Class - Configuration and cache metadata storage
  • Ut Utility Class - String/path utilities
  • Diag Class - Diagnostic logging

Version History

  • Supports PHP 8.0+ (uses match expressions, union types)
  • Follows RFC 9110 for HTTP header handling
  • Modern cookie security practices

Conclusion

The Http class is the central request/response handler in WackoWiki, managing everything from session initialization to security headers to file serving. Understanding this class is essential for:
  • Extending WackoWiki with custom request handlers
  • Implementing custom session logic
  • Adding new security policies
  • Optimizing cache strategies
  • Debugging HTTP-related issues

Deletions:
# HTTP Class Technical Documentation
## Overview
The `Http` class (`src/class/http.php`) is a core component of the WackoWiki system responsible for handling HTTP request/response processing, session management, caching, and security features. This class acts as a bridge between the web server and the wiki engine.
File Location: `src/class/http.php`
Dependencies: Database class, Session classes, Utility classes (`Ut`), Diagnostics class (`Diag`)

## Class Properties
### Public Properties
| Property | Type | Description |
|
|
|
| | `$tls_session` | bool | Indicates if the current session uses HTTPS/TLS encryption |
| `$request_uri` | string | Normalized REQUEST_URI (e.g., 'PageOfNoReturn/show?a=1') |
| `$ip` | string | Client's real IP address (accounts for proxies) |
| `$sess` | Session | Reference to the Session object |
| `$method` | string | Current HTTP method/request type |
### Private Properties
| Property | Type | Description |
|
|
|
| | `$db` | object | Database connection reference |
| `$tls_mark` | string | Cookie name for TLS session marking |
| `$page` | string | Current page name being processed |
| `$hash` | string | SHA1 hash of the page name |
| `$query` | string | Encoded query string |
| `$lang` | string | Current language code |
| `$file` | string | Cache file path |
| `$caching` | int | Flag indicating if page should be cached (0 or 1) |

## Constructor
`php	
`
- `$db` - Database object reference
1. Stores database reference
2. Extracts and normalizes REQUEST_URI
3. Detects TLS/HTTPS session status
4. Determines client's real IP address
5. Sets up TLS mark cookie name
6. Enforces TLS session upgrade if needed
`php	
`

## Core Methods
### Session Management
`session($route): void`
- `$route` (int) - Routing flag:
  • Bit 2 (`$route & 2`): Enable static mode for files/freecap (disables replay prevention and ID regeneration)
- Selects storage backend (file or database)
- Configures cookie settings (security, path, httponly)
- Binds IP and TLS validation
- Recovers diagnostic logs from previous session
`php	
`

### Caching System
`check_cache($page, $method): void`
- `$page` (string) - Page name to cache
- `$method` (string) - Request method/action (e.g., 'show', 'edit')
- ✅ Enabled for GET requests only
- ✅ Disabled for POST requests
- ❌ Never cached for 'edit' or 'watch' methods
- ✅ Only cached for anonymous users (no logged-in users)
`php	
`

`store_cache(): void`
- Retrieves output buffer content
- Saves to cache file with proper permissions
- Records cache metadata in database
- Only executes if caching flag is set and user is anonymous
`php	
`

`invalidate_page($page): int`
- `$page` (string) - Page name to invalidate
- Number of cache entries invalidated
1. Finds all cached versions (different methods/languages)
2. Touches files to past timestamp (faster than deletion)
3. Removes entries from cache metadata table
4. Returns count of invalidated caches
`php	
`

### TLS/HTTPS Security
`secure_base_url(): void`
- Ensures all subsequent URLs use HTTPS
- Stores original HTTP URL for fallback
- Called when TLS session is detected
`php	
`

`ensure_tls($url): void`
- `$url` (string) - URL to secure
- If not already HTTPS and TLS is enabled, forces HTTPS redirect
- Handles both relative and absolute URLs
- Converts relative URLs using current server name
`php	
`

### IP Address Detection
`real_ip(): string` (Private)
1. `HTTP_X_CLUSTER_CLIENT_IP`
2. `HTTP_X_FORWARDED_FOR` (or custom header)
3. `HTTP_CLIENT_IP`
4. `HTTP_X_REMOTE_ADDR`
5. `REMOTE_ADDR` (fallback)
- Filters out private/reserved IP ranges
- Respects configured reverse proxy addresses
- Returns `'0.0.0.0'` as fallback
- `reverse_proxy_addresses` - Comma/space-separated proxy IPs
- `reverse_proxy_header` - Custom header name (default: `X-Forwarded-For`)
`php	
`

### HTTPS Detection
`tls_session(): bool` (Private)
- `$_SERVER['HTTPS']` is 'on'
- `$_SERVER['SERVER_PORT']` is 443
- `$_SERVER['HTTP_X_FORWARDED_PROTO']` is 'https'
- `$_SERVER['HTTP_X_FORWARDED_SSL']` is 'on'
- `$_SERVER['HTTP_X_FORWARDED_PORT']` is 443

### Security Headers
`http_security_headers(): void`
| Header | Purpose | Config Key |
|
|
|
| | Content-Security-Policy | XSS/injection protection | `csp` |
| Permissions-Policy | Control browser features | `permissions_policy` |
| Referrer-Policy | Control referrer information | `referrer_policy` |
| Strict-Transport-Security | Force HTTPS | Auto (TLS only) |
| X-Frame-Options | Clickjacking protection | Hardcoded: `SAMEORIGIN` |
| X-Content-Type-Options | MIME sniffing prevention | Hardcoded: `nosniff` |
- `0` - Disabled
- `1` - Default policy (from `csp.conf`)
- `2` - Custom policy (from `csp_custom.conf`)
`php	
`

### HTTP Methods
`redirect($url, $permanent = false): void`
- `$url` (string) - Target URL
- `$permanent` (bool) - Use 301 (permanent) vs 302 (temporary)
- Decodes `&` entities to prevent broken redirects
- Only works if headers not yet sent
- Uses output buffering to work anywhere in page processing
`php	
`

`terminate(): void`
- Saves diagnostic logs to session flash data
- Ends script execution
`php	
`

`status($code): void`
`php	
`
`php	
`

### Caching Control
`no_cache($client_only = true): void`
- `$client_only` (bool, default: TRUE)
  • `TRUE`: Disable browser cache only
  • `FALSE`: Disable both browser and server cache
- `Last-Modified: <current-time>` (always fresh)
- `Cache-Control: no-store`
`php	
`

`cache_promisc(): void`
- `Cache-Control: public`
`php	
`

### Language Negotiation
`user_agent_language(): string`
- Follows RFC 9110 section 12.5.4 (HTTP Accept-Language)
- Parses `Accept-Language` header with quality factors
- Attempts exact match first, then language fallback
- Falls back to default system language
`	
`
- Language code (e.g., 'en', 'en-US', 'de')

`available_languages($subset = true): array`
- `$subset` (bool, default: TRUE)
  • `TRUE`: Only allowed languages
  • `FALSE`: All available languages
- Scans `LANG_DIR` for language files
- Filters by `allowed_languages` config if set
- Caches result in session
- System language always included
- Associative array: `['en' => 'en', 'de' => 'de', ...]`
`php	
`

### File Serving
`sendfile($path, $filename = null, $age = null): void`
- `$path` (string) - File path (or HTTP_XXX constant for error pages)
- `$filename` (string, optional) - Custom download filename
- `$age` (int, optional) - Cache age in days
- HTTP range request support (partial file downloads)
- ETag and Last-Modified conditional requests
- Proper MIME type detection
- Content-Security-Policy for special file types
- Streaming for large files
- GZip compression for text files
`php	
`
`php	
`

`mime_type($path): string`
- MIME type string (e.g., 'application/pdf')
- Default: `'application/octet-stream'`
`php	
`

`mime_types(): array` (Private)
- Reads from `config/mime.types`
- Caches to `cache/config/mime.types`
- Reloads if config is updated

### Compression
`gzip(): void`
- Manually implements gzip (not relying on zlib.output_compression)
- Produces correct `Content-Length` header
- Only compresses if:
`php	
`

### Utility Methods
`parse_str($str): array` (Private)
- Safely handles special characters in query/form data
- Converts encoding properly
`php	
`

`request_uri(): string` (Private)
- Removes base URL prefix
- Removes spaces
- Collapses multiple slashes
- Removes `..` path traversal attempts
- Removes leading/trailing slashes

`cut_prefix($prefix, $path): string` (Private)

`get_header_conf($file_name): string` (Private)
- `csp.conf` / `csp_custom.conf`
- `permissions_policy.conf` / `permissions_policy_custom.conf`

## Configuration Dependencies
| Setting | Type | Purpose |
|
|
|
| | `base_url` | string | Wiki's base URL |
| `tls` | bool | Enable HTTPS enforcement |
| `cache` | bool | Enable page caching |
| `cache_ttl` | int | Cache lifetime in seconds |
| `session_store` | int | 1=File, 0=Database |
| `system_seed_hash` | string | Session encryption seed |
| `cookie_prefix` | string | Session cookie prefix |
| `cookie_path` | string | Cookie path |
| `allow_persistent_cookie` | bool | Allow persistent login |
| `session_length` | int | Session lifetime in seconds |
| `reverse_proxy_addresses` | string | Comma/space-separated proxy IPs |
| `reverse_proxy_header` | string | Custom X-Forwarded header |
| `language` | string | Default language code |
| `multilanguage` | bool | Enable language negotiation |
| `allowed_languages` | string | Comma/space-separated allowed langs |
| `enable_security_headers` | bool | Send security headers |
| `csp` | int | CSP setting (0/1/2) |
| `permissions_policy` | int | Permissions-Policy setting (0/1/2) |
| `referrer_policy` | int | Referrer-Policy setting (0-8) |

## Constants Used
| Constant | Type | Purpose |
|
|
|
| | `IN_WACKO` | bool | Security check (exit if not defined) |
| `CHMOD_SAFE` | int | File permissions for cache files |
| `CHMOD_FILE` | int | File permissions for config cache |
| `CACHE_PAGE_DIR` | string | Page cache directory |
| `CACHE_SESSION_DIR` | string | Session cache directory |
| `CACHE_CONFIG_DIR` | string | Config cache directory |
| `CONFIG_DIR` | string | Configuration directory |
| `LANG_DIR` | string | Language files directory |
| `DAYSECS` | int | Seconds in a day (86400) |
| `HTTP_404` | string | Path to 404 error page |
| `HTTP_403` | string | Path to 403 error page |

## Workflow Examples
### Example 1: Handling a GET Request
`php	
`
### Example 2: Handling TLS/HTTPS Upgrade
`php	
`
### Example 3: Invalidating Cache After Page Edit
`php	
`
### Example 4: Serving a File
`php	
`

## Security Considerations
### 1. IP Address Spoofing
- Validates IPs against private ranges
- Filters proxy-provided IPs appropriately
- Configurable reverse proxy trust
### 2. Session Security
- Binds sessions to IP address
- Binds sessions to TLS status
- Supports both file and database storage
- HttpOnly cookies by default
### 3. TLS Enforcement
- Automatic HTTPS upgrade when configured
- Marks TLS sessions to prevent downgrade attacks
- HSTS header support
### 4. Content Security
- CSP headers to prevent XSS
- X-Frame-Options to prevent clickjacking
- X-Content-Type-Options to prevent MIME sniffing
- Referrer-Policy control
- Permissions-Policy for browser features
### 5. File Serving
- Validates file existence and readability
- Prevents directory traversal via `realpath()`
- Rejects symbolic links
- Special CSP for SVG and PDF files
### 6. Cache Security
- Cached only for anonymous users
- Disabled for sensitive operations (edit, watch)
- Only GET requests cached

## Performance Optimization
### 1. Page Caching
- Stores full HTML output
- TTL-based expiration
- Language and method-aware caching
- Conditional request support (304 Not Modified)
### 2. MIME Type Caching
- Loads MIME types once and caches
- Regenerates only when config changes
### 3. Session Options
- File-based sessions for simple deployments
- Database sessions for distributed systems
### 4. Compression
- Manual gzip implementation
- Proper Content-Length generation
- Only compresses appropriate sizes

## Debugging
`php	
`

## Related Classes
- Session Classes (`SessionFileStore`, `SessionDbalStore`) - Session management backends
- Database Class - Configuration and cache metadata storage
- Ut Utility Class - String/path utilities
- Diag Class - Diagnostic logging

## Version History
- Supports PHP 8.0+ (uses match expressions, union types)
- Follows RFC 9110 for HTTP header handling
- Modern cookie security practices

## Conclusion
The `Http` class is the central request/response handler in WackoWiki, managing everything from session initialization to security headers to file serving. Understanding this class is essential for:
- Extending WackoWiki with custom request handlers
- Implementing custom session logic
- Adding new security policies
- Optimizing cache strategies
- Debugging HTTP-related issues