query->get('action') ?? $request->request->get('action'); $this->logger->info('Legacy API call', [ 'action' => $action, 'method' => $request->getMethod(), 'ip' => $request->getClientIp(), ]); return match ($action) { 'messageNew' => $this->messageNew($request), 'messageGet' => $this->messageGet($request), 'againOptions' => $this->againOptions($request), 'getProfile' => $this->getProfile($request), 'getWidgets' => $this->getWidgets($request), 'createApiKey' => $this->createApiKey($request), 'saveWidget' => $this->saveWidget($request), 'promptUpdate' => $this->promptUpdate($request), 'sendEmail' => $this->sendEmail($request), 'verifyEmail' => $this->verifyEmail($request), 'chatStream' => $this->chatStream($request), 'ragUpload' => $this->ragUpload($request), 'wpWizardComplete' => $this->wpWizardComplete($request), 'wpStep1VerifyAndCreateUser' => $this->wpStep1($request), 'wpStep2CreateApiKey' => $this->wpStep2($request), 'wpStep3UploadFile' => $this->wpStep3($request), 'wpStep4EnableFileSearch' => $this->wpStep4($request), 'wpStep5SaveWidget' => $this->wpStep5($request), default => $this->error('Unknown action: '.$action, 404), }; } /** * Legacy: messageNew * → Neues System: POST /api/messages/send. */ private function messageNew(Request $request): JsonResponse { try { $userId = $this->authenticatedUserId(); if (null === $userId) { return $this->error('User not authenticated', 401); } $messageText = $request->query->get('message') ?? $request->request->get('message') ?? $request->query->get('text') ?? $request->request->get('text') ?? ''; $widgetId = $request->query->get('widget_id') ?? $request->request->get('widget_id') ?? $request->getSession()->get('widget_id'); if (empty($messageText)) { return $this->error('Message text cannot be empty', 400); } return $this->acceptLegacyMessage($userId, $messageText); } catch (\Exception $e) { $this->logger->error('Legacy messageNew failed', [ 'error' => $e->getMessage(), 'trace' => $e->getTraceAsString(), ]); return $this->error($e->getMessage(), 500); } } private function acceptLegacyMessage(int $userId, string $messageText): JsonResponse { $message = new Message(); $message->setUserId($userId); $message->setText($messageText); $message->setDirect('IN'); $message->setStatus('NEW'); $message->setUnixTimestamp(time()); $message->setDatetime(date('YmdHis')); $message->setMessType('WEB'); $message->setTrackId(time()); $this->preProcessor->process($message); $this->messageRepository->save($message); $this->classifier->classify($message); $this->messageRepository->save($message); $aiResponse = $this->inferenceRouter->route($message); $this->messageRepository->save($aiResponse); return new JsonResponse([ 'success' => true, 'tracking_id' => 'msg_'.$message->getId(), 'message_id' => $message->getId(), 'response_id' => $aiResponse->getId(), 'response' => $aiResponse->getText(), 'status' => 'completed', 'timestamp' => time(), ]); } /** * Legacy: messageGet * Holt Message by ID or Tracking-ID. */ private function messageGet(Request $request): JsonResponse { $userId = $this->authenticatedUserId(); if (null === $userId) { return $this->error('User not authenticated', 401); } $messageId = $request->query->get('message_id') ?? $request->request->get('message_id') ?? $request->query->get('id') ?? $request->request->get('id'); $trackingId = $request->query->get('tracking_id') ?? $request->request->get('tracking_id'); try { if ($trackingId) { $message = $this->messageRepository->findOneBy(['trackId' => $trackingId]); } elseif ($messageId) { $message = $this->messageRepository->find($messageId); } else { return $this->error('Missing message_id or tracking_id', 400); } if (!$message instanceof Message || (int) $message->getUserId() !== $userId) { return $this->error('Message not found', 404); } return new JsonResponse([ 'success' => true, 'message' => [ 'id' => $message->getId(), 'user_id' => $message->getUserId(), 'text' => $message->getText(), 'direction' => $message->getDirection(), 'status' => $message->getStatus(), 'topic' => $message->getTopic(), 'language' => $message->getLanguage(), 'timestamp' => $message->getUnixTimestamp(), ], ]); } catch (\Exception $e) { $this->logger->error('Legacy messageGet failed', ['error' => $e->getMessage()]); return $this->error($e->getMessage(), 500); } } /** * Legacy: againOptions * Gibt alternative Antwort-Optionen zurück. */ private function againOptions(Request $request): JsonResponse { $userId = $this->authenticatedUserId(); if (null === $userId) { return $this->error('User not authenticated', 401); } $messageId = $request->query->get('in_id') ?? $request->request->get('in_id') ?? $request->query->get('message_id') ?? $request->request->get('message_id'); try { $message = $this->messageRepository->find($messageId); if (!$message instanceof Message || (int) $message->getUserId() !== $userId) { return $this->error('Message not found', 404); } // Generate alternative responses (simplified) return new JsonResponse([ 'success' => true, 'options' => [ 'regenerate' => true, 'edit' => true, 'delete' => true, ], ]); } catch (\Exception $e) { return $this->error($e->getMessage(), 500); } } /** * Legacy: getProfile * Gibt User-Profile zurück. */ private function getProfile(Request $request): JsonResponse { $userId = $this->authenticatedUserId(); if (null === $userId) { return $this->error('User not authenticated', 401); } try { $user = $this->userRepository->find($userId); if (!$user) { return $this->error('User not found', 404); } return new JsonResponse([ 'success' => true, 'profile' => [ 'id' => $user->getId(), 'email' => $user->getMail(), 'level' => $user->getUserlevel(), 'created' => $user->getCreated(), 'details' => $user->getUserdetails(), ], ]); } catch (\Exception $e) { return $this->error($e->getMessage(), 500); } } /** * Legacy: chatStream * SSE Streaming (simplified redirect). */ private function chatStream(Request $request): Response { $userId = $this->authenticatedUserId(); if (null === $userId) { return $this->error('User not authenticated', 401); } $messageId = $request->query->get('message_id') ?? $request->request->get('message_id'); $message = $this->messageRepository->find($messageId); if (!$message instanceof Message || (int) $message->getUserId() !== $userId) { return $this->error('Message not found', 404); } return $this->redirectToRoute('api_messages_stream', [ 'id' => $message->getId(), ]); } /** * Legacy: ragUpload * File upload for RAG. */ private function ragUpload(Request $request): JsonResponse { $userId = $this->authenticatedUserId(); if (!$userId) { return $this->error('User not authenticated', 401); } try { $file = $request->files->get('file'); if (null === $file) { return $this->error('No file uploaded', 400); } // Use WordPressIntegrationService which handles file upload $result = $this->wordpressIntegrationService->step3UploadFile($userId, $file); return new JsonResponse($result); } catch (\Exception $e) { $this->logger->error('Legacy ragUpload failed', ['error' => $e->getMessage()]); return $this->error($e->getMessage(), 500); } } /** * Legacy: getWidgets * Returns list of widgets for a user. */ private function getWidgets(Request $request): JsonResponse { $userId = $this->authenticatedUserId(); if (!$userId) { return $this->error('User not authenticated', 401); } try { $widgets = $this->widgetService->getWidgetsByUserId($userId); $widgetData = []; foreach ($widgets as $widget) { $widgetData[] = [ 'id' => $widget->getId(), 'widget_id' => $widget->getWidgetId(), 'name' => $widget->getName(), 'config' => $widget->getConfig(), 'active' => $widget->isActive(), 'created' => $widget->getCreatedAt()?->format('Y-m-d H:i:s'), ]; } return new JsonResponse([ 'success' => true, 'widgets' => $widgetData, ]); } catch (\Exception $e) { $this->logger->error('Legacy getWidgets failed', ['error' => $e->getMessage()]); return $this->error($e->getMessage(), 500); } } /** * Legacy: createApiKey * Creates an API key for the authenticated user. */ private function createApiKey(Request $request): JsonResponse { $userId = $this->authenticatedUserId(); if (!$userId) { return $this->error('User not authenticated', 401); } try { $result = $this->wordpressIntegrationService->step2CreateApiKey($userId); return new JsonResponse($result); } catch (ApiKeyPlanRequiredException $refusal) { return new JsonResponse($refusal->body(), Response::HTTP_FORBIDDEN); } catch (\Exception $e) { $this->logger->error('Legacy createApiKey failed', ['error' => $e->getMessage()]); return $this->error($e->getMessage(), 500); } } /** * Legacy: saveWidget * Saves widget configuration. */ private function saveWidget(Request $request): JsonResponse { $userId = $this->authenticatedUserId(); if (!$userId) { return $this->error('User not authenticated', 401); } try { $payload = $this->collectLegacyPayload($request); $result = $this->wordpressIntegrationService->step5SaveWidget($userId, $payload); return new JsonResponse($result); } catch (\Exception $e) { $this->logger->error('Legacy saveWidget failed', ['error' => $e->getMessage()]); return $this->error($e->getMessage(), 500); } } /** * Legacy: promptUpdate * Updates a prompt configuration. */ private function promptUpdate(Request $request): JsonResponse { $userId = $this->authenticatedUserId(); if (!$userId) { return $this->error('User not authenticated', 401); } try { $payload = $this->collectLegacyPayload($request); $topic = $payload['topic'] ?? $payload['prompt'] ?? null; if (!$topic) { return $this->error('Missing topic/prompt parameter', 400); } // Get prompt with metadata $promptData = $this->promptService->getPromptWithMetadata($topic, $userId); if (!$promptData) { return $this->error('Prompt not found', 404); } $prompt = $promptData['prompt']; // Update metadata if provided $metadata = []; if (isset($payload['tool_files'])) { $metadata['tool_files'] = (bool) $payload['tool_files']; } if (isset($payload['tool_internet'])) { $metadata['tool_internet'] = (bool) $payload['tool_internet']; } if (isset($payload['aiModel'])) { $metadata['aiModel'] = (int) $payload['aiModel']; } if (!empty($metadata)) { // Mirror the eligibility gate from PromptController so // the legacy widget API cannot be used to assign a // premium-only model behind the new check (issue #891). $user = $this->userRepository->find($userId); if ($user) { try { $this->modelEligibilityValidator->assertMetadataAllowed($user, $metadata); } catch (InvalidPromptModelException $e) { return $this->error($e->getMessage(), 400); } catch (PremiumRequiredException $e) { return new JsonResponse([ 'success' => false, 'error' => 'requires_premium', 'capability' => 'VECTORIZE', 'message' => $e->getMessage(), 'currentLevel' => $e->currentLevel, ], Response::HTTP_FORBIDDEN); } } $this->promptService->saveMetadataForPrompt($prompt, array_merge($promptData['metadata'], $metadata)); } return new JsonResponse([ 'success' => true, 'message' => 'Prompt updated successfully', ]); } catch (\Exception $e) { $this->logger->error('Legacy promptUpdate failed', ['error' => $e->getMessage()]); return $this->error($e->getMessage(), 500); } } /** * Legacy: sendEmail * Sends a confirmation/verification email. */ /** * Retired. This action mailed any address and did not store the token it * claimed to send. */ private function sendEmail(Request $request): JsonResponse { unset($request); return $this->error('This action is no longer available.', 410); } /** * Retired. This action reported success without checking a token. */ private function verifyEmail(Request $request): JsonResponse { unset($request); return $this->error('This action is no longer available.', 410); } /** * The signed-in account. A user_id parameter is never accepted. */ private function authenticatedUserId(): ?int { $user = $this->authenticatedUser(); return $user instanceof User ? (int) $user->getId() : null; } private function authenticatedUser(): ?User { $user = $this->getUser(); if (!$user instanceof User || (int) $user->getId() <= 0) { return null; } return $user; } /** * @param array $payload */ private function assertOwnAccount(User $user, array $payload): void { $email = strtolower(trim((string) ($payload['email'] ?? ''))); if ('' === $email || $email !== strtolower($user->getMail())) { throw new \InvalidArgumentException('WordPress setup can only continue for the signed-in account.'); } } private function wpStep1(Request $request): JsonResponse { $user = $this->authenticatedUser(); if (!$user instanceof User) { return $this->error('User not authenticated', 401); } return $this->wpResponse(function () use ($request, $user) { $payload = $this->collectLegacyPayload($request); $this->assertOwnAccount($user, $payload); return $this->wordpressIntegrationService->step1VerifyAndCreateUser($payload); }); } private function wpStep2(Request $request): JsonResponse { unset($request); $userId = $this->authenticatedUserId(); if (null === $userId) { return $this->error('User not authenticated', 401); } return $this->wpResponse(function () use ($userId) { return $this->wordpressIntegrationService->step2CreateApiKey($userId); }); } private function wpStep3(Request $request): JsonResponse { $userId = $this->authenticatedUserId(); if (null === $userId) { return $this->error('User not authenticated', 401); } return $this->wpResponse(function () use ($request, $userId) { $file = $request->files->get('file'); if (null === $file) { throw new \InvalidArgumentException('file upload is required'); } return $this->wordpressIntegrationService->step3UploadFile($userId, $file); }); } private function wpStep4(Request $request): JsonResponse { unset($request); $userId = $this->authenticatedUserId(); if (null === $userId) { return $this->error('User not authenticated', 401); } return $this->wpResponse(function () use ($userId) { return $this->wordpressIntegrationService->step4EnableFileSearch($userId); }); } private function wpStep5(Request $request): JsonResponse { $userId = $this->authenticatedUserId(); if (null === $userId) { return $this->error('User not authenticated', 401); } return $this->wpResponse(function () use ($request, $userId) { $payload = $this->collectLegacyPayload($request); return $this->wordpressIntegrationService->step5SaveWidget($userId, $payload); }); } private function wpWizardComplete(Request $request): JsonResponse { $user = $this->authenticatedUser(); if (!$user instanceof User) { return $this->error('User not authenticated', 401); } return $this->wpResponse(function () use ($request, $user) { $payload = $this->collectLegacyPayload($request); $this->assertOwnAccount($user, $payload); return $this->wordpressIntegrationService->completeWizard($payload, array_values($request->files->all())); }); } /** * @param callable(): array $callback */ private function wpResponse(callable $callback): JsonResponse { try { $result = $callback(); return new JsonResponse($result); } catch (ApiKeyPlanRequiredException $refusal) { return new JsonResponse($refusal->body(), Response::HTTP_FORBIDDEN); } catch (\Throwable $e) { $this->logger->error('Legacy WordPress wizard error', [ 'error' => $e->getMessage(), ]); return $this->error($e->getMessage(), 400); } } /** * @return array */ private function collectLegacyPayload(Request $request): array { $payload = array_merge($request->query->all(), $request->request->all()); $contentType = $request->headers->get('Content-Type', ''); if (str_contains((string) $contentType, 'application/json') && $request->getContent()) { $decoded = json_decode($request->getContent(), true); if (is_array($decoded)) { $payload = array_merge($payload, $decoded); } } return $payload; } /** * Error Response Helper. */ private function error(string $message, int $code = 400): JsonResponse { return new JsonResponse([ 'success' => false, 'error' => $message, 'code' => $code, ], $code); } }