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