Difference between revisions for Users / Eo Ny / dev




← Previous edit
Next edit →

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