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