getHeaderLine('Origin'); if (!empty($origin)) { $domain = parse_url($origin, PHP_URL_HOST); } else { $domain = $request->getHeaderLine('Host'); } $configPath = __DIR__ . '/../../config.json'; $config = file_exists($configPath) ? json_decode(file_get_contents($configPath), true) : []; $name = $config[$domain] ?? null; $params = (array)$request->getParsedBody(); if(!$name){ return $this->json($response, [ 'status' => 'not_found', 'message' => 'Container not found', ], 404); } $captcha = new PCaptcha(); if (!$captcha->validate_captcha($params['panswer'])) { return $this->json($response, ['status' => 'error', 'message' => 'Invalid CAPTCHA'], 400); } $lxd = new LxdService(); $status = $lxd->getContainerState($name)['metadata']['status'] ?? 'Stopped'; if ($status !== 'Running') { $lxd->startContainer($name); } // Write log LogWriterHelper::write($name, $request->getUri()); $redirect = '/waiting?name='.$name .'&redirect='.urlencode($params['redirect']); // Login success return $this->json($response, ['status' => 'success', 'message' => 'Container started!', 'redirect' => $redirect]); } catch (\Throwable $e) { return $this->json($response, [ 'status' => 'error', 'message' => $e->getMessage(), ], 500); } } public function status(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface { $queryParams = $request->getQueryParams(); $name = $queryParams['name'] ?? ''; if (empty($name)) { return $this->json($response, [ 'status' => 'error', 'message' => 'Missing container name.', ], 400); } $lxd = new LxdService(); $state = $lxd->getContainerState($name); if (!$state) { return $this->json($response, [ 'status' => 'not_found', 'message' => 'Container not found', ], 404); } $status = $state['metadata']['status'] ?? 'Stopped'; if ($status !== 'Running') { return $this->json($response, [ 'status' => 'starting', 'message' => 'Container is not yet running', ]); } $ip = $lxd->getContainerIP($name); $nginx = $lxd->isServiceRunning($name, 'nginx'); $mysql = $lxd->isServiceRunning($name, 'mysql'); if ($ip && $nginx === 'active' && $mysql === 'active') { return $this->json($response, [ 'status' => 'ready', 'ip' => $ip, 'message' => 'Container is ready', ]); } if($nginx === 'failed'){ return $this->json($response, [ 'status' => 'failed', 'message' => 'Failed to start web server service in container', ], 400); } if($mysql === 'failed'){ return $this->json($response, [ 'status' => 'failed', 'message' => 'Failed to start mysql service in container', ], 400); } return $this->json($response, [ 'status' => 'running', 'message' => 'Container is running, waiting for services...', ]); } /** * Sends a JSON response. */ protected function json($response, array $data, int $status = 200) { $payload = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); $response->getBody()->write($payload); return $response ->withHeader('Content-Type', 'application/json') ->withHeader('Access-Control-Allow-Origin', '*') ->withStatus($status); } }