Difference between revisions for Users / Eo Ny / dev




← Previous edit
Next edit →

Version1 Version2 Differences
1   == HTTP Class Technical Documentation ==
  1 {{toc numerate=1}}
2 2
3 3 === Overview ===
4 4
12 12
13 13 === Class Properties ===
14 14
15   ==== Public Properties ====
  15 ====Public Properties====
16 16
17 17 #|
18 18 *| Property | Type | Description |*
21 21 || ##$ip## | string | Client's real IP address (accounts for proxies) ||
22 22 || ##$sess## | Session | Reference to the Session object ||
23 23 || ##$method## | string | Current HTTP method/request type ||
24   || ==== Private Properties ==== ||
25   || Property | Type | Description ||
26   || ---------- | ------ | ------------- ||
  24 |#
  25
  26 ====Private Properties====
  27
  28 #|
  29 *| Property | Type | Description |*
27 30 || ##$db## | object | Database connection reference ||
28 31 || ##$tls_mark## | string | Cookie name for TLS session marking ||
29 32 || ##$page## | string | Current page name being processed ||
32 35 || ##$lang## | string | Current language code ||
33 36 || ##$file## | string | Cache file path ||
34 37 || ##$caching## | int | Flag indicating if page should be cached (0 or 1) ||
35   |
  38 |#
  39
  40 ----
  41 === Constructor ===
  42
  43 %%(hl php)
  44 public function __construct(&$db)
  45 %%
  46
  47 **Purpose:** Initializes the Http object and sets up HTTP session handling.
  48
  49 **Parameters:**
  50   - ##$db## - Database object reference
  51
  52 **Initialization Steps:**
  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 %%(hl php)
  62 $http = new Http($db);
  63 %%
  64
  65 ----
  66
  67 === Core Methods ===
  68
  69 ==== Session Management ====
  70
  71 ===== ##session($route): void## =====
  72 Initializes the session handler (file-based or database-based).
  73
  74 **Parameters:**
  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 %%(hl php)
  86 $http->session(0); // Normal session
  87 $http->session(2); // Static file serving mode
  88 %%
  89
  90 ----
  91
  92 ==== Caching System ====
  93
  94 ===== ##check_cache($page, $method): void## =====
  95 Determines if a page can be cached and prepares the cache check.
  96
  97 **Parameters:**
  98   - ##$page## (string) - Page name to cache
  99   - ##$method## (string) - Request method/action (e.g., 'show', 'edit')
  100
  101 **Caching Rules:**
  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 %%(hl php)
  109 $http->check_cache('HomePage', 'show');
  110 %%
  111
  112 ----
  113
  114 =====##store_cache(): void##=====
  115 Saves the generated page content to cache file.
  116
  117 **Features:**
  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 %%(hl php)
  125 // Called at end of page rendering
  126 $http->store_cache();
  127 %%
  128
  129 ----
  130
  131 ===== ##invalidate_page($page): int## =====
  132 Invalidates all cached versions of a page.
  133
  134 **Parameters:**
  135   - ##$page## (string) - Page name to invalidate
  136
  137 **Returns:**
  138   - Number of cache entries invalidated
  139
  140 **Process:**
  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 %%(hl php)
  148 $count = $http->invalidate_page('HomePage');
  149 echo "Invalidated $count cache entries";
  150 %%
  151
  152 ----
  153
  154 ==== TLS/HTTPS Security ====
  155
  156 ===== ##secure_base_url(): void## =====
  157 Switches base URL from HTTP to HTTPS.
  158
  159 **Purpose:**
  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 %%(hl php)
  166 $http->secure_base_url();
  167 // $db->base_url now uses https://
  168 %%
  169
  170 ----
  171
  172 ===== ##ensure_tls($url): void## =====
  173 Enforces HTTPS for a specific URL and redirects if necessary.
  174
  175 **Parameters:**
  176   - ##$url## (string) - URL to secure
  177
  178 **Behavior:**
  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 %%(hl php)
  185 $http->ensure_tls('/secure/payment');
  186 %%
  187
  188 ----
  189
  190 ==== IP Address Detection ====
  191
  192 ===== ##real_ip(): string## (Private) =====
  193 Detects client's real IP address accounting for proxies.
  194
  195 **Proxy Headers Checked (in order):**
  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
  206
  207 **Configuration in Database:**
  208   - ##reverse_proxy_addresses## - Comma/space-separated proxy IPs
  209   - ##reverse_proxy_header## - Custom header name (default: ##X-Forwarded-For##)
  210
  211 **Example:**
  212 %%(hl php)
  213 $client_ip = $http->ip; // e.g., "203.0.113.42"
  214 %%
  215
  216 ----
  217
  218 ==== HTTPS Detection ====
  219
  220 ===== ##tls_session(): bool## (Private) =====
  221 Detects if current connection uses HTTPS/TLS.
  222
  223 **Checks (any being true = HTTPS):**
  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
  236 Sets security-related HTTP headers.
  237
  238 **Headers Set:**
  239
  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 |#
  249
  250 **CSP Configuration Options:**
  251   - ##0## - Disabled
  252   - ##1## - Default policy (from ##csp.conf##)
  253   - ##2## - Custom policy (from ##csp_custom.conf##)
  254
  255 **Example:**
  256 %%(hl php)
  257 $http->http_security_headers();
  258 %%
  259
  260 ----
  261 ==== HTTP Methods ====
  262
  263 ===== ##redirect($url, $permanent = false): void## =====
  264 Performs an HTTP redirect.
  265
  266 **Parameters:**
  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 %%(hl php)
  277 $http->redirect('http://example.com/new-page', true); // 301
  278 $http->redirect('/wiki/HomePage'); // 302
  279 %%
  280
  281 ----
  282
  283 ===== ##terminate(): void## =====
  284 Safe exit/die with cleanup.
  285
  286 **Cleanup Operations:**
  287   - Saves diagnostic logs to session flash data
  288   - Ends script execution
  289
  290 **Example:**
  291 %%(hl php)
  292 $http->terminate();
  293 %%
  294
  295 ----
  296
  297 ===== ##status($code): void## =====
  298 Sets HTTP response status code.
  299
  300 **Supported Status Codes:**
  301 %%(hl php)
  302 200 => 'OK'
  303 206 => 'Partial Content'
  304 301 => 'Moved Permanently'
  305 302 => 'Moved Temporarily'
  306 304 => 'Not Modified'
  307 400 => 'Bad Request'
  308 401 => 'Unauthorized'
  309 403 => 'Forbidden'
  310 404 => 'Not Found'
  311 405 => 'Method Not Allowed'
  312 409 => 'Conflict'
  313 410 => 'Gone'
  314 416 => 'Requested Range Not Satisfiable'
  315 500 => 'Internal Server Error'
  316 501 => 'Not Implemented'
  317 503 => 'Service Unavailable'
  318 %%
  319
  320 **Example:**
  321 %%(hl php)
  322 $http->status(404); // Send 404 Not Found
  323 %%
  324
  325 ----
  326
  327 ==== Caching Control ====
  328
  329 ===== ##no_cache($client_only = true): void## =====
  330 Disables caching of the current page.
  331
  332 **Parameters:**
  333   - ##$client_only## (bool, default: TRUE)
  334   - ##TRUE##: Disable browser cache only
  335   - ##FALSE##: Disable both browser and server cache
  336
  337 **Headers Set:**
  338   - ##Last-Modified: <current-time>## (always fresh)
  339   - ##Cache-Control: no-store##
  340
  341 **Example:**
  342 %%(hl php)
  343 $http->no_cache(); // Client-side only
  344 $http->no_cache(false); // Both client & server
  345 %%
  346
  347 ----
  348
  349 ===== ##cache_promisc(): void## =====
  350 Marks page as publicly cacheable.
  351
  352 **Headers Set:**
  353   - ##Cache-Control: public##
  354
  355 **Example:**
  356 %%(hl php)
  357 $http->cache_promisc();
  358 %%
  359
  360 ----
  361
  362 ==== Language Negotiation ====
  363
  364 ===== ##user_agent_language(): string## =====
  365 Determines best language based on browser preferences.
  366
  367 **Features:**
  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
  372
  373 **Example Header:**
  374 %%
  375 Accept-Language: en-US,en;q=0.9,de;q=0.8
  376 %%
  377
  378 **Returns:**
  379   - Language code (e.g., 'en', 'en-US', 'de')
  380
  381 ----
  382
  383 ===== ##available_languages($subset = true): array## =====
  384 Returns list of available language translations.
  385
  386 **Parameters:**
  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
  396
  397 **Returns:**
  398   - Associative array: ##['en' => 'en', 'de' => 'de', ...]##
  399
  400 **Example:**
  401 %%(hl php)
  402 $all_langs = $http->available_languages(false);
  403 $allowed = $http->available_languages(true);
  404 %%
  405
  406 ----
  407
  408 ==== File Serving ====
  409
  410 ===== ##sendfile($path, $filename = null, $age = null): void## =====
  411 Serves files with proper HTTP headers and caching.
  412
  413 **Parameters:**
  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
  425
  426 **Special Paths:**
  427 %%(hl php)
  428 $http->sendfile(404); // Serves file defined by HTTP_404 constant
  429 $http->sendfile(403); // Serves file defined by HTTP_403 constant
  430 %%
  431
  432 **Example:**
  433 %%(hl php)
  434 $http->sendfile('uploads/document.pdf', 'my-document.pdf', 30);
  435 %%
  436
  437 ----
  438
  439 ===== ##mime_type($path): string## =====
  440 Returns MIME type for a file.
  441
  442 **Returns:**
  443   - MIME type string (e.g., 'application/pdf')
  444   - Default: ##'application/octet-stream'##
  445
  446 **Example:**
  447 %%(hl php)
  448 $mime = $http->mime_type('file.pdf'); // 'application/pdf'
  449 %%
  450
  451 ----
  452
  453 ===== ##mime_types(): array## (Private) =====
  454 Loads and caches MIME types from configuration.
  455
  456 **Features:**
  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## =====
  466 Compresses HTTP response with gzip/x-gzip.
  467
  468 **Features:**
  469   - Manually implements gzip (not relying on zlib.output_compression)
  470   - Produces correct ##Content-Length## header
  471   - Only compresses if:
  472   - 860 bytes < content < 1 MB
  473   - Client accepts compression
  474   - Headers not already sent
  475
  476 **Example:**
  477 %%(hl php)
  478 $http->gzip();
  479 %%
  480
  481 ----
  482
  483 ==== Utility Methods ====
  484
  485 ===== ##parse_str($str): array## (Private) =====
  486 Parses URL-encoded strings with special character handling.
  487
  488 **Purpose:**
  489   - Safely handles special characters in query/form data
  490   - Converts encoding properly
  491
  492 **Example:**
  493 %%(hl php)
  494 $data = $http->parse_str('name=John&age=30');
  495 %%
  496
  497 ----
  498
  499 ===== ##request_uri(): string## (Private) =====
  500 Extracts and normalizes REQUEST_URI from server.
  501
  502 **Normalization:**
  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) =====
  512 Removes prefix from path (case-insensitive).
  513
  514 ----
  515
  516 ===== ##get_header_conf($file_name): string## (Private) =====
  517 Loads security header configuration from files.
  518
  519 **Files Supported:**
  520   - ##csp.conf## / ##csp_custom.conf##
  521   - ##permissions_policy.conf## / ##permissions_policy_custom.conf##
  522
  523 ----
  524
  525 ===Configuration Dependencies===
  526
  527 The class relies on these database configuration settings:
  528
  529 #|
  530 *| Setting | Type | Purpose |*
  531 || ##base_url## | string | Wiki's base URL ||
  532 || ##tls## | bool | Enable HTTPS enforcement ||
  533 || ##cache## | bool | Enable page caching ||
  534 || ##cache_ttl## | int | Cache lifetime in seconds ||
  535 || ##session_store## | int | 1=File, 0=Database ||
  536 || ##system_seed_hash## | string | Session encryption seed ||
  537 || ##cookie_prefix## | string | Session cookie prefix ||
  538 || ##cookie_path## | string | Cookie path ||
  539 || ##allow_persistent_cookie## | bool | Allow persistent login ||
  540 || ##session_length## | int | Session lifetime in seconds ||
  541 || ##reverse_proxy_addresses## | string | Comma/space-separated proxy IPs ||
  542 || ##reverse_proxy_header## | string | Custom X-Forwarded header ||
  543 || ##language## | string | Default language code ||
  544 || ##multilanguage## | bool | Enable language negotiation ||
  545 || ##allowed_languages## | string | Comma/space-separated allowed langs ||
  546 || ##enable_security_headers## | bool | Send security headers ||
  547 || ##csp## | int | CSP setting (0/1/2) ||
  548 || ##permissions_policy## | int | Permissions-Policy setting (0/1/2) ||
  549 || ##referrer_policy## | int | Referrer-Policy setting (0-8) ||
  550 |#
  551
  552 ----
  553
  554 ===Constants Used===
  555
  556 #|
  557 *| Constant | Type | Purpose |*
  558 || ##IN_WACKO## | bool | Security check (exit if not defined) ||
  559 || ##CHMOD_SAFE## | int | File permissions for cache files ||
  560 || ##CHMOD_FILE## | int | File permissions for config cache ||
  561 || ##CACHE_PAGE_DIR## | string | Page cache directory ||
  562 || ##CACHE_SESSION_DIR## | string | Session cache directory ||
  563 || ##CACHE_CONFIG_DIR## | string | Config cache directory ||
  564 || ##CONFIG_DIR## | string | Configuration directory ||
  565 || ##LANG_DIR## | string | Language files directory ||
  566 || ##DAYSECS## | int | Seconds in a day (86400) ||
  567 || ##HTTP_404## | string | Path to 404 error page ||
  568 || ##HTTP_403## | string | Path to 403 error page ||
  569 |#
  570
  571 ----
  572
  573 === Workflow Examples ===
  574
  575 ====Example 1: Handling a GET Request====
  576
  577 %%(hl php)
  578 // In main wiki entry point
  579 $http = new Http($db);
  580 $http->session(0); // Start session
  581
  582 // Check if page can be served from cache
  583 $http->check_cache('HomePage', 'show');
  584
  585 // ... render page content ...
  586
  587 // Store rendered page in cache if applicable
  588 $http->store_cache();
  589
  590 // Send security headers
  591 $http->http_security_headers();
  592
  593 // Possibly compress output
  594 $http->gzip();
  595 %%
  596
  597 ==== Example 2: Handling TLS/HTTPS Upgrade ====
  598
  599 %%(hl php)
  600 $http = new Http($db); // Constructor detects TLS requirement
  601 // If TLS is enabled and user wasn't in TLS before:
  602 // - Sets TLS session flag
  603 // - Marks session with TLS cookie
  604 // - Redirects to HTTPS version
  605 %%
  606
  607 ==== Example 3: Invalidating Cache After Page Edit ====
  608
  609 %%(hl php)
  610 // User edits a page
  611 $http = new Http($db);
  612 $count = $http->invalidate_page('HomePage');
  613 // All cached versions (different languages, methods) are invalidated
  614 %%
  615
  616 ==== Example 4: Serving a File ====
  617
  618 %%(hl php)
  619 $http = new Http($db);
  620 $http->session(2); // Static file mode - no session replay prevention
  621
  622 // Serve with 30-day cache
  623 $http->sendfile('uploads/manual.pdf', 'user-manual.pdf', 30);
  624 %%
  625
  626 ----
  627
36 628 === Security Considerations ===
37 629
38 630 ==== 1. **IP Address Spoofing** ====
98 690
99 691 The class integrates with WackoWiki's diagnostic system:
100 692
101   %%php
  693 %%(hl php)
102 694 // Diagnostic messages are preserved across redirects
103 695 // via session flash data
104 696