Difference between revisions for Users / Eo Ny / dev




← Previous edit
Next edit →

Version1 Version2
1 == HTTP Class Technical Documentation == 1 # HTTP Class Technical Documentation
2 2
3 === Overview === 3 ## Overview
4 4
5 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. 5 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.
6 6
7 **File Location:** ##src/class/http.php## 7 **File Location:** `src/class/http.php`
8 **Language:** PHP 8 **Language:** PHP
9 **Dependencies:** Database class, Session classes, Utility classes (##Ut##), Diagnostics class (##Diag##) 9 **Dependencies:** Database class, Session classes, Utility classes (`Ut`), Diagnostics class (`Diag`)
10 10
11 ---- 11 ---
12 12
13 === Class Properties === 13 ## Class Properties
14 14
15 ==== Public Properties ==== 15 ### Public Properties
16 16
17 #| 17 | Property | Type | Description |
18 *| Property | Type | Description |* 18 |----------|------|-------------|
19 || ##$tls_session## | bool | Indicates if the current session uses HTTPS/TLS encryption || 19 | `$tls_session` | bool | Indicates if the current session uses HTTPS/TLS encryption |
20 || ##$request_uri## | string | Normalized REQUEST_URI (e.g., 'PageOfNoReturn/show?a=1') || 20 | `$request_uri` | string | Normalized REQUEST_URI (e.g., 'PageOfNoReturn/show?a=1') |
21 || ##$ip## | string | Client's real IP address (accounts for proxies) || 21 | `$ip` | string | Client's real IP address (accounts for proxies) |
22 || ##$sess## | Session | Reference to the Session object || 22 | `$sess` | Session | Reference to the Session object |
23 || ##$method## | string | Current HTTP method/request type || 23 | `$method` | string | Current HTTP method/request type |
24 || ==== Private Properties ==== || 24
25 || Property | Type | Description || 25 ### Private Properties
26 || ---------- | ------ | ------------- || 26
27 || ##$db## | object | Database connection reference || 27 | Property | Type | Description |
28 || ##$tls_mark## | string | Cookie name for TLS session marking || 28 |----------|------|-------------|
29 || ##$page## | string | Current page name being processed || 29 | `$db` | object | Database connection reference |
30 || ##$hash## | string | SHA1 hash of the page name || 30 | `$tls_mark` | string | Cookie name for TLS session marking |
31 || ##$query## | string | Encoded query string || 31 | `$page` | string | Current page name being processed |
32 || ##$lang## | string | Current language code || 32 | `$hash` | string | SHA1 hash of the page name |
33 || ##$file## | string | Cache file path || 33 | `$query` | string | Encoded query string |
34 || ##$caching## | int | Flag indicating if page should be cached (0 or 1) || 34 | `$lang` | string | Current language code |
35 || ---- || 35 | `$file` | string | Cache file path |
36 || === Constructor === || 36 | `$caching` | int | Flag indicating if page should be cached (0 or 1) |
37 || %%php 37
    38 ---
    39
    40 ## Constructor
    41
    42 ```php
38 public function __construct(&$db) 43 public function __construct(&$db)
39 %% || 44 ```
40 || **Purpose:** Initializes the Http object and sets up HTTP session handling. || 45
41 || **Parameters:** || 46 **Purpose:** Initializes the Http object and sets up HTTP session handling.
42 || - ##$db## - Database object reference || 47
43 || **Initialization Steps:** || 48 **Parameters:**
44 || 1. Stores database reference || 49 - `$db` - Database object reference
45 || 2. Extracts and normalizes REQUEST_URI || 50
46 || 3. Detects TLS/HTTPS session status || 51 **Initialization Steps:**
47 || 4. Determines client's real IP address || 52 1. Stores database reference
48 || 5. Sets up TLS mark cookie name || 53 2. Extracts and normalizes REQUEST_URI
49 || 6. Enforces TLS session upgrade if needed || 54 3. Detects TLS/HTTPS session status
50 || **Example:** || 55 4. Determines client's real IP address
51 || %%php 56 5. Sets up TLS mark cookie name
    57 6. Enforces TLS session upgrade if needed
    58
    59 **Example:**
    60 ```php
52 $http = new Http($db); 61 $http = new Http($db);
53 %% || 62 ```
54 || ---- || 63
55 || === Core Methods === || 64 ---
56 || ==== Session Management ==== || 65
57 || ===== ##session($route): void## ===== || 66 ## Core Methods
58 || Initializes the session handler (file-based or database-based). || 67
59 || **Parameters:** || 68 ### Session Management
60 || - ##$route## (int) - Routing flag: || 69
61 || - Bit 2 (##$route & 2##): Enable static mode for files/freecap (disables replay prevention and ID regeneration) || 70 #### `session($route): void`
62 || **Features:** || 71 Initializes the session handler (file-based or database-based).
63 || - Selects storage backend (file or database) || 72
64 || - Configures cookie settings (security, path, httponly) || 73 **Parameters:**
65 || - Binds IP and TLS validation || 74 - `$route` (int) - Routing flag:
66 || - Recovers diagnostic logs from previous session || 75   - Bit 2 (`$route & 2`): Enable static mode for files/freecap (disables replay prevention and ID regeneration)
67 || **Example:** || 76
68 || %%php 77 **Features:**
    78 - Selects storage backend (file or database)
    79 - Configures cookie settings (security, path, httponly)
    80 - Binds IP and TLS validation
    81 - Recovers diagnostic logs from previous session
    82
    83 **Example:**
    84 ```php
69 $http->session(0); // Normal session 85 $http->session(0); // Normal session
70 $http->session(2); // Static file serving mode 86 $http->session(2); // Static file serving mode
71 %% || 87 ```
72 || ---- || 88
73 || ==== Caching System ==== || 89 ---
74 || ===== ##check_cache($page, $method): void## ===== || 90
75 || Determines if a page can be cached and prepares the cache check. || 91 ### Caching System
76 || **Parameters:** || 92
77 || - ##$page## (string) - Page name to cache || 93 #### `check_cache($page, $method): void`
78 || - ##$method## (string) - Request method/action (e.g., 'show', 'edit') || 94 Determines if a page can be cached and prepares the cache check.
79 || **Caching Rules:** || 95
80 || - ✅ Enabled for GET requests only || 96 **Parameters:**
81 || - ✅ Disabled for POST requests || 97 - `$page` (string) - Page name to cache
82 || - ❌ Never cached for 'edit' or 'watch' methods || 98 - `$method` (string) - Request method/action (e.g., 'show', 'edit')
83 || - ✅ Only cached for anonymous users (no logged-in users) || 99
84 || **Example:** || 100 **Caching Rules:**
85 || %%php 101 - ✅ Enabled for GET requests only
    102 - ✅ Disabled for POST requests
    103 - ❌ Never cached for 'edit' or 'watch' methods
    104 - ✅ Only cached for anonymous users (no logged-in users)
    105
    106 **Example:**
    107 ```php
86 $http->check_cache('HomePage', 'show'); 108 $http->check_cache('HomePage', 'show');
87 %% || 109 ```
88 || ---- || 110
89 || ===== ##store_cache(): void## ===== || 111 ---
90 || Saves the generated page content to cache file. || 112
91 || **Features:** || 113 #### `store_cache(): void`
92 || - Retrieves output buffer content || 114 Saves the generated page content to cache file.
93 || - Saves to cache file with proper permissions || 115
94 || - Records cache metadata in database || 116 **Features:**
95 || - Only executes if caching flag is set and user is anonymous || 117 - Retrieves output buffer content
96 || **Example:** || 118 - Saves to cache file with proper permissions
97 || %%php 119 - Records cache metadata in database
    120 - Only executes if caching flag is set and user is anonymous
    121
    122 **Example:**
    123 ```php
98 // Called at end of page rendering 124 // Called at end of page rendering
99 $http->store_cache(); 125 $http->store_cache();
100 %% || 126 ```
101 || ---- || 127
102 || ===== ##invalidate_page($page): int## ===== || 128 ---
103 || Invalidates all cached versions of a page. || 129
104 || **Parameters:** || 130 #### `invalidate_page($page): int`
105 || - ##$page## (string) - Page name to invalidate || 131 Invalidates all cached versions of a page.
106 || **Returns:** || 132
107 || - Number of cache entries invalidated || 133 **Parameters:**
108 || **Process:** || 134 - `$page` (string) - Page name to invalidate
109 || 1. Finds all cached versions (different methods/languages) || 135
110 || 2. Touches files to past timestamp (faster than deletion) || 136 **Returns:**
111 || 3. Removes entries from cache metadata table || 137 - Number of cache entries invalidated
112 || 4. Returns count of invalidated caches || 138
113 || **Example:** || 139 **Process:**
114 || %%php 140 1. Finds all cached versions (different methods/languages)
    141 2. Touches files to past timestamp (faster than deletion)
    142 3. Removes entries from cache metadata table
    143 4. Returns count of invalidated caches
    144
    145 **Example:**
    146 ```php
115 $count = $http->invalidate_page('HomePage'); 147 $count = $http->invalidate_page('HomePage');
116 echo "Invalidated $count cache entries"; 148 echo "Invalidated $count cache entries";
117 %% || 149 ```
118 || ---- || 150
119 || ==== TLS/HTTPS Security ==== || 151 ---
120 || ===== ##secure_base_url(): void## ===== || 152
121 || Switches base URL from HTTP to HTTPS. || 153 ### TLS/HTTPS Security
122 || **Purpose:** || 154
123 || - Ensures all subsequent URLs use HTTPS || 155 #### `secure_base_url(): void`
124 || - Stores original HTTP URL for fallback || 156 Switches base URL from HTTP to HTTPS.
125 || - Called when TLS session is detected || 157
126 || **Example:** || 158 **Purpose:**
127 || %%php 159 - Ensures all subsequent URLs use HTTPS
    160 - Stores original HTTP URL for fallback
    161 - Called when TLS session is detected
    162
    163 **Example:**
    164 ```php
128 $http->secure_base_url(); 165 $http->secure_base_url();
129 // $db->base_url now uses https:// 166 // $db->base_url now uses https://
130 %% || 167 ```
131 || ---- || 168
132 || ===== ##ensure_tls($url): void## ===== || 169 ---
133 || Enforces HTTPS for a specific URL and redirects if necessary. || 170
134 || **Parameters:** || 171 #### `ensure_tls($url): void`
135 || - ##$url## (string) - URL to secure || 172 Enforces HTTPS for a specific URL and redirects if necessary.
136 || **Behavior:** || 173
137 || - If not already HTTPS and TLS is enabled, forces HTTPS redirect || 174 **Parameters:**
138 || - Handles both relative and absolute URLs || 175 - `$url` (string) - URL to secure
139 || - Converts relative URLs using current server name || 176
140 || **Example:** || 177 **Behavior:**
141 || %%php 178 - If not already HTTPS and TLS is enabled, forces HTTPS redirect
    179 - Handles both relative and absolute URLs
    180 - Converts relative URLs using current server name
    181
    182 **Example:**
    183 ```php
142 $http->ensure_tls('/secure/payment'); 184 $http->ensure_tls('/secure/payment');
143 %% || 185 ```
144 || ---- || 186
145 || ==== IP Address Detection ==== || 187 ---
146 || ===== ##real_ip(): string## (Private) ===== || 188
147 || Detects client's real IP address accounting for proxies. || 189 ### IP Address Detection
148 || **Proxy Headers Checked (in order):** || 190
149 || 1. ##HTTP_X_CLUSTER_CLIENT_IP## || 191 #### `real_ip(): string` (Private)
150 || 2. ##HTTP_X_FORWARDED_FOR## (or custom header) || 192 Detects client's real IP address accounting for proxies.
151 || 3. ##HTTP_CLIENT_IP## || 193
152 || 4. ##HTTP_X_REMOTE_ADDR## || 194 **Proxy Headers Checked (in order):**
153 || 5. ##REMOTE_ADDR## (fallback) || 195 1. `HTTP_X_CLUSTER_CLIENT_IP`
154 || **Features:** || 196 2. `HTTP_X_FORWARDED_FOR` (or custom header)
155 || - Filters out private/reserved IP ranges || 197 3. `HTTP_CLIENT_IP`
156 || - Respects configured reverse proxy addresses || 198 4. `HTTP_X_REMOTE_ADDR`
157 || - Returns ##'0.0.0.0'## as fallback || 199 5. `REMOTE_ADDR` (fallback)
158 || **Configuration in Database:** || 200
159 || - ##reverse_proxy_addresses## - Comma/space-separated proxy IPs || 201 **Features:**
160 || - ##reverse_proxy_header## - Custom header name (default: ##X-Forwarded-For##) || 202 - Filters out private/reserved IP ranges
161 || **Example:** || 203 - Respects configured reverse proxy addresses
162 || %%php 204 - Returns `'0.0.0.0'` as fallback
    205
    206 **Configuration in Database:**
    207 - `reverse_proxy_addresses` - Comma/space-separated proxy IPs
    208 - `reverse_proxy_header` - Custom header name (default: `X-Forwarded-For`)
    209
    210 **Example:**
    211 ```php
163 $client_ip = $http->ip; // e.g., "203.0.113.42" 212 $client_ip = $http->ip; // e.g., "203.0.113.42"
164 %% || 213 ```
165 || ---- || 214
166 || ==== HTTPS Detection ==== || 215 ---
167 || ===== ##tls_session(): bool## (Private) ===== || 216
168 || Detects if current connection uses HTTPS/TLS. || 217 ### HTTPS Detection
169 || **Checks (any being true = HTTPS):** || 218
170 || - ##$_SERVER['HTTPS']## is 'on' || 219 #### `tls_session(): bool` (Private)
171 || - ##$_SERVER['SERVER_PORT']## is 443 || 220 Detects if current connection uses HTTPS/TLS.
172 || - ##$_SERVER['HTTP_X_FORWARDED_PROTO']## is 'https' || 221
173 || - ##$_SERVER['HTTP_X_FORWARDED_SSL']## is 'on' || 222 **Checks (any being true = HTTPS):**
174 || - ##$_SERVER['HTTP_X_FORWARDED_PORT']## is 443 || 223 - `$_SERVER['HTTPS']` is 'on'
175 || ---- || 224 - `$_SERVER['SERVER_PORT']` is 443
176 || ==== Security Headers ==== || 225 - `$_SERVER['HTTP_X_FORWARDED_PROTO']` is 'https'
177 || ===== ##http_security_headers(): void## ===== || 226 - `$_SERVER['HTTP_X_FORWARDED_SSL']` is 'on'
178 || Sets security-related HTTP headers. || 227 - `$_SERVER['HTTP_X_FORWARDED_PORT']` is 443
179 || **Headers Set:** || 228
180 || Header | Purpose | Config Key || 229 ---
181 || -------- | --------- | ------------ || 230
182 || Content-Security-Policy | XSS/injection protection | ##csp## || 231 ### Security Headers
183 || Permissions-Policy | Control browser features | ##permissions_policy## || 232
184 || Referrer-Policy | Control referrer information | ##referrer_policy## || 233 #### `http_security_headers(): void`
185 || Strict-Transport-Security | Force HTTPS | Auto (TLS only) || 234 Sets security-related HTTP headers.
186 || X-Frame-Options | Clickjacking protection | Hardcoded: ##SAMEORIGIN## || 235
187 || X-Content-Type-Options | MIME sniffing prevention | Hardcoded: ##nosniff## || 236 **Headers Set:**
188 || **CSP Configuration Options:** || 237
189 || - ##0## - Disabled || 238 | Header | Purpose | Config Key |
190 || - ##1## - Default policy (from ##csp.conf##) || 239 |--------|---------|------------|
191 || - ##2## - Custom policy (from ##csp_custom.conf##) || 240 | Content-Security-Policy | XSS/injection protection | `csp` |
192 || **Example:** || 241 | Permissions-Policy | Control browser features | `permissions_policy` |
193 || %%php 242 | Referrer-Policy | Control referrer information | `referrer_policy` |
    243 | Strict-Transport-Security | Force HTTPS | Auto (TLS only) |
    244 | X-Frame-Options | Clickjacking protection | Hardcoded: `SAMEORIGIN` |
    245 | X-Content-Type-Options | MIME sniffing prevention | Hardcoded: `nosniff` |
    246
    247 **CSP Configuration Options:**
    248 - `0` - Disabled
    249 - `1` - Default policy (from `csp.conf`)
    250 - `2` - Custom policy (from `csp_custom.conf`)
    251
    252 **Example:**
    253 ```php
194 $http->http_security_headers(); 254 $http->http_security_headers();
195 %% || 255 ```
196 || ---- || 256
197 || ==== HTTP Methods ==== || 257 ---
198 || ===== ##redirect($url, $permanent = false): void## ===== || 258
199 || Performs an HTTP redirect. || 259 ### HTTP Methods
200 || **Parameters:** || 260
201 || - ##$url## (string) - Target URL || 261 #### `redirect($url, $permanent = false): void`
202 || - ##$permanent## (bool) - Use 301 (permanent) vs 302 (temporary) || 262 Performs an HTTP redirect.
203 || **Features:** || 263
204 || - Decodes ##&## entities to prevent broken redirects || 264 **Parameters:**
205 || - Only works if headers not yet sent || 265 - `$url` (string) - Target URL
206 || - Uses output buffering to work anywhere in page processing || 266 - `$permanent` (bool) - Use 301 (permanent) vs 302 (temporary)
207 || **Example:** || 267
208 || %%php 268 **Features:**
    269 - Decodes `&` entities to prevent broken redirects
    270 - Only works if headers not yet sent
    271 - Uses output buffering to work anywhere in page processing
    272
    273 **Example:**
    274 ```php
209 $http->redirect('http://example.com/new-page', true); // 301 275 $http->redirect('http://example.com/new-page', true); // 301
210 $http->redirect('/wiki/HomePage'); // 302 276 $http->redirect('/wiki/HomePage'); // 302
211 %% || 277 ```
212 || ---- || 278
213 || ===== ##terminate(): void## ===== || 279 ---
214 || Safe exit/die with cleanup. || 280
215 || **Cleanup Operations:** || 281 #### `terminate(): void`
216 || - Saves diagnostic logs to session flash data || 282 Safe exit/die with cleanup.
217 || - Ends script execution || 283
218 || **Example:** || 284 **Cleanup Operations:**
219 || %%php 285 - Saves diagnostic logs to session flash data
    286 - Ends script execution
    287
    288 **Example:**
    289 ```php
220 $http->terminate(); 290 $http->terminate();
221 %% || 291 ```
222 || ---- || 292
223 || ===== ##status($code): void## ===== || 293 ---
224 || Sets HTTP response status code. || 294
225 || **Supported Status Codes:** || 295 #### `status($code): void`
226 || %%php 296 Sets HTTP response status code.
    297
    298 **Supported Status Codes:**
    299 ```php
227 200 => 'OK' 300 200 => 'OK'
228 206 => 'Partial Content' 301 206 => 'Partial Content'
229 301 => 'Moved Permanently' 302 301 => 'Moved Permanently'
240 500 => 'Internal Server Error' 313 500 => 'Internal Server Error'
241 501 => 'Not Implemented' 314 501 => 'Not Implemented'
242 503 => 'Service Unavailable' 315 503 => 'Service Unavailable'
243 %% || 316 ```
244 || **Example:** || 317
245 || %%php 318 **Example:**
    319 ```php
246 $http->status(404); // Send 404 Not Found 320 $http->status(404); // Send 404 Not Found
247 %% || 321 ```
248 || ---- || 322
249 || ==== Caching Control ==== || 323 ---
250 || ===== ##no_cache($client_only = true): void## ===== || 324
251 || Disables caching of the current page. || 325 ### Caching Control
252 || **Parameters:** || 326
253 || - ##$client_only## (bool, default: TRUE) || 327 #### `no_cache($client_only = true): void`
254 || - ##TRUE##: Disable browser cache only || 328 Disables caching of the current page.
255 || - ##FALSE##: Disable both browser and server cache || 329
256 || **Headers Set:** || 330 **Parameters:**
257 || - ##Last-Modified: <current-time>## (always fresh) || 331 - `$client_only` (bool, default: TRUE)
258 || - ##Cache-Control: no-store## || 332   - `TRUE`: Disable browser cache only
259 || **Example:** || 333   - `FALSE`: Disable both browser and server cache
260 || %%php 334
    335 **Headers Set:**
    336 - `Last-Modified: <current-time>` (always fresh)
    337 - `Cache-Control: no-store`
    338
    339 **Example:**
    340 ```php
261 $http->no_cache(); // Client-side only 341 $http->no_cache(); // Client-side only
262 $http->no_cache(false); // Both client & server 342 $http->no_cache(false); // Both client & server
263 %% || 343 ```
264 || ---- || 344
265 || ===== ##cache_promisc(): void## ===== || 345 ---
266 || Marks page as publicly cacheable. || 346
267 || **Headers Set:** || 347 #### `cache_promisc(): void`
268 || - ##Cache-Control: public## || 348 Marks page as publicly cacheable.
269 || **Example:** || 349
270 || %%php 350 **Headers Set:**
    351 - `Cache-Control: public`
    352
    353 **Example:**
    354 ```php
271 $http->cache_promisc(); 355 $http->cache_promisc();
272 %% || 356 ```
273 || ---- || 357
274 || ==== Language Negotiation ==== || 358 ---
275 || ===== ##user_agent_language(): string## ===== || 359
276 || Determines best language based on browser preferences. || 360 ### Language Negotiation
277 || **Features:** || 361
278 || - Follows RFC 9110 section 12.5.4 (HTTP Accept-Language) || 362 #### `user_agent_language(): string`
279 || - Parses ##Accept-Language## header with quality factors || 363 Determines best language based on browser preferences.
280 || - Attempts exact match first, then language fallback || 364
281 || - Falls back to default system language || 365 **Features:**
282 || **Example Header:** || 366 - Follows RFC 9110 section 12.5.4 (HTTP Accept-Language)
283 || %% 367 - Parses `Accept-Language` header with quality factors
    368 - Attempts exact match first, then language fallback
    369 - Falls back to default system language
    370
    371 **Example Header:**
    372 ```
284 Accept-Language: en-US,en;q=0.9,de;q=0.8 373 Accept-Language: en-US,en;q=0.9,de;q=0.8
285 %% || 374 ```
286 || **Returns:** || 375
287 || - Language code (e.g., 'en', 'en-US', 'de') || 376 **Returns:**
288 || ---- || 377 - Language code (e.g., 'en', 'en-US', 'de')
289 || ===== ##available_languages($subset = true): array## ===== || 378
290 || Returns list of available language translations. || 379 ---
291 || **Parameters:** || 380
292 || - ##$subset## (bool, default: TRUE) || 381 #### `available_languages($subset = true): array`
293 || - ##TRUE##: Only allowed languages || 382 Returns list of available language translations.
294 || - ##FALSE##: All available languages || 383
295 || **Features:** || 384 **Parameters:**
296 || - Scans ##LANG_DIR## for language files || 385 - `$subset` (bool, default: TRUE)
297 || - Filters by ##allowed_languages## config if set || 386   - `TRUE`: Only allowed languages
298 || - Caches result in session || 387   - `FALSE`: All available languages
299 || - System language always included || 388
300 || **Returns:** || 389 **Features:**
301 || - Associative array: ##['en' => 'en', 'de' => 'de', ...]## || 390 - Scans `LANG_DIR` for language files
302 || **Example:** || 391 - Filters by `allowed_languages` config if set
303 || %%php 392 - Caches result in session
    393 - System language always included
    394
    395 **Returns:**
    396 - Associative array: `['en' => 'en', 'de' => 'de', ...]`
    397
    398 **Example:**
    399 ```php
304 $all_langs = $http->available_languages(false); 400 $all_langs = $http->available_languages(false);
305 $allowed = $http->available_languages(true); 401 $allowed = $http->available_languages(true);
306 %% || 402 ```
307 || ---- || 403
308 || ==== File Serving ==== || 404 ---
309 || ===== ##sendfile($path, $filename = null, $age = null): void## ===== || 405
310 || Serves files with proper HTTP headers and caching. || 406 ### File Serving
311 || **Parameters:** || 407
312 || - ##$path## (string) - File path (or HTTP_XXX constant for error pages) || 408 #### `sendfile($path, $filename = null, $age = null): void`
313 || - ##$filename## (string, optional) - Custom download filename || 409 Serves files with proper HTTP headers and caching.
314 || - ##$age## (int, optional) - Cache age in days || 410
315 || **Features:** || 411 **Parameters:**
316 || - HTTP range request support (partial file downloads) || 412 - `$path` (string) - File path (or HTTP_XXX constant for error pages)
317 || - ETag and Last-Modified conditional requests || 413 - `$filename` (string, optional) - Custom download filename
318 || - Proper MIME type detection || 414 - `$age` (int, optional) - Cache age in days
319 || - Content-Security-Policy for special file types || 415
320 || - Streaming for large files || 416 **Features:**
321 || - GZip compression for text files || 417 - HTTP range request support (partial file downloads)
322 || **Special Paths:** || 418 - ETag and Last-Modified conditional requests
323 || %%php 419 - Proper MIME type detection
    420 - Content-Security-Policy for special file types
    421 - Streaming for large files
    422 - GZip compression for text files
    423
    424 **Special Paths:**
    425 ```php
324 $http->sendfile(404); // Serves file defined by HTTP_404 constant 426 $http->sendfile(404); // Serves file defined by HTTP_404 constant
325 $http->sendfile(403); // Serves file defined by HTTP_403 constant 427 $http->sendfile(403); // Serves file defined by HTTP_403 constant
326 %% || 428 ```
327 || **Example:** || 429
328 || %%php 430 **Example:**
    431 ```php
329 $http->sendfile('uploads/document.pdf', 'my-document.pdf', 30); 432 $http->sendfile('uploads/document.pdf', 'my-document.pdf', 30);
330 %% || 433 ```
331 || ---- || 434
332 || ===== ##mime_type($path): string## ===== || 435 ---
333 || Returns MIME type for a file. || 436
334 || **Returns:** || 437 #### `mime_type($path): string`
335 || - MIME type string (e.g., 'application/pdf') || 438 Returns MIME type for a file.
336 || - Default: ##'application/octet-stream'## || 439
337 || **Example:** || 440 **Returns:**
338 || %%php 441 - MIME type string (e.g., 'application/pdf')
    442 - Default: `'application/octet-stream'`
    443
    444 **Example:**
    445 ```php
339 $mime = $http->mime_type('file.pdf'); // 'application/pdf' 446 $mime = $http->mime_type('file.pdf'); // 'application/pdf'
340 %% || 447 ```
341 || ---- || 448
342 || ===== ##mime_types(): array## (Private) ===== || 449 ---
343 || Loads and caches MIME types from configuration. || 450
344 || **Features:** || 451 #### `mime_types(): array` (Private)
345 || - Reads from ##config/mime.types## || 452 Loads and caches MIME types from configuration.
346 || - Caches to ##cache/config/mime.types## || 453
347 || - Reloads if config is updated || 454 **Features:**
348 || ---- || 455 - Reads from `config/mime.types`
349 || ==== Compression ==== || 456 - Caches to `cache/config/mime.types`
350 || ===== ##gzip(): void## ===== || 457 - Reloads if config is updated
351 || Compresses HTTP response with gzip/x-gzip. || 458
352 || **Features:** || 459 ---
353 || - Manually implements gzip (not relying on zlib.output_compression) || 460
354 || - Produces correct ##Content-Length## header || 461 ### Compression
355 || - Only compresses if: || 462
356 || - 860 bytes < content < 1 MB || 463 #### `gzip(): void`
357 || - Client accepts compression || 464 Compresses HTTP response with gzip/x-gzip.
358 || - Headers not already sent || 465
359 || **Example:** || 466 **Features:**
360 || %%php 467 - Manually implements gzip (not relying on zlib.output_compression)
    468 - Produces correct `Content-Length` header
    469 - Only compresses if:
    470   - 860 bytes < content < 1 MB
    471   - Client accepts compression
    472   - Headers not already sent
    473
    474 **Example:**
    475 ```php
361 $http->gzip(); 476 $http->gzip();
362 %% || 477 ```
363 || ---- || 478
364 || ==== Utility Methods ==== || 479 ---
365 || ===== ##parse_str($str): array## (Private) ===== || 480
366 || Parses URL-encoded strings with special character handling. || 481 ### Utility Methods
367 || **Purpose:** || 482
368 || - Safely handles special characters in query/form data || 483 #### `parse_str($str): array` (Private)
369 || - Converts encoding properly || 484 Parses URL-encoded strings with special character handling.
370 || **Example:** || 485
371 || %%php 486 **Purpose:**
    487 - Safely handles special characters in query/form data
    488 - Converts encoding properly
    489
    490 **Example:**
    491 ```php
372 $data = $http->parse_str('name=John&age=30'); 492 $data = $http->parse_str('name=John&age=30');
373 %% || 493 ```
374 || ---- || 494
375 || ===== ##request_uri(): string## (Private) ===== || 495 ---
376 || Extracts and normalizes REQUEST_URI from server. || 496
377 || **Normalization:** || 497 #### `request_uri(): string` (Private)
378 || - Removes base URL prefix || 498 Extracts and normalizes REQUEST_URI from server.
379 || - Removes spaces || 499
380 || - Collapses multiple slashes || 500 **Normalization:**
381 || - Removes ##..## path traversal attempts || 501 - Removes base URL prefix
382 || - Removes leading/trailing slashes || 502 - Removes spaces
383 || ---- || 503 - Collapses multiple slashes
384 || ===== ##cut_prefix($prefix, $path): string## (Private) ===== || 504 - Removes `..` path traversal attempts
385 || Removes prefix from path (case-insensitive). || 505 - Removes leading/trailing slashes
386 || ---- || 506
387 || ===== ##get_header_conf($file_name): string## (Private) ===== || 507 ---
388 || Loads security header configuration from files. || 508
389 || **Files Supported:** || 509 #### `cut_prefix($prefix, $path): string` (Private)
390 || - ##csp.conf## / ##csp_custom.conf## || 510 Removes prefix from path (case-insensitive).
391 || - ##permissions_policy.conf## / ##permissions_policy_custom.conf## || 511
392 || ---- || 512 ---
393 || === Configuration Dependencies === || 513
394 || The class relies on these database configuration settings: || 514 #### `get_header_conf($file_name): string` (Private)
395 || Setting | Type | Purpose || 515 Loads security header configuration from files.
396 || --------- | ------ | --------- || 516
397 || ##base_url## | string | Wiki's base URL || 517 **Files Supported:**
398 || ##tls## | bool | Enable HTTPS enforcement || 518 - `csp.conf` / `csp_custom.conf`
399 || ##cache## | bool | Enable page caching || 519 - `permissions_policy.conf` / `permissions_policy_custom.conf`
400 || ##cache_ttl## | int | Cache lifetime in seconds || 520
401 || ##session_store## | int | 1=File, 0=Database || 521 ---
402 || ##system_seed_hash## | string | Session encryption seed || 522
403 || ##cookie_prefix## | string | Session cookie prefix || 523 ## Configuration Dependencies
404 || ##cookie_path## | string | Cookie path || 524
405 || ##allow_persistent_cookie## | bool | Allow persistent login || 525 The class relies on these database configuration settings:
406 || ##session_length## | int | Session lifetime in seconds || 526
407 || ##reverse_proxy_addresses## | string | Comma/space-separated proxy IPs || 527 | Setting | Type | Purpose |
408 || ##reverse_proxy_header## | string | Custom X-Forwarded header || 528 |---------|------|---------|
409 || ##language## | string | Default language code || 529 | `base_url` | string | Wiki's base URL |
410 || ##multilanguage## | bool | Enable language negotiation || 530 | `tls` | bool | Enable HTTPS enforcement |
411 || ##allowed_languages## | string | Comma/space-separated allowed langs || 531 | `cache` | bool | Enable page caching |
412 || ##enable_security_headers## | bool | Send security headers || 532 | `cache_ttl` | int | Cache lifetime in seconds |
413 || ##csp## | int | CSP setting (0/1/2) || 533 | `session_store` | int | 1=File, 0=Database |
414 || ##permissions_policy## | int | Permissions-Policy setting (0/1/2) || 534 | `system_seed_hash` | string | Session encryption seed |
415 || ##referrer_policy## | int | Referrer-Policy setting (0-8) || 535 | `cookie_prefix` | string | Session cookie prefix |
416 || ---- || 536 | `cookie_path` | string | Cookie path |
417 || === Constants Used === || 537 | `allow_persistent_cookie` | bool | Allow persistent login |
418 || Constant | Type | Purpose || 538 | `session_length` | int | Session lifetime in seconds |
419 || ---------- | ------ | --------- || 539 | `reverse_proxy_addresses` | string | Comma/space-separated proxy IPs |
420 || ##IN_WACKO## | bool | Security check (exit if not defined) || 540 | `reverse_proxy_header` | string | Custom X-Forwarded header |
421 || ##CHMOD_SAFE## | int | File permissions for cache files || 541 | `language` | string | Default language code |
422 || ##CHMOD_FILE## | int | File permissions for config cache || 542 | `multilanguage` | bool | Enable language negotiation |
423 || ##CACHE_PAGE_DIR## | string | Page cache directory || 543 | `allowed_languages` | string | Comma/space-separated allowed langs |
424 || ##CACHE_SESSION_DIR## | string | Session cache directory || 544 | `enable_security_headers` | bool | Send security headers |
425 || ##CACHE_CONFIG_DIR## | string | Config cache directory || 545 | `csp` | int | CSP setting (0/1/2) |
426 || ##CONFIG_DIR## | string | Configuration directory || 546 | `permissions_policy` | int | Permissions-Policy setting (0/1/2) |
427 || ##LANG_DIR## | string | Language files directory || 547 | `referrer_policy` | int | Referrer-Policy setting (0-8) |
428 || ##DAYSECS## | int | Seconds in a day (86400) || 548
429 || ##HTTP_404## | string | Path to 404 error page || 549 ---
430 || ##HTTP_403## | string | Path to 403 error page || 550
431 |# 551 ## Constants Used
432 552
433 ---- 553 | Constant | Type | Purpose |
434 554 |----------|------|---------|
435 === Workflow Examples === 555 | `IN_WACKO` | bool | Security check (exit if not defined) |
436 556 | `CHMOD_SAFE` | int | File permissions for cache files |
437 ==== Example 1: Handling a GET Request ==== 557 | `CHMOD_FILE` | int | File permissions for config cache |
438 558 | `CACHE_PAGE_DIR` | string | Page cache directory |
439 %%php 559 | `CACHE_SESSION_DIR` | string | Session cache directory |
    560 | `CACHE_CONFIG_DIR` | string | Config cache directory |
    561 | `CONFIG_DIR` | string | Configuration directory |
    562 | `LANG_DIR` | string | Language files directory |
    563 | `DAYSECS` | int | Seconds in a day (86400) |
    564 | `HTTP_404` | string | Path to 404 error page |
    565 | `HTTP_403` | string | Path to 403 error page |
    566
    567 ---
    568
    569 ## Workflow Examples
    570
    571 ### Example 1: Handling a GET Request
    572
    573 ```php
440 // In main wiki entry point 574 // In main wiki entry point
441 $http = new Http($db); 575 $http = new Http($db);
442 $http->session(0); // Start session 576 $http->session(0); // Start session
454 588
455 // Possibly compress output 589 // Possibly compress output
456 $http->gzip(); 590 $http->gzip();
457 %% 591 ```
458 592
459 ==== Example 2: Handling TLS/HTTPS Upgrade ==== 593 ### Example 2: Handling TLS/HTTPS Upgrade
460 594
461 %%php 595 ```php
462 $http = new Http($db); // Constructor detects TLS requirement 596 $http = new Http($db); // Constructor detects TLS requirement
463 // If TLS is enabled and user wasn't in TLS before: 597 // If TLS is enabled and user wasn't in TLS before:
464 // - Sets TLS session flag 598 // - Sets TLS session flag
465 // - Marks session with TLS cookie 599 // - Marks session with TLS cookie
466 // - Redirects to HTTPS version 600 // - Redirects to HTTPS version
467 %% 601 ```
468 602
469 ==== Example 3: Invalidating Cache After Page Edit ==== 603 ### Example 3: Invalidating Cache After Page Edit
470 604
471 %%php 605 ```php
472 // User edits a page 606 // User edits a page
473 $http = new Http($db); 607 $http = new Http($db);
474 $count = $http->invalidate_page('HomePage'); 608 $count = $http->invalidate_page('HomePage');
475 // All cached versions (different languages, methods) are invalidated 609 // All cached versions (different languages, methods) are invalidated
476 %% 610 ```
477 611
478 ==== Example 4: Serving a File ==== 612 ### Example 4: Serving a File
479 613
480 %%php 614 ```php
481 $http = new Http($db); 615 $http = new Http($db);
482 $http->session(2); // Static file mode - no session replay prevention 616 $http->session(2); // Static file mode - no session replay prevention
483 617
484 // Serve with 30-day cache 618 // Serve with 30-day cache
485 $http->sendfile('uploads/manual.pdf', 'user-manual.pdf', 30); 619 $http->sendfile('uploads/manual.pdf', 'user-manual.pdf', 30);
486 %% 620 ```
487 621
488 ---- 622 ---
489 623
490 === Security Considerations === 624 ## Security Considerations
491 625
492 ==== 1. **IP Address Spoofing** ==== 626 ### 1. **IP Address Spoofing**
493   - Validates IPs against private ranges 627 - Validates IPs against private ranges
494   - Filters proxy-provided IPs appropriately 628 - Filters proxy-provided IPs appropriately
495   - Configurable reverse proxy trust 629 - Configurable reverse proxy trust
496 630
497 ==== 2. **Session Security** ==== 631 ### 2. **Session Security**
498   - Binds sessions to IP address 632 - Binds sessions to IP address
499   - Binds sessions to TLS status 633 - Binds sessions to TLS status
500   - Supports both file and database storage 634 - Supports both file and database storage
501   - HttpOnly cookies by default 635 - HttpOnly cookies by default
502 636
503 ==== 3. **TLS Enforcement** ==== 637 ### 3. **TLS Enforcement**
504   - Automatic HTTPS upgrade when configured 638 - Automatic HTTPS upgrade when configured
505   - Marks TLS sessions to prevent downgrade attacks 639 - Marks TLS sessions to prevent downgrade attacks
506   - HSTS header support 640 - HSTS header support
507 641
508 ==== 4. **Content Security** ==== 642 ### 4. **Content Security**
509   - CSP headers to prevent XSS 643 - CSP headers to prevent XSS
510   - X-Frame-Options to prevent clickjacking 644 - X-Frame-Options to prevent clickjacking
511   - X-Content-Type-Options to prevent MIME sniffing 645 - X-Content-Type-Options to prevent MIME sniffing
512   - Referrer-Policy control 646 - Referrer-Policy control
513   - Permissions-Policy for browser features 647 - Permissions-Policy for browser features
514 648
515 ==== 5. **File Serving** ==== 649 ### 5. **File Serving**
516   - Validates file existence and readability 650 - Validates file existence and readability
517   - Prevents directory traversal via ##realpath()## 651 - Prevents directory traversal via `realpath()`
518   - Rejects symbolic links 652 - Rejects symbolic links
519   - Special CSP for SVG and PDF files 653 - Special CSP for SVG and PDF files
520 654
521 ==== 6. **Cache Security** ==== 655 ### 6. **Cache Security**
522   - Cached only for anonymous users 656 - Cached only for anonymous users
523   - Disabled for sensitive operations (edit, watch) 657 - Disabled for sensitive operations (edit, watch)
524   - Only GET requests cached 658 - Only GET requests cached
525 659
526 ---- 660 ---
527 661
528 === Performance Optimization === 662 ## Performance Optimization
529 663
530 ==== 1. **Page Caching** ==== 664 ### 1. **Page Caching**
531   - Stores full HTML output 665 - Stores full HTML output
532   - TTL-based expiration 666 - TTL-based expiration
533   - Language and method-aware caching 667 - Language and method-aware caching
534   - Conditional request support (304 Not Modified) 668 - Conditional request support (304 Not Modified)
535 669
536 ==== 2. **MIME Type Caching** ==== 670 ### 2. **MIME Type Caching**
537   - Loads MIME types once and caches 671 - Loads MIME types once and caches
538   - Regenerates only when config changes 672 - Regenerates only when config changes
539 673
540 ==== 3. **Session Options** ==== 674 ### 3. **Session Options**
541   - File-based sessions for simple deployments 675 - File-based sessions for simple deployments
542   - Database sessions for distributed systems 676 - Database sessions for distributed systems
543 677
544 ==== 4. **Compression** ==== 678 ### 4. **Compression**
545   - Manual gzip implementation 679 - Manual gzip implementation
546   - Proper Content-Length generation 680 - Proper Content-Length generation
547   - Only compresses appropriate sizes 681 - Only compresses appropriate sizes
548 682
549 ---- 683 ---
550 684
551 === Debugging === 685 ## Debugging
552 686
553 The class integrates with WackoWiki's diagnostic system: 687 The class integrates with WackoWiki's diagnostic system:
554 688
555 %%php 689 ```php
556 // Diagnostic messages are preserved across redirects 690 // Diagnostic messages are preserved across redirects
557 // via session flash data 691 // via session flash data
558 692
559 // Check cached pages (debug comments in output): 693 // Check cached pages (debug comments in output):
560 // <!-- WackoWiki Caching Engine: page cached at 2024-01-15 12:30:45 GMT --> 694 // <!-- WackoWiki Caching Engine: page cached at 2024-01-15 12:30:45 GMT -->
561 %% 695 ```
562 696
563 ---- 697 ---
564 698
565 === Related Classes === 699 ## Related Classes
566   - **Session Classes** (##SessionFileStore##, ##SessionDbalStore##) - Session management backends 700
567   - **Database Class** - Configuration and cache metadata storage 701 - **Session Classes** (`SessionFileStore`, `SessionDbalStore`) - Session management backends
568   - **Ut Utility Class** - String/path utilities 702 - **Database Class** - Configuration and cache metadata storage
569   - **Diag Class** - Diagnostic logging 703 - **Ut Utility Class** - String/path utilities
570 704 - **Diag Class** - Diagnostic logging
571 ---- 705
572 706 ---
573 === Version History === 707
574   - Supports PHP 8.0+ (uses match expressions, union types) 708 ## Version History
575   - Follows RFC 9110 for HTTP header handling 709
576   - Modern cookie security practices 710 - Supports PHP 8.0+ (uses match expressions, union types)
577 711 - Follows RFC 9110 for HTTP header handling
578 ---- 712 - Modern cookie security practices
579 713
580 === Conclusion === 714 ---
581 715
582 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: 716 ## Conclusion
583   - Extending WackoWiki with custom request handlers 717
584   - Implementing custom session logic 718 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:
585   - Adding new security policies 719
586   - Optimizing cache strategies 720 - Extending WackoWiki with custom request handlers
587   - Debugging HTTP-related issues 721 - Implementing custom session logic
    722 - Adding new security policies
    723 - Optimizing cache strategies
    724 - Debugging HTTP-related issues