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
Language: PHP
Dependencies: Database class, Session classes, Utility classes (
Ut), Diagnostics class (
Diag)
Class Properties
Public Properties
| Property |
Type |
Description |
|| $tls_session | bool | Indicates if
==== Private Properties ====
Constructor
php
public function __construct(&$db)
Purpose: Initializes the current Http object and sets up HTTP session uses HTTPS/TLS encryption
|
$request_uri | string | Normalized handling.
Parameters:
-
$db - Database object reference
Initialization Steps:
- Stores database reference
- Extracts and normalizes
REQUEST_URI (e.g., 'PageOfNoReturn/show?a=1')
|
$ip | string | Client's
3. Detects TLS/HTTPS session status
- Determines client's real IP address
(accounts for proxies)
|
$sess |
5. Sets up TLS mark cookie name
- Enforces TLS session upgrade if needed
Example:
php
$http = new Http($db);
Core Methods
Session | Reference to Management ====
session($route): void
Initializes the Session object
|
$method | string | Current HTTP method/request type
|
session handler (file-based or database-based).
Parameters:
Private Properties Caching System
|
Property | Type | Description
|
|
|
|
$db | object | Database connection reference
|
$tls_mark | string | Cookie
===== check_cache($page, $method): void =====
Determines if a page can be cached and prepares the cache check.
Parameters:
name to cache
$method (string) - Request method/action (e.g., 'show', 'edit')
Caching Rules:
✅ 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)
Example:
php
$http->check_cache('HomePage', 'show');
store_cache(): void
Saves the generated page content to cache file.
Features:
invalidate_page($page): int
Invalidates all cached versions of a page.
Parameters:
-
$page (string) - Page name to invalidate
Returns:
- Number of cache entries invalidated
Process:
- Finds all cached versions (different methods/languages)
- Touches files to past timestamp (faster than deletion)
- Removes entries from cache metadata table
- Returns count of invalidated caches
Example:
php
$count = $http->invalidate_page('HomePage');
echo "Invalidated $count cache entries";
TLS/HTTPS Security
secure_base_url(): void
Switches base URL from HTTP to HTTPS.
Purpose:
- Ensures all subsequent URLs use HTTPS
- Stores original HTTP URL for fallback
- Called when
TLS session marking
|
$page | string | Current page is detected
Example:
php
$http->secure_base_url();
// $db->base_url now uses https://
ensure_tls($url): void
Enforces HTTPS for a specific URL and redirects if necessary.
Parameters:
-
$url (string) - URL to secure
Behavior:
- If not already HTTPS and TLS is enabled, forces HTTPS redirect
- Handles both relative and absolute URLs
- Converts relative URLs using current server
name
<!markup:2:begin>Example:
php
$http->ensure_tls('/secure/payment');
IP Address Detection
real_ip(): string (Private)
Detects client's real IP address accounting for proxies.
Proxy Headers Checked (in order):
-
HTTP_X_CLUSTER_CLIENT_IP
-
HTTP_X_FORWARDED_FOR (or custom header)
-
HTTP_CLIENT_IP
-
HTTP_X_REMOTE_ADDR
-
REMOTE_ADDR (fallback)
Features:
HTTPS Detection
tls_session(): bool (Private)
Detects if current connection uses HTTPS/TLS.
**Checks (any<!markup:2:end> being processed
|
$hash | string | SHA1 hash true = HTTPS):**
-
$_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
HTTP Methods
redirect($url, $permanent = false): void
Performs an HTTP redirect.
Parameters:
terminate(): void
Safe exit/die with cleanup.
Cleanup Operations:
- Saves diagnostic logs to session flash data
- Ends script execution
Example:
php
$http->terminate();
status($code): void
Sets HTTP response status code.
Supported Status Codes:
php
200 => 'OK'
206 => 'Partial Content'
301 => 'Moved Permanently'
302 => 'Moved Temporarily'
304 => 'Not Modified'
400 => 'Bad Request'
401 => 'Unauthorized'
403 => 'Forbidden'
404 => 'Not Found'
405 => 'Method Not Allowed'
409 => 'Conflict'
410 => 'Gone'
416 => 'Requested Range Not Satisfiable'
500 => 'Internal Server Error'
501 => 'Not Implemented'
503 => 'Service Unavailable'
Example:
php
$http->status(404); // Send 404 Not Found
Caching Control
no_cache($client_only = true): void
Disables caching of the current page.
Parameters:
cache_promisc(): void
Marks page name
|
$query | string | Encoded query string
|
$lang | string | Current as publicly cacheable.
Headers Set:
Language Negotiation
user_agent_language(): string
Determines best language based on browser preferences.
Features:
code
|
$file | string | (e.g., 'en', 'en-US', 'de')
available_languages($subset = true): array
Returns list of available language translations.
Parameters:
File Serving
sendfile($path, $filename = null, $age = null): void
Serves files with proper HTTP headers and caching.
Parameters:
-
$path (string) - File path (or HTTP_XXX constant for error pages)
-
$filename (string, optional) - Custom download filename
-
$age (int, optional) -
Cache age in days
Features:
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
Special Paths:
php
$http->sendfile(404); // Serves file defined by HTTP_404 constant
$http->sendfile(403); // Serves file defined by HTTP_403 constant
Example:
php
$http->sendfile('uploads/document.pdf', 'my-document.pdf', 30);
mime_type($path): string
Returns MIME type for a file.
Returns:
mime_types(): array (Private)
Loads and caches MIME types from configuration.
Features:
- Reads from
config/mime.types
- Caches to
cache/config/mime.types
- Reloads if config is updated
Compression
gzip(): void
Compresses HTTP response with gzip/x-gzip.
Features:
- Manually implements gzip (not relying on zlib.output_compression)
- Produces correct
Content-Length header
- Only compresses if:
- 860 bytes < content < 1 MB
- Client accepts compression
- Headers not already sent
Example:
php
$http->gzip();
Utility Methods
parse_str($str): array (Private)
Parses URL-encoded strings with special character handling.
Purpose:
request_uri(): string (Private)
Extracts and normalizes REQUEST_URI from server.
Normalization:
- Removes base URL prefix
- Removes spaces
- Collapses multiple slashes
- Removes
..
path
|
$caching | int | Flag indicating traversal attempts
Removes leading/trailing slashes
cut_prefix($prefix, $path): string (Private)
Removes prefix from path (case-insensitive).
get_header_conf($file_name): string (Private)
Loads security header configuration from files.
Files Supported:
-
csp.conf / csp_custom.conf
-
permissions_policy.conf / permissions_policy_custom.conf
Configuration Dependencies
Constants Used
Workflow Examples
Example 1: Handling a GET Request
php
// In main wiki entry point
$http = new Http($db);
$http->session(0); // Start session
// Check<!--markup:2:end--> if page <!--markup:1:begin-->should<!--markup:1:end--> <!--markup:2:begin-->can<!--markup:2:end--> be <!--markup:2:begin-->served from cache
$http->check_cache('HomePage', 'show');
// ... render page content ...
// Store rendered page in cache if applicable
$http->store_cache();
// Send security headers
$http->http_security_headers();
// Possibly compress output
$http->gzip();
Example 2: Handling TLS/HTTPS Upgrade
php
$http = new Http($db); // Constructor detects TLS requirement
// If TLS is enabled and user wasn't in TLS before:
// - Sets TLS session flag
// - Marks session with TLS cookie
// - Redirects to HTTPS version
Example 3: Invalidating Cache After Page Edit
php
// User edits a page
$http = new Http($db);
$count = $http->invalidate_page('HomePage');
// All<!--markup:2:end--> cached <!--markup:1:begin-->(0 or 1) ||
|<!--markup:1:end--> <!--markup:2:begin-->versions (different languages, methods) are invalidated
Example 4: Serving a File
php
$http = new Http($db);
$http->session(2); // Static file mode - no session replay prevention
// Serve with 30-day cache
$http->sendfile('uploads/manual.pdf', 'user-manual.pdf', 30);
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
The class integrates with WackoWiki's diagnostic system:
php
// Diagnostic messages are preserved across redirects
// via session flash data
// Check cached pages (debug comments in output):
// <!-- WackoWiki Caching Engine: page cached at 2024-01-15 12:30:45 GMT -->
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