| Total Complexity | 110 |
| Total Lines | 816 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
Complex classes like ResourceController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use ResourceController, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 55 | #[Route('/r')] |
||
| 56 | class ResourceController extends AbstractResourceController implements CourseControllerInterface |
||
| 57 | { |
||
| 58 | use ControllerTrait; |
||
| 59 | use CourseControllerTrait; |
||
| 60 | use GradebookControllerTrait; |
||
| 61 | use ResourceControllerTrait; |
||
| 62 | |||
| 63 | public function __construct( |
||
| 64 | private readonly UserHelper $userHelper, |
||
| 65 | private readonly ResourceNodeRepository $resourceNodeRepository, |
||
| 66 | private readonly ResourceFileRepository $resourceFileRepository |
||
| 67 | ) {} |
||
| 68 | |||
| 69 | #[Route(path: '/{tool}/{type}/{id}/disk_space', methods: ['GET', 'POST'], name: 'chamilo_core_resource_disk_space')] |
||
| 70 | public function diskSpace(Request $request): Response |
||
| 71 | { |
||
| 72 | $nodeId = $request->get('id'); |
||
| 73 | $repository = $this->getRepositoryFromRequest($request); |
||
| 74 | |||
| 75 | /** @var ResourceNode $resourceNode */ |
||
| 76 | $resourceNode = $repository->getResourceNodeRepository()->find($nodeId); |
||
| 77 | |||
| 78 | $this->denyAccessUnlessGranted( |
||
| 79 | ResourceNodeVoter::VIEW, |
||
| 80 | $resourceNode, |
||
| 81 | $this->trans('Unauthorised access to resource') |
||
| 82 | ); |
||
| 83 | |||
| 84 | $course = $this->getCourse(); |
||
| 85 | $totalSize = 0; |
||
| 86 | if (null !== $course) { |
||
| 87 | $totalSize = $course->getDiskQuota(); |
||
| 88 | } |
||
| 89 | |||
| 90 | $size = $repository->getResourceNodeRepository()->getSize( |
||
| 91 | $resourceNode, |
||
| 92 | $repository->getResourceType(), |
||
| 93 | $course |
||
| 94 | ); |
||
| 95 | |||
| 96 | $labels[] = $course->getTitle(); |
||
|
|
|||
| 97 | $data[] = $size; |
||
| 98 | $sessions = $course->getSessions(); |
||
| 99 | |||
| 100 | foreach ($sessions as $sessionRelCourse) { |
||
| 101 | $session = $sessionRelCourse->getSession(); |
||
| 102 | |||
| 103 | $labels[] = $course->getTitle().' - '.$session->getTitle(); |
||
| 104 | $size = $repository->getResourceNodeRepository()->getSize( |
||
| 105 | $resourceNode, |
||
| 106 | $repository->getResourceType(), |
||
| 107 | $course, |
||
| 108 | $session |
||
| 109 | ); |
||
| 110 | $data[] = $size; |
||
| 111 | } |
||
| 112 | |||
| 113 | /*$groups = $course->getGroups(); |
||
| 114 | foreach ($groups as $group) { |
||
| 115 | $labels[] = $course->getTitle().' - '.$group->getTitle(); |
||
| 116 | $size = $repository->getResourceNodeRepository()->getSize( |
||
| 117 | $resourceNode, |
||
| 118 | $repository->getResourceType(), |
||
| 119 | $course, |
||
| 120 | null, |
||
| 121 | $group |
||
| 122 | ); |
||
| 123 | $data[] = $size; |
||
| 124 | }*/ |
||
| 125 | |||
| 126 | $used = array_sum($data); |
||
| 127 | $labels[] = $this->trans('Free space on disk'); |
||
| 128 | $data[] = $totalSize - $used; |
||
| 129 | |||
| 130 | return $this->render( |
||
| 131 | '@ChamiloCore/Resource/disk_space.html.twig', |
||
| 132 | [ |
||
| 133 | 'resourceNode' => $resourceNode, |
||
| 134 | 'labels' => $labels, |
||
| 135 | 'data' => $data, |
||
| 136 | ] |
||
| 137 | ); |
||
| 138 | } |
||
| 139 | |||
| 140 | /** |
||
| 141 | * View file of a resource node. |
||
| 142 | */ |
||
| 143 | #[Route('/{tool}/{type}/{id}/view', name: 'chamilo_core_resource_view', methods: ['GET'])] |
||
| 209 | } |
||
| 210 | |||
| 211 | /** |
||
| 212 | * Redirect resource to link. |
||
| 213 | * |
||
| 214 | * @return RedirectResponse|void |
||
| 215 | */ |
||
| 216 | #[Route('/{tool}/{type}/{id}/link', name: 'chamilo_core_resource_link', methods: ['GET'])] |
||
| 247 | } |
||
| 248 | } |
||
| 249 | |||
| 250 | /** |
||
| 251 | * Download file of a resource node. |
||
| 252 | */ |
||
| 253 | #[Route('/{tool}/{type}/{id}/download', name: 'chamilo_core_resource_download', methods: ['GET'])] |
||
| 370 | } |
||
| 371 | |||
| 372 | #[Route('/{tool}/{type}/{id}/change_visibility', name: 'chamilo_core_resource_change_visibility', methods: ['POST'])] |
||
| 373 | public function changeVisibility( |
||
| 374 | Request $request, |
||
| 375 | EntityManagerInterface $entityManager, |
||
| 376 | SerializerInterface $serializer, |
||
| 377 | Security $security, |
||
| 378 | ): Response { |
||
| 379 | /** @var User $user */ |
||
| 380 | $user = $security->getUser(); |
||
| 381 | $isAdmin = ($user->isSuperAdmin() || $user->isAdmin()); |
||
| 382 | $isCourseTeacher = ($user->hasRole('ROLE_CURRENT_COURSE_TEACHER') || $user->hasRole('ROLE_CURRENT_COURSE_SESSION_TEACHER')); |
||
| 383 | |||
| 384 | if (!($isCourseTeacher || $isAdmin)) { |
||
| 385 | throw new AccessDeniedHttpException(); |
||
| 386 | } |
||
| 387 | |||
| 388 | $session = null; |
||
| 389 | if ($this->getSession()) { |
||
| 390 | $sessionId = $this->getSession()->getId(); |
||
| 391 | $session = $entityManager->getRepository(Session::class)->find($sessionId); |
||
| 392 | } |
||
| 393 | $courseId = $this->getCourse()->getId(); |
||
| 394 | $course = $entityManager->getRepository(Course::class)->find($courseId); |
||
| 395 | $id = $request->attributes->getInt('id'); |
||
| 396 | $resourceNode = $this->getResourceNodeRepository()->findOneBy(['id' => $id]); |
||
| 397 | |||
| 398 | if (null === $resourceNode) { |
||
| 399 | throw new NotFoundHttpException($this->trans('Resource not found')); |
||
| 400 | } |
||
| 401 | |||
| 402 | $link = null; |
||
| 403 | foreach ($resourceNode->getResourceLinks() as $resourceLink) { |
||
| 404 | if ($resourceLink->getSession() === $session) { |
||
| 405 | $link = $resourceLink; |
||
| 406 | |||
| 407 | break; |
||
| 408 | } |
||
| 409 | } |
||
| 410 | |||
| 411 | if (null === $link) { |
||
| 412 | $link = new ResourceLink(); |
||
| 413 | $link->setResourceNode($resourceNode) |
||
| 414 | ->setSession($session) |
||
| 415 | ->setCourse($course) |
||
| 416 | ->setVisibility(ResourceLink::VISIBILITY_DRAFT) |
||
| 417 | ; |
||
| 418 | $entityManager->persist($link); |
||
| 419 | } else { |
||
| 420 | if (ResourceLink::VISIBILITY_PUBLISHED === $link->getVisibility()) { |
||
| 421 | $link->setVisibility(ResourceLink::VISIBILITY_DRAFT); |
||
| 422 | } else { |
||
| 423 | $link->setVisibility(ResourceLink::VISIBILITY_PUBLISHED); |
||
| 424 | } |
||
| 425 | } |
||
| 426 | |||
| 427 | $entityManager->flush(); |
||
| 428 | |||
| 429 | $json = $serializer->serialize( |
||
| 430 | $link, |
||
| 431 | 'json', |
||
| 432 | [ |
||
| 433 | 'groups' => ['ctool:read'], |
||
| 434 | ] |
||
| 435 | ); |
||
| 436 | |||
| 437 | return JsonResponse::fromJsonString($json); |
||
| 438 | } |
||
| 439 | |||
| 440 | #[Route( |
||
| 441 | '/{tool}/{type}/change_visibility/{visibility}', |
||
| 442 | name: 'chamilo_core_resource_change_visibility_all', |
||
| 443 | methods: ['POST'] |
||
| 444 | )] |
||
| 445 | public function changeVisibilityAll( |
||
| 446 | Request $request, |
||
| 447 | CToolRepository $toolRepository, |
||
| 448 | CShortcutRepository $shortcutRepository, |
||
| 449 | ToolChain $toolChain, |
||
| 450 | EntityManagerInterface $entityManager, |
||
| 451 | Security $security |
||
| 452 | ): Response { |
||
| 453 | /** @var User $user */ |
||
| 454 | $user = $security->getUser(); |
||
| 455 | $isAdmin = ($user->isSuperAdmin() || $user->isAdmin()); |
||
| 456 | $isCourseTeacher = ($user->hasRole('ROLE_CURRENT_COURSE_TEACHER') || $user->hasRole('ROLE_CURRENT_COURSE_SESSION_TEACHER')); |
||
| 457 | |||
| 458 | if (!($isCourseTeacher || $isAdmin)) { |
||
| 459 | throw new AccessDeniedHttpException(); |
||
| 460 | } |
||
| 461 | |||
| 462 | $visibility = $request->attributes->get('visibility'); |
||
| 463 | |||
| 464 | $session = null; |
||
| 465 | if ($this->getSession()) { |
||
| 466 | $sessionId = $this->getSession()->getId(); |
||
| 467 | $session = $entityManager->getRepository(Session::class)->find($sessionId); |
||
| 468 | } |
||
| 469 | $courseId = $this->getCourse()->getId(); |
||
| 470 | $course = $entityManager->getRepository(Course::class)->find($courseId); |
||
| 471 | |||
| 472 | $result = $toolRepository->getResourcesByCourse($course, $session) |
||
| 473 | ->addSelect('tool') |
||
| 474 | ->innerJoin('resource.tool', 'tool') |
||
| 475 | ->getQuery() |
||
| 476 | ->getResult() |
||
| 477 | ; |
||
| 478 | |||
| 479 | $skipTools = ['course_tool', |
||
| 480 | // 'chat', |
||
| 481 | // 'notebook', |
||
| 482 | // 'wiki' |
||
| 483 | ]; |
||
| 484 | |||
| 485 | /** @var CTool $item */ |
||
| 486 | foreach ($result as $item) { |
||
| 487 | if (\in_array($item->getTitle(), $skipTools, true)) { |
||
| 488 | continue; |
||
| 489 | } |
||
| 490 | $toolModel = $toolChain->getToolFromName($item->getTool()->getTitle()); |
||
| 491 | |||
| 492 | if (!\in_array($toolModel->getCategory(), ['authoring', 'interaction'], true)) { |
||
| 493 | continue; |
||
| 494 | } |
||
| 495 | |||
| 496 | $resourceNode = $item->getResourceNode(); |
||
| 497 | |||
| 498 | /** @var ResourceLink $link */ |
||
| 499 | $link = null; |
||
| 500 | foreach ($resourceNode->getResourceLinks() as $resourceLink) { |
||
| 501 | if ($resourceLink->getSession() === $session) { |
||
| 502 | $link = $resourceLink; |
||
| 503 | |||
| 504 | break; |
||
| 505 | } |
||
| 506 | } |
||
| 507 | |||
| 508 | if (null === $link) { |
||
| 509 | $link = new ResourceLink(); |
||
| 510 | $link->setResourceNode($resourceNode) |
||
| 511 | ->setSession($session) |
||
| 512 | ->setCourse($course) |
||
| 513 | ->setVisibility(ResourceLink::VISIBILITY_DRAFT) |
||
| 514 | ; |
||
| 515 | $entityManager->persist($link); |
||
| 516 | } |
||
| 517 | |||
| 518 | if ('show' === $visibility) { |
||
| 519 | $link->setVisibility(ResourceLink::VISIBILITY_PUBLISHED); |
||
| 520 | } elseif ('hide' === $visibility) { |
||
| 521 | $link->setVisibility(ResourceLink::VISIBILITY_DRAFT); |
||
| 522 | } |
||
| 523 | } |
||
| 524 | |||
| 525 | $entityManager->flush(); |
||
| 526 | |||
| 527 | return new Response(null, Response::HTTP_NO_CONTENT); |
||
| 528 | } |
||
| 529 | |||
| 530 | #[Route('/resource_files/{resourceNodeId}/variants', name: 'chamilo_core_resource_files_variants', methods: ['GET'])] |
||
| 531 | public function getVariants(string $resourceNodeId, EntityManagerInterface $em): JsonResponse |
||
| 532 | { |
||
| 533 | $variants = $em->getRepository(ResourceFile::class)->createQueryBuilder('rf') |
||
| 534 | ->join('rf.resourceNode', 'rn') |
||
| 535 | ->leftJoin('rn.creator', 'creator') |
||
| 536 | ->where('rf.resourceNode = :resourceNodeId') |
||
| 537 | ->andWhere('rf.accessUrl IS NOT NULL') |
||
| 538 | ->setParameter('resourceNodeId', $resourceNodeId) |
||
| 539 | ->getQuery() |
||
| 540 | ->getResult() |
||
| 541 | ; |
||
| 542 | |||
| 543 | $data = []; |
||
| 544 | |||
| 545 | /** @var ResourceFile $variant */ |
||
| 546 | foreach ($variants as $variant) { |
||
| 547 | $data[] = [ |
||
| 548 | 'id' => $variant->getId(), |
||
| 549 | 'title' => $variant->getOriginalName(), |
||
| 550 | 'mimeType' => $variant->getMimeType(), |
||
| 551 | 'size' => $variant->getSize(), |
||
| 552 | 'updatedAt' => $variant->getUpdatedAt()->format('Y-m-d H:i:s'), |
||
| 553 | 'url' => $variant->getAccessUrl() ? $variant->getAccessUrl()->getUrl() : null, |
||
| 554 | 'path' => $this->resourceNodeRepository->getResourceFileUrl($variant->getResourceNode(), [], null, $variant), |
||
| 555 | 'creator' => $variant->getResourceNode()->getCreator() ? $variant->getResourceNode()->getCreator()->getFullName() : 'Unknown', |
||
| 556 | ]; |
||
| 557 | } |
||
| 558 | |||
| 559 | return $this->json($data); |
||
| 560 | } |
||
| 561 | |||
| 562 | #[Route('/resource_files/{id}/delete_variant', methods: ['DELETE'], name: 'chamilo_core_resource_files_delete_variant')] |
||
| 574 | } |
||
| 575 | |||
| 576 | private function processFile(Request $request, ResourceNode $resourceNode, string $mode = 'show', string $filter = '', ?array $allUserInfo = null, ?ResourceFile $resourceFile = null): mixed |
||
| 577 | { |
||
| 578 | $this->denyAccessUnlessGranted( |
||
| 579 | ResourceNodeVoter::VIEW, |
||
| 580 | $resourceNode, |
||
| 581 | $this->trans('Unauthorised view access to resource') |
||
| 582 | ); |
||
| 583 | |||
| 584 | $resourceFile ??= $resourceNode->getResourceFiles()->first(); |
||
| 585 | |||
| 586 | if (!$resourceFile) { |
||
| 587 | throw $this->createNotFoundException($this->trans('File not found for resource')); |
||
| 588 | } |
||
| 589 | |||
| 590 | $fileName = $resourceFile->getOriginalName(); |
||
| 591 | $fileSize = $resourceFile->getSize(); |
||
| 592 | $mimeType = $resourceFile->getMimeType() ?: ''; |
||
| 593 | [$start, $end, $length] = $this->getRange($request, $fileSize); |
||
| 594 | $resourceNodeRepo = $this->getResourceNodeRepository(); |
||
| 595 | |||
| 596 | // Convert the file name to ASCII using iconv |
||
| 597 | $fileName = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $fileName); |
||
| 598 | |||
| 599 | // MIME normalization for HTML |
||
| 600 | $looksLikeHtmlByExt = (bool) preg_match('/\.x?html?$/i', (string) $fileName); |
||
| 601 | if ('' === $mimeType || false === stripos($mimeType, 'html')) { |
||
| 602 | if ($looksLikeHtmlByExt) { |
||
| 603 | $mimeType = 'text/html; charset=UTF-8'; |
||
| 604 | } |
||
| 605 | } |
||
| 606 | |||
| 607 | switch ($mode) { |
||
| 608 | case 'download': |
||
| 609 | $forceDownload = true; |
||
| 610 | |||
| 611 | break; |
||
| 612 | |||
| 613 | case 'show': |
||
| 614 | default: |
||
| 615 | $forceDownload = false; |
||
| 616 | // If it's an image then send it to Glide. |
||
| 617 | if (str_contains($mimeType, 'image')) { |
||
| 618 | $glide = $this->getGlide(); |
||
| 619 | $server = $glide->getServer(); |
||
| 620 | $params = $request->query->all(); |
||
| 621 | |||
| 622 | // The filter overwrites the params from GET. |
||
| 623 | if (!empty($filter)) { |
||
| 624 | $params = $glide->getFilters()[$filter] ?? []; |
||
| 625 | } |
||
| 626 | |||
| 627 | // The image was cropped manually by the user, so we force to render this version, |
||
| 628 | // no matter other crop parameters. |
||
| 629 | $crop = $resourceFile->getCrop(); |
||
| 630 | if (!empty($crop)) { |
||
| 631 | $params['crop'] = $crop; |
||
| 632 | } |
||
| 633 | |||
| 634 | $filePath = $resourceNodeRepo->getFilename($resourceFile); |
||
| 635 | |||
| 636 | $response = $server->getImageResponse($filePath, $params); |
||
| 637 | |||
| 638 | $disposition = $response->headers->makeDisposition( |
||
| 639 | ResponseHeaderBag::DISPOSITION_INLINE, |
||
| 640 | $fileName |
||
| 641 | ); |
||
| 642 | $response->headers->set('Content-Disposition', $disposition); |
||
| 643 | |||
| 644 | return $response; |
||
| 645 | } |
||
| 646 | |||
| 647 | // Modify the HTML content before displaying it. |
||
| 648 | if (str_contains($mimeType, 'html')) { |
||
| 649 | $content = $resourceNodeRepo->getResourceNodeFileContent($resourceNode, $resourceFile); |
||
| 650 | |||
| 651 | if (null !== $allUserInfo) { |
||
| 652 | $tagsToReplace = $allUserInfo[0]; |
||
| 653 | $replacementValues = $allUserInfo[1]; |
||
| 654 | $content = str_replace($tagsToReplace, $replacementValues, $content); |
||
| 655 | } |
||
| 656 | |||
| 657 | $content = $this->injectGlossaryJs($request, $content, $resourceNode); |
||
| 658 | |||
| 659 | $response = new Response(); |
||
| 660 | $disposition = $response->headers->makeDisposition( |
||
| 661 | ResponseHeaderBag::DISPOSITION_INLINE, |
||
| 662 | $fileName |
||
| 663 | ); |
||
| 664 | $response->headers->set('Content-Disposition', $disposition); |
||
| 665 | $response->headers->set('Content-Type', 'text/html; charset=UTF-8'); |
||
| 666 | |||
| 667 | // Existing translate_html logic |
||
| 668 | if ('true' === $this->getSettingsManager()->getSetting('editor.translate_html')) { |
||
| 669 | $user = $this->userHelper->getCurrent(); |
||
| 670 | if (null !== $user) { |
||
| 671 | // Overwrite user_json, otherwise it will be loaded by the TwigListener.php |
||
| 672 | $userJson = json_encode(['locale' => $user->getLocale()]); |
||
| 673 | $js = $this->renderView( |
||
| 674 | '@ChamiloCore/Layout/document.html.twig', |
||
| 675 | ['breadcrumb' => '', 'user_json' => $userJson] |
||
| 676 | ); |
||
| 677 | // Insert inside the head tag. |
||
| 678 | $content = str_replace('</head>', $js.'</head>', $content); |
||
| 679 | } |
||
| 680 | } |
||
| 681 | $response->setContent($content); |
||
| 682 | |||
| 683 | return $response; |
||
| 684 | } |
||
| 685 | |||
| 686 | break; |
||
| 687 | } |
||
| 688 | |||
| 689 | $response = new StreamedResponse( |
||
| 690 | function () use ($resourceNodeRepo, $resourceFile, $start, $length): void { |
||
| 691 | $this->streamFileContent($resourceNodeRepo, $resourceFile, $start, $length); |
||
| 692 | } |
||
| 693 | ); |
||
| 694 | |||
| 695 | $disposition = $response->headers->makeDisposition( |
||
| 696 | $forceDownload ? ResponseHeaderBag::DISPOSITION_ATTACHMENT : ResponseHeaderBag::DISPOSITION_INLINE, |
||
| 697 | $fileName |
||
| 698 | ); |
||
| 699 | $response->headers->set('Content-Disposition', $disposition); |
||
| 700 | $response->headers->set('Content-Type', $mimeType ?: 'application/octet-stream'); |
||
| 701 | $response->headers->set('Content-Length', (string) $length); |
||
| 702 | $response->headers->set('Accept-Ranges', 'bytes'); |
||
| 703 | $response->headers->set('Content-Range', "bytes $start-$end/$fileSize"); |
||
| 704 | $response->setStatusCode( |
||
| 705 | $start > 0 || $end < $fileSize - 1 ? Response::HTTP_PARTIAL_CONTENT : Response::HTTP_OK |
||
| 706 | ); |
||
| 707 | |||
| 708 | return $response; |
||
| 709 | } |
||
| 710 | |||
| 711 | private function injectGlossaryJs( |
||
| 754 | } |
||
| 755 | |||
| 756 | |||
| 757 | /** |
||
| 758 | * Normalize generated HTML documents coming from templates/editors. |
||
| 759 | * |
||
| 760 | * This method tries to fix the pattern: |
||
| 761 | * <head>...</head><!DOCTYPE html><html>...<head>...</head><body>...</body></html> |
||
| 762 | * |
||
| 763 | * It will: |
||
| 764 | * - Extract the first <head>...</head> block (if it appears before <!DOCTYPE). |
||
| 765 | * - Keep the proper <!DOCTYPE html><html>... document. |
||
| 766 | * - Inject the inner content of the first head into the main <head> of the document. |
||
| 767 | */ |
||
| 768 | private function normalizeGeneratedHtml(string $content): string |
||
| 830 | } |
||
| 831 | |||
| 832 | |||
| 833 | private function getRange(Request $request, int $fileSize): array |
||
| 852 | } |
||
| 853 | |||
| 854 | private function streamFileContent(ResourceNodeRepository $resourceNodeRepo, ResourceFile $resourceFile, int $start, int $length): void |
||
| 873 |