ExamPdfExportService.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. <?php
  2. namespace App\Services;
  3. use App\Http\Controllers\ExamPdfController;
  4. use App\Models\Paper;
  5. use App\Models\PaperQuestion;
  6. use App\Models\Student;
  7. use Illuminate\Http\Request;
  8. use Illuminate\Support\Facades\File;
  9. use Illuminate\Support\Facades\Log;
  10. use Illuminate\Support\Facades\Storage;
  11. use Illuminate\Support\Facades\URL;
  12. use App\Services\LearningAnalyticsService;
  13. use App\Services\QuestionBankService;
  14. use App\Services\QuestionServiceApi;
  15. use Symfony\Component\Process\Exception\ProcessSignaledException;
  16. use Symfony\Component\Process\Exception\ProcessTimedOutException;
  17. use Symfony\Component\Process\Process;
  18. class ExamPdfExportService
  19. {
  20. private ExamPdfController $controller;
  21. private LearningAnalyticsService $learningAnalyticsService;
  22. private QuestionBankService $questionBankService;
  23. public function __construct(
  24. ExamPdfController $controller,
  25. LearningAnalyticsService $learningAnalyticsService,
  26. QuestionBankService $questionBankService
  27. )
  28. {
  29. $this->controller = $controller;
  30. $this->learningAnalyticsService = $learningAnalyticsService;
  31. $this->questionBankService = $questionBankService;
  32. }
  33. /**
  34. 生成试卷 PDF(不含答案)
  35. */
  36. public function generateExamPdf(string $paperId): ?string
  37. {
  38. return $this->renderAndStore($paperId, includeAnswer: false, suffix: 'exam');
  39. }
  40. /**
  41. 生成判卷 PDF(含答案与解析)
  42. */
  43. public function generateGradingPdf(string $paperId): ?string
  44. {
  45. return $this->renderAndStore($paperId, includeAnswer: true, suffix: 'grading', useGradingView: true);
  46. }
  47. /**
  48. * 生成学情分析 PDF
  49. */
  50. public function generateAnalysisReportPdf(string $paperId, string $studentId): ?string
  51. {
  52. if (function_exists('set_time_limit')) {
  53. @set_time_limit(240);
  54. }
  55. try {
  56. $payload = $this->buildAnalysisPayload($paperId, $studentId);
  57. if (!$payload) {
  58. return null;
  59. }
  60. $html = view('exam-analysis.pdf-report', $payload)->render();
  61. $pdfBinary = $this->buildPdf($html);
  62. if (!$pdfBinary) {
  63. return null;
  64. }
  65. $path = "analysis_reports/{$paperId}_{$studentId}.pdf";
  66. Storage::disk('public')->put($path, $pdfBinary);
  67. return URL::to(Storage::url($path));
  68. } catch (\Throwable $e) {
  69. Log::error('ExamPdfExportService: 生成学情分析 PDF 失败', [
  70. 'paper_id' => $paperId,
  71. 'student_id' => $studentId,
  72. 'error' => $e->getMessage(),
  73. 'exception' => get_class($e),
  74. 'trace' => $e->getTraceAsString(),
  75. ]);
  76. return null;
  77. }
  78. }
  79. private function renderAndStore(
  80. string $paperId,
  81. bool $includeAnswer,
  82. string $suffix,
  83. bool $useGradingView = false
  84. ): ?string {
  85. // 放宽脚本执行时间,避免长耗时渲染被 PHP 全局超时打断
  86. if (function_exists('set_time_limit')) {
  87. @set_time_limit(240);
  88. }
  89. try {
  90. $html = $this->renderHtml($paperId, $includeAnswer, $useGradingView);
  91. if (!$html) {
  92. Log::error('ExamPdfExportService: 渲染 HTML 为空', [
  93. 'paper_id' => $paperId,
  94. 'include_answer' => $includeAnswer,
  95. 'use_grading_view' => $useGradingView,
  96. ]);
  97. return null;
  98. }
  99. $pdfBinary = $this->buildPdf($html);
  100. if (!$pdfBinary) {
  101. return null;
  102. }
  103. $path = "exams/{$paperId}_{$suffix}.pdf";
  104. Storage::disk('public')->put($path, $pdfBinary);
  105. return URL::to(Storage::url($path));
  106. } catch (\Throwable $e) {
  107. Log::error('ExamPdfExportService: 生成 PDF 失败', [
  108. 'paper_id' => $paperId,
  109. 'suffix' => $suffix,
  110. 'error' => $e->getMessage(),
  111. 'exception' => get_class($e),
  112. 'trace' => $e->getTraceAsString(),
  113. ]);
  114. return null;
  115. }
  116. }
  117. private function renderHtml(string $paperId, bool $includeAnswer, bool $useGradingView): ?string
  118. {
  119. // 复用已有控制器的渲染逻辑,保证版式一致
  120. $request = Request::create(
  121. '/admin/intelligent-exam/' . ($useGradingView ? 'grading' : 'pdf') . '/' . $paperId,
  122. 'GET',
  123. ['answer' => $includeAnswer ? 'true' : 'false']
  124. );
  125. $view = $useGradingView
  126. ? $this->controller->showGrading($request, $paperId)
  127. : $this->controller->show($request, $paperId);
  128. if (is_object($view) && method_exists($view, 'render')) {
  129. return $this->ensureUtf8Html($view->render());
  130. }
  131. return null;
  132. }
  133. private function buildPdf(string $html): ?string
  134. {
  135. $tmpHtml = tempnam(sys_get_temp_dir(), 'exam_html_') . '.html';
  136. $utf8Html = $this->ensureUtf8Html($html);
  137. file_put_contents($tmpHtml, $utf8Html);
  138. // 仅使用 Chrome 渲染,去掉 wkhtmltopdf 兜底以暴露真实问题
  139. $chromePdf = $this->renderWithChrome($tmpHtml);
  140. @unlink($tmpHtml);
  141. return $chromePdf;
  142. }
  143. private function renderWithChrome(string $htmlPath): ?string
  144. {
  145. $tmpPdf = tempnam(sys_get_temp_dir(), 'exam_pdf_') . '.pdf';
  146. // 固定用户目录,减少 Chrome 首次初始化开销;允许多进程并发时可按需加锁
  147. $userDataDir = sys_get_temp_dir() . '/chrome-pdf-profile';
  148. $chromeBinary = env('PDF_CHROME_BINARY');
  149. if (!$chromeBinary) {
  150. $candidates = [
  151. '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
  152. '/usr/bin/google-chrome-stable',
  153. '/usr/bin/google-chrome',
  154. '/usr/bin/chromium-browser',
  155. '/usr/bin/chromium',
  156. ];
  157. foreach ($candidates as $path) {
  158. if (is_file($path) && is_executable($path)) {
  159. $chromeBinary = $path;
  160. break;
  161. }
  162. }
  163. }
  164. if (!$chromeBinary) {
  165. Log::error('ExamPdfExportService: 未找到可用的 Chrome/Chromium,已停止导出', [
  166. 'html_path' => $htmlPath,
  167. 'path_env' => env('PATH'),
  168. 'candidates_checked' => $candidates ?? [],
  169. ]);
  170. return null;
  171. }
  172. // 为无权限环境设置可写的 HOME/XDG 目录,避免创建 /var/www/.local 报错
  173. $runtimeHome = sys_get_temp_dir() . '/chrome-home';
  174. $runtimeXdg = sys_get_temp_dir() . '/chrome-xdg';
  175. if (!File::exists($runtimeHome)) {
  176. @File::makeDirectory($runtimeHome, 0755, true);
  177. }
  178. if (!File::exists($runtimeXdg)) {
  179. @File::makeDirectory($runtimeXdg, 0755, true);
  180. }
  181. $process = new Process([
  182. $chromeBinary,
  183. '--headless',
  184. '--disable-gpu',
  185. '--no-sandbox',
  186. '--disable-setuid-sandbox',
  187. '--disable-dev-shm-usage',
  188. '--no-zygote',
  189. '--disable-features=VizDisplayCompositor',
  190. '--disable-software-rasterizer',
  191. '--disable-extensions',
  192. '--disable-background-networking',
  193. '--disable-component-update',
  194. '--disable-client-side-phishing-detection',
  195. '--disable-default-apps',
  196. '--disable-domain-reliability',
  197. '--disable-sync',
  198. '--safebrowsing-disable-auto-update',
  199. '--no-first-run',
  200. '--no-default-browser-check',
  201. '--disable-crash-reporter',
  202. '--disable-print-preview',
  203. '--disable-features=PrintHeaderFooter',
  204. '--user-data-dir=' . $userDataDir,
  205. '--print-to-pdf=' . $tmpPdf,
  206. '--print-to-pdf-no-header',
  207. '--allow-file-access-from-files',
  208. 'file://' . $htmlPath,
  209. ], null, [
  210. 'HOME' => $runtimeHome,
  211. 'XDG_RUNTIME_DIR' => $runtimeXdg,
  212. ]);
  213. $process->setTimeout(60);
  214. try {
  215. $startedAt = microtime(true);
  216. Log::info('ExamPdfExportService: Chrome 渲染启动', [
  217. 'cmd' => $process->getCommandLine(),
  218. 'html_path' => $htmlPath,
  219. 'tmp_pdf' => $tmpPdf,
  220. 'user_data_dir' => $userDataDir,
  221. 'html_exists' => file_exists($htmlPath),
  222. 'html_size' => file_exists($htmlPath) ? filesize($htmlPath) : null,
  223. 'cwd' => $process->getWorkingDirectory(),
  224. ]);
  225. $process->start();
  226. $pdfGenerated = false;
  227. // 轮询检测 PDF 是否生成,尽快返回,避免等待 Chrome 完整退出
  228. $pollStart = microtime(true);
  229. $maxPollSeconds = 45;
  230. while ($process->isRunning() && (microtime(true) - $pollStart) < $maxPollSeconds) {
  231. if (file_exists($tmpPdf) && filesize($tmpPdf) > 0) {
  232. $pdfGenerated = true;
  233. Log::info('ExamPdfExportService: 发现 PDF 已生成,提前结束 Chrome', [
  234. 'duration_sec' => round(microtime(true) - $startedAt, 3),
  235. 'tmp_pdf_size' => filesize($tmpPdf),
  236. ]);
  237. $process->stop(5, SIGKILL);
  238. break;
  239. }
  240. usleep(200_000); // 200ms
  241. }
  242. // 如果仍在运行且超过轮询窗口,则强制结束
  243. if ($process->isRunning()) {
  244. Log::warning('ExamPdfExportService: Chrome 轮询超时,强制结束', [
  245. 'duration_sec' => round(microtime(true) - $startedAt, 3),
  246. ]);
  247. $process->stop(5, SIGKILL);
  248. }
  249. $process->wait();
  250. Log::info('ExamPdfExportService: Chrome 渲染完成', [
  251. 'duration_sec' => round(microtime(true) - $startedAt, 3),
  252. 'exit_code' => $process->getExitCode(),
  253. 'tmp_pdf_exists' => file_exists($tmpPdf),
  254. 'tmp_pdf_size' => file_exists($tmpPdf) ? filesize($tmpPdf) : null,
  255. 'stderr' => $process->getErrorOutput(),
  256. 'stdout' => $process->getOutput(),
  257. 'pdf_generated_during_poll' => $pdfGenerated,
  258. ]);
  259. } catch (ProcessTimedOutException|ProcessSignaledException $e) {
  260. Log::error('ExamPdfExportService: Chrome 进程异常', [
  261. 'cmd' => $process->getCommandLine(),
  262. 'signal' => method_exists($process, 'getTermSignal') ? $process->getTermSignal() : null,
  263. 'error' => $process->getErrorOutput(),
  264. 'output' => $process->getOutput(),
  265. 'exit_code' => $process->getExitCode(),
  266. 'exception' => $e->getMessage(),
  267. 'trace' => $e->getTraceAsString(),
  268. ]);
  269. if ($process->isRunning()) {
  270. $process->stop(5, SIGKILL);
  271. }
  272. $pdfExists = file_exists($tmpPdf);
  273. $pdfSize = $pdfExists ? filesize($tmpPdf) : null;
  274. if ($pdfExists && $pdfSize > 0) {
  275. Log::warning('ExamPdfExportService: Chrome 异常但产生了 PDF,尝试继续返回', [
  276. 'tmp_pdf_exists' => $pdfExists,
  277. 'tmp_pdf_size' => $pdfSize,
  278. 'duration_sec' => isset($startedAt) ? round(microtime(true) - $startedAt, 3) : null,
  279. ]);
  280. $pdfBinary = file_get_contents($tmpPdf);
  281. @unlink($tmpPdf);
  282. File::deleteDirectory($userDataDir);
  283. return $pdfBinary ?: null;
  284. }
  285. @unlink($tmpPdf);
  286. File::deleteDirectory($userDataDir);
  287. return null;
  288. } catch (\Throwable $e) {
  289. Log::error('ExamPdfExportService: Chrome 调用异常', [
  290. 'cmd' => $process->getCommandLine(),
  291. 'error' => $e->getMessage(),
  292. 'exit_code' => $process->getExitCode(),
  293. 'stderr' => $process->getErrorOutput(),
  294. 'stdout' => $process->getOutput(),
  295. 'trace' => $e->getTraceAsString(),
  296. ]);
  297. if ($process->isRunning()) {
  298. $process->stop(5, SIGKILL);
  299. }
  300. $pdfExists = file_exists($tmpPdf);
  301. $pdfSize = $pdfExists ? filesize($tmpPdf) : null;
  302. if ($pdfExists && $pdfSize > 0) {
  303. Log::warning('ExamPdfExportService: Chrome 调用异常但产生了 PDF,尝试继续返回', [
  304. 'tmp_pdf_exists' => $pdfExists,
  305. 'tmp_pdf_size' => $pdfSize,
  306. 'duration_sec' => isset($startedAt) ? round(microtime(true) - $startedAt, 3) : null,
  307. ]);
  308. $pdfBinary = file_get_contents($tmpPdf);
  309. @unlink($tmpPdf);
  310. File::deleteDirectory($userDataDir);
  311. return $pdfBinary ?: null;
  312. }
  313. @unlink($tmpPdf);
  314. File::deleteDirectory($userDataDir);
  315. return null;
  316. }
  317. $pdfExists = file_exists($tmpPdf);
  318. $pdfSize = $pdfExists ? filesize($tmpPdf) : null;
  319. if (!$process->isSuccessful()) {
  320. if ($pdfExists && $pdfSize > 0) {
  321. Log::warning('ExamPdfExportService: Chrome 进程异常但生成了 PDF,继续使用', [
  322. 'cmd' => implode(' ', (array) $process->getCommandLine()),
  323. 'exit_code' => $process->getExitCode(),
  324. 'error' => $process->getErrorOutput(),
  325. 'output' => $process->getOutput(),
  326. 'tmp_pdf_exists' => $pdfExists,
  327. 'tmp_pdf_size' => $pdfSize,
  328. 'html_path' => $htmlPath,
  329. 'user_data_dir' => $userDataDir,
  330. ]);
  331. } else {
  332. Log::error('ExamPdfExportService: Chrome 渲染失败', [
  333. 'cmd' => implode(' ', (array) $process->getCommandLine()),
  334. 'exit_code' => $process->getExitCode(),
  335. 'error' => $process->getErrorOutput(),
  336. 'output' => $process->getOutput(),
  337. 'tmp_pdf_exists' => $pdfExists,
  338. 'tmp_pdf_size' => $pdfSize,
  339. 'html_path' => $htmlPath,
  340. 'user_data_dir' => $userDataDir,
  341. ]);
  342. @unlink($tmpPdf);
  343. File::deleteDirectory($userDataDir);
  344. return null;
  345. }
  346. }
  347. $pdfBinary = $pdfExists ? file_get_contents($tmpPdf) : null;
  348. @unlink($tmpPdf);
  349. File::deleteDirectory($userDataDir);
  350. return $pdfBinary ?: null;
  351. }
  352. private function buildAnalysisPayload(string $paperId, string $studentId): ?array
  353. {
  354. $paper = Paper::with(['questions' => function ($query) {
  355. $query->orderBy('question_number');
  356. }])->find($paperId);
  357. if (!$paper) {
  358. Log::error('ExamPdfExportService: 未找到试卷,无法生成学情报告', [
  359. 'paper_id' => $paperId,
  360. 'student_id' => $studentId,
  361. ]);
  362. return null;
  363. }
  364. $student = Student::find($studentId);
  365. $studentInfo = [
  366. 'id' => $student?->student_id ?? $studentId,
  367. 'name' => $student?->name ?? $studentId,
  368. 'grade' => $student?->grade ?? '未知年级',
  369. 'class' => $student?->class_name ?? '未知班级',
  370. ];
  371. // 调用学习分析服务获取本卷分析与掌握度
  372. $analysisData = [];
  373. if (!empty($paper->analysis_id)) {
  374. $analysis = $this->learningAnalyticsService->getAnalysisResult($paper->analysis_id);
  375. if (!empty($analysis['data'])) {
  376. $analysisData = $analysis['data'];
  377. }
  378. }
  379. $masteryData = [];
  380. $masteryResponse = $this->learningAnalyticsService->getStudentMastery($studentId);
  381. if (!empty($masteryResponse['data'])) {
  382. $masteryData = $masteryResponse['data'];
  383. }
  384. $recommendations = [];
  385. $recommendationResponse = $this->learningAnalyticsService->getLearningRecommendations($studentId);
  386. if (!empty($recommendationResponse['data'])) {
  387. $recommendations = $recommendationResponse['data'];
  388. }
  389. $kpNameMap = $this->buildKnowledgePointNameMap();
  390. // 预取题库详情用于解析/解题思路
  391. $questionDetails = [];
  392. $questionIds = $paper->questions->pluck('question_id')->filter()->unique()->values();
  393. foreach ($questionIds as $qid) {
  394. try {
  395. $detail = $this->questionBankService->getQuestion((string) $qid);
  396. if (!empty($detail)) {
  397. $questionDetails[(string) $qid] = $detail;
  398. }
  399. } catch (\Throwable $e) {
  400. Log::warning('ExamPdfExportService: 获取题库题目详情失败', [
  401. 'question_id' => $qid,
  402. 'error' => $e->getMessage(),
  403. ]);
  404. }
  405. }
  406. $questions = $paper->questions
  407. ->map(function (PaperQuestion $question) use ($kpNameMap, $questionDetails) {
  408. $kpCode = $question->knowledge_point ?? '';
  409. $kpName = $kpNameMap[$kpCode] ?? $kpCode ?: '未标注';
  410. $detail = $questionDetails[(string) ($question->question_id ?? '')] ?? [];
  411. $solution = $detail['solution'] ?? $detail['解析'] ?? $detail['analysis'] ?? null;
  412. $typeRaw = $detail['question_type'] ?? $detail['type'] ?? $question->question_type ?? '';
  413. $normalizedType = $this->normalizeQuestionType($typeRaw);
  414. return [
  415. 'question_number' => $question->question_number,
  416. 'question_text' => is_array($question->question_text) ? json_encode($question->question_text, JSON_UNESCAPED_UNICODE) : ($question->question_text ?? ''),
  417. 'question_type' => $normalizedType,
  418. 'knowledge_point' => $kpCode,
  419. 'knowledge_point_name' => $kpName,
  420. 'score' => $question->score,
  421. 'solution' => $solution,
  422. ];
  423. })
  424. ->sortBy('question_number')
  425. ->values()
  426. ->toArray();
  427. $questionInsights = $analysisData['question_results'] ?? [];
  428. $masterySummary = $this->buildMasterySummary($masteryData, $kpNameMap);
  429. return [
  430. 'paper' => [
  431. 'id' => $paper->paper_id,
  432. 'name' => $paper->paper_name,
  433. 'total_questions' => $paper->question_count,
  434. 'total_score' => $paper->total_score,
  435. 'created_at' => $paper->created_at,
  436. ],
  437. 'student' => $studentInfo,
  438. 'questions' => $questions,
  439. 'mastery' => $masterySummary,
  440. 'question_insights' => $questionInsights,
  441. 'recommendations' => $recommendations,
  442. 'analysis_data' => $analysisData,
  443. ];
  444. }
  445. private function buildKnowledgePointNameMap(): array
  446. {
  447. try {
  448. // 优先使用 QuestionServiceApi(已有知识点名称缓存)
  449. if (class_exists(QuestionServiceApi::class)) {
  450. /** @var QuestionServiceApi $service */
  451. $service = app(QuestionServiceApi::class);
  452. $options = $service->getKnowledgePointOptions();
  453. if (!empty($options)) {
  454. return $options;
  455. }
  456. }
  457. // 退回 QuestionBankService(可能缺少此方法)
  458. if (method_exists($this->questionBankService, 'getKnowledgePointOptions')) {
  459. $options = $this->questionBankService->getKnowledgePointOptions();
  460. $map = [];
  461. foreach ($options as $item) {
  462. if (is_array($item)) {
  463. $code = $item['kp_code'] ?? null;
  464. $name = $item['kp_name'] ?? $item['name'] ?? null;
  465. if ($code && $name) {
  466. $map[$code] = $name;
  467. }
  468. }
  469. }
  470. if (!empty($map)) {
  471. return $map;
  472. }
  473. }
  474. } catch (\Throwable $e) {
  475. Log::warning('ExamPdfExportService: 获取知识点名称失败,退回使用编码', [
  476. 'error' => $e->getMessage(),
  477. ]);
  478. }
  479. return [];
  480. }
  481. private function buildMasterySummary(array $masteryData, array $kpNameMap): array
  482. {
  483. $items = [];
  484. $total = 0;
  485. $count = 0;
  486. $hasMap = !empty($kpNameMap);
  487. foreach ($masteryData as $row) {
  488. $code = $row['kp_code'] ?? null;
  489. if ($hasMap && $code && !isset($kpNameMap[$code])) {
  490. // 不在知识图谱中的知识点不呈现
  491. continue;
  492. }
  493. $name = $row['kp_name'] ?? ($code ? ($kpNameMap[$code] ?? $code) : '未知知识点');
  494. $level = (float) ($row['mastery_level'] ?? 0);
  495. $delta = $row['mastery_change'] ?? null;
  496. $items[] = [
  497. 'kp_code' => $code,
  498. 'kp_name' => $name,
  499. 'mastery_level' => $level,
  500. 'mastery_change' => $delta,
  501. ];
  502. $total += $level;
  503. $count++;
  504. }
  505. $average = $count > 0 ? round($total / $count, 2) : null;
  506. // 按掌握度从低到高排序,便于突出薄弱点
  507. usort($items, fn($a, $b) => ($a['mastery_level'] <=> $b['mastery_level']));
  508. return [
  509. 'items' => $items,
  510. 'average' => $average,
  511. 'weak_list' => array_slice($items, 0, 5),
  512. ];
  513. }
  514. private function normalizeQuestionType(?string $type): string
  515. {
  516. $t = strtolower(trim((string) $type));
  517. return match (true) {
  518. str_contains($t, 'choice') || str_contains($t, '选择') => 'choice',
  519. str_contains($t, 'fill') || str_contains($t, 'blank') || str_contains($t, '填空') => 'fill',
  520. default => 'answer',
  521. };
  522. }
  523. private function ensureUtf8Html(string $html): string
  524. {
  525. $meta = '<meta charset="UTF-8">';
  526. if (stripos($html, '<head>') !== false) {
  527. return preg_replace('/<head>/i', "<head>{$meta}", $html, 1);
  528. }
  529. return $meta . $html;
  530. }
  531. }