| Total Complexity | 88 |
| Total Lines | 734 |
| 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 |
||
| 56 | #[Route('/r')] |
||
| 57 | class ResourceController extends AbstractResourceController implements CourseControllerInterface |
||
| 58 | { |
||
| 59 | use ControllerTrait; |
||
| 60 | use CourseControllerTrait; |
||
| 61 | use GradebookControllerTrait; |
||
| 62 | use ResourceControllerTrait; |
||
| 63 | |||
| 64 | public function __construct( |
||
| 65 | private readonly UserHelper $userHelper, |
||
| 66 | private readonly ResourceNodeRepository $resourceNodeRepository, |
||
| 67 | private readonly ResourceFileRepository $resourceFileRepository |
||
| 68 | ) {} |
||
| 69 | |||
| 70 | #[Route(path: '/{tool}/{type}/{id}/disk_space', methods: ['GET', 'POST'], name: 'chamilo_core_resource_disk_space')] |
||
| 71 | public function diskSpace(Request $request): Response |
||
| 72 | { |
||
| 73 | $nodeId = $request->get('id'); |
||
| 74 | $repository = $this->getRepositoryFromRequest($request); |
||
| 75 | |||
| 76 | /** @var ResourceNode $resourceNode */ |
||
| 77 | $resourceNode = $repository->getResourceNodeRepository()->find($nodeId); |
||
| 78 | |||
| 79 | $this->denyAccessUnlessGranted( |
||
| 80 | ResourceNodeVoter::VIEW, |
||
| 81 | $resourceNode, |
||
| 82 | $this->trans('Unauthorised access to resource') |
||
| 83 | ); |
||
| 84 | |||
| 85 | $course = $this->getCourse(); |
||
| 86 | $totalSize = 0; |
||
| 87 | if (null !== $course) { |
||
| 88 | $totalSize = $course->getDiskQuota(); |
||
| 89 | } |
||
| 90 | |||
| 91 | $size = $repository->getResourceNodeRepository()->getSize( |
||
| 92 | $resourceNode, |
||
| 93 | $repository->getResourceType(), |
||
| 94 | $course |
||
| 95 | ); |
||
| 96 | |||
| 97 | $labels[] = $course->getTitle(); |
||
|
|
|||
| 98 | $data[] = $size; |
||
| 99 | $sessions = $course->getSessions(); |
||
| 100 | |||
| 101 | foreach ($sessions as $sessionRelCourse) { |
||
| 102 | $session = $sessionRelCourse->getSession(); |
||
| 103 | |||
| 104 | $labels[] = $course->getTitle().' - '.$session->getTitle(); |
||
| 105 | $size = $repository->getResourceNodeRepository()->getSize( |
||
| 106 | $resourceNode, |
||
| 107 | $repository->getResourceType(), |
||
| 108 | $course, |
||
| 109 | $session |
||
| 110 | ); |
||
| 111 | $data[] = $size; |
||
| 112 | } |
||
| 113 | |||
| 114 | /*$groups = $course->getGroups(); |
||
| 115 | foreach ($groups as $group) { |
||
| 116 | $labels[] = $course->getTitle().' - '.$group->getTitle(); |
||
| 117 | $size = $repository->getResourceNodeRepository()->getSize( |
||
| 118 | $resourceNode, |
||
| 119 | $repository->getResourceType(), |
||
| 120 | $course, |
||
| 121 | null, |
||
| 122 | $group |
||
| 123 | ); |
||
| 124 | $data[] = $size; |
||
| 125 | }*/ |
||
| 126 | |||
| 127 | $used = array_sum($data); |
||
| 128 | $labels[] = $this->trans('Free space on disk'); |
||
| 129 | $data[] = $totalSize - $used; |
||
| 130 | |||
| 131 | return $this->render( |
||
| 132 | '@ChamiloCore/Resource/disk_space.html.twig', |
||
| 133 | [ |
||
| 134 | 'resourceNode' => $resourceNode, |
||
| 135 | 'labels' => $labels, |
||
| 136 | 'data' => $data, |
||
| 137 | ] |
||
| 138 | ); |
||
| 139 | } |
||
| 140 | |||
| 141 | /** |
||
| 142 | * View file of a resource node. |
||
| 143 | */ |
||
| 144 | #[Route('/{tool}/{type}/{id}/view', name: 'chamilo_core_resource_view', methods: ['GET'])] |
||
| 145 | public function view( |
||
| 146 | Request $request, |
||
| 147 | TrackEDownloadsRepository $trackEDownloadsRepository, |
||
| 148 | ResourceFileHelper $resourceFileHelper, |
||
| 149 | ): Response { |
||
| 150 | $id = $request->get('id'); |
||
| 151 | $resourceFileId = $request->get('resourceFileId'); |
||
| 152 | $filter = (string) $request->get('filter'); |
||
| 153 | $resourceNode = $this->getResourceNodeRepository()->findOneBy(['uuid' => $id]); |
||
| 154 | |||
| 155 | if (null === $resourceNode) { |
||
| 156 | throw new FileNotFoundException($this->trans('Resource not found')); |
||
| 157 | } |
||
| 158 | |||
| 159 | $resourceFile = null; |
||
| 160 | if ($resourceFileId) { |
||
| 161 | $resourceFile = $this->resourceFileRepository->find($resourceFileId); |
||
| 162 | } |
||
| 163 | |||
| 164 | $resourceFile ??= $resourceFileHelper->resolveResourceFileByAccessUrl($resourceNode); |
||
| 165 | |||
| 166 | if (!$resourceFile) { |
||
| 167 | throw new FileNotFoundException($this->trans('Resource file not found for the given resource node')); |
||
| 168 | } |
||
| 169 | |||
| 170 | $user = $this->userHelper->getCurrent(); |
||
| 171 | $firstResourceLink = $resourceNode->getResourceLinks()->first(); |
||
| 172 | if ($firstResourceLink && $user) { |
||
| 173 | $url = $resourceFile->getOriginalName(); |
||
| 174 | $trackEDownloadsRepository->saveDownload($user, $firstResourceLink, $url); |
||
| 175 | } |
||
| 176 | |||
| 177 | $cid = (int) $request->query->get('cid'); |
||
| 178 | $sid = (int) $request->query->get('sid'); |
||
| 179 | $allUserInfo = null; |
||
| 180 | if ($cid && $user) { |
||
| 181 | $allUserInfo = $this->getAllInfoToCertificate( |
||
| 182 | $user->getId(), |
||
| 183 | $cid, |
||
| 184 | $sid, |
||
| 185 | false |
||
| 186 | ); |
||
| 187 | } |
||
| 188 | |||
| 189 | return $this->processFile($request, $resourceNode, 'show', $filter, $allUserInfo, $resourceFile); |
||
| 190 | } |
||
| 191 | |||
| 192 | /** |
||
| 193 | * Redirect resource to link. |
||
| 194 | * |
||
| 195 | * @return RedirectResponse|void |
||
| 196 | */ |
||
| 197 | #[Route('/{tool}/{type}/{id}/link', name: 'chamilo_core_resource_link', methods: ['GET'])] |
||
| 198 | public function link(Request $request, RouterInterface $router, CLinkRepository $cLinkRepository): RedirectResponse |
||
| 199 | { |
||
| 200 | $tool = $request->get('tool'); |
||
| 201 | $type = $request->get('type'); |
||
| 202 | $id = $request->get('id'); |
||
| 203 | $resourceNode = $this->getResourceNodeRepository()->find($id); |
||
| 204 | |||
| 205 | if (null === $resourceNode) { |
||
| 206 | throw new FileNotFoundException('Resource not found'); |
||
| 207 | } |
||
| 208 | |||
| 209 | if ('course_tool' === $tool && 'links' === $type) { |
||
| 210 | $cLink = $cLinkRepository->findOneBy(['resourceNode' => $resourceNode]); |
||
| 211 | if ($cLink) { |
||
| 212 | $url = $cLink->getUrl(); |
||
| 213 | |||
| 214 | return $this->redirect($url); |
||
| 215 | } |
||
| 216 | |||
| 217 | throw new FileNotFoundException('CLink not found for the given resource node'); |
||
| 218 | } else { |
||
| 219 | $repo = $this->getRepositoryFromRequest($request); |
||
| 220 | if ($repo instanceof ResourceWithLinkInterface) { |
||
| 221 | $resource = $repo->getResourceFromResourceNode($resourceNode->getId()); |
||
| 222 | $url = $repo->getLink($resource, $router, $this->getCourseUrlQueryToArray()); |
||
| 223 | |||
| 224 | return $this->redirect($url); |
||
| 225 | } |
||
| 226 | |||
| 227 | $this->abort('No redirect'); |
||
| 228 | } |
||
| 229 | } |
||
| 230 | |||
| 231 | /** |
||
| 232 | * Download file of a resource node. |
||
| 233 | */ |
||
| 234 | #[Route('/{tool}/{type}/{id}/download', name: 'chamilo_core_resource_download', methods: ['GET'])] |
||
| 235 | public function download( |
||
| 236 | Request $request, |
||
| 237 | TrackEDownloadsRepository $trackEDownloadsRepository, |
||
| 238 | ResourceFileHelper $resourceFileHelper, |
||
| 239 | ): Response { |
||
| 240 | $id = $request->get('id'); |
||
| 241 | $resourceNode = $this->getResourceNodeRepository()->findOneBy(['uuid' => $id]); |
||
| 242 | |||
| 243 | if (null === $resourceNode) { |
||
| 244 | throw new FileNotFoundException($this->trans('Resource not found')); |
||
| 245 | } |
||
| 246 | |||
| 247 | $repo = $this->getRepositoryFromRequest($request); |
||
| 248 | |||
| 249 | $this->denyAccessUnlessGranted( |
||
| 250 | ResourceNodeVoter::VIEW, |
||
| 251 | $resourceNode, |
||
| 252 | $this->trans('Unauthorised access to resource') |
||
| 253 | ); |
||
| 254 | |||
| 255 | $resourceFile = $resourceFileHelper->resolveResourceFileByAccessUrl($resourceNode); |
||
| 256 | |||
| 257 | // If resource node has a file just download it. Don't download the children. |
||
| 258 | if ($resourceFile) { |
||
| 259 | $user = $this->userHelper->getCurrent(); |
||
| 260 | $firstResourceLink = $resourceNode->getResourceLinks()->first(); |
||
| 261 | |||
| 262 | if ($firstResourceLink && $user) { |
||
| 263 | $url = $resourceFile->getOriginalName(); |
||
| 264 | $trackEDownloadsRepository->saveDownload($user, $firstResourceLink, $url); |
||
| 265 | } |
||
| 266 | |||
| 267 | // Redirect to download single file. |
||
| 268 | return $this->processFile($request, $resourceNode, 'download', '', null, $resourceFile); |
||
| 269 | } |
||
| 270 | |||
| 271 | $zipName = $resourceNode->getSlug().'.zip'; |
||
| 272 | $resourceNodeRepo = $repo->getResourceNodeRepository(); |
||
| 273 | $type = $repo->getResourceType(); |
||
| 274 | |||
| 275 | $criteria = Criteria::create() |
||
| 276 | ->where(Criteria::expr()->neq('resourceFiles', null)) // must have a file |
||
| 277 | ->andWhere(Criteria::expr()->eq('resourceType', $type)) // only download same type |
||
| 278 | ; |
||
| 279 | |||
| 280 | $qb = $resourceNodeRepo->getChildrenQueryBuilder($resourceNode); |
||
| 281 | $qbAlias = $qb->getRootAliases()[0]; |
||
| 282 | |||
| 283 | $qb |
||
| 284 | ->leftJoin(\sprintf('%s.resourceFiles', $qbAlias), 'resourceFiles') // must have a file |
||
| 285 | ->addCriteria($criteria) |
||
| 286 | ; |
||
| 287 | |||
| 288 | /** @var ArrayCollection|ResourceNode[] $children */ |
||
| 289 | $children = $qb->getQuery()->getResult(); |
||
| 290 | $count = \count($children); |
||
| 291 | if (0 === $count) { |
||
| 292 | $params = $this->getResourceParams($request); |
||
| 293 | $params['id'] = $id; |
||
| 294 | |||
| 295 | $this->addFlash('warning', $this->trans('No files')); |
||
| 296 | |||
| 297 | return $this->redirectToRoute('chamilo_core_resource_list', $params); |
||
| 298 | } |
||
| 299 | |||
| 300 | $response = new StreamedResponse( |
||
| 301 | function () use ($zipName, $children, $repo): void { |
||
| 302 | // Define suitable options for ZipStream Archive. |
||
| 303 | $options = new Archive(); |
||
| 304 | $options->setContentType('application/octet-stream'); |
||
| 305 | // initialise zipstream with output zip filename and options. |
||
| 306 | $zip = new ZipStream($zipName, $options); |
||
| 307 | |||
| 308 | /** @var ResourceNode $node */ |
||
| 309 | foreach ($children as $node) { |
||
| 310 | $resourceFiles = $node->getResourceFiles(); |
||
| 311 | $resourceFile = $resourceFiles->filter(fn ($file) => null === $file->getAccessUrl())->first(); |
||
| 312 | |||
| 313 | if ($resourceFile) { |
||
| 314 | $stream = $repo->getResourceNodeFileStream($node); |
||
| 315 | $fileName = $resourceFile->getOriginalName(); |
||
| 316 | $zip->addFileFromStream($fileName, $stream); |
||
| 317 | } |
||
| 318 | } |
||
| 319 | $zip->finish(); |
||
| 320 | } |
||
| 321 | ); |
||
| 322 | |||
| 323 | // Convert the file name to ASCII using iconv |
||
| 324 | $zipName = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $zipName); |
||
| 325 | |||
| 326 | $disposition = $response->headers->makeDisposition( |
||
| 327 | ResponseHeaderBag::DISPOSITION_ATTACHMENT, |
||
| 328 | $zipName // Transliterator::transliterate($zipName) |
||
| 329 | ); |
||
| 330 | $response->headers->set('Content-Disposition', $disposition); |
||
| 331 | $response->headers->set('Content-Type', 'application/octet-stream'); |
||
| 332 | |||
| 333 | return $response; |
||
| 334 | } |
||
| 335 | |||
| 336 | #[Route('/{tool}/{type}/{id}/change_visibility', name: 'chamilo_core_resource_change_visibility', methods: ['POST'])] |
||
| 337 | public function changeVisibility( |
||
| 338 | Request $request, |
||
| 339 | EntityManagerInterface $entityManager, |
||
| 340 | SerializerInterface $serializer, |
||
| 341 | Security $security, |
||
| 342 | ): Response { |
||
| 343 | /** @var User $user */ |
||
| 344 | $user = $security->getUser(); |
||
| 345 | $isAdmin = ($user->isSuperAdmin() || $user->isAdmin()); |
||
| 346 | $isCourseTeacher = ($user->hasRole('ROLE_CURRENT_COURSE_TEACHER') || $user->hasRole('ROLE_CURRENT_COURSE_SESSION_TEACHER')); |
||
| 347 | |||
| 348 | if (!($isCourseTeacher || $isAdmin)) { |
||
| 349 | throw new AccessDeniedHttpException(); |
||
| 350 | } |
||
| 351 | |||
| 352 | $session = null; |
||
| 353 | if ($this->getSession()) { |
||
| 354 | $sessionId = $this->getSession()->getId(); |
||
| 355 | $session = $entityManager->getRepository(Session::class)->find($sessionId); |
||
| 356 | } |
||
| 357 | $courseId = $this->getCourse()->getId(); |
||
| 358 | $course = $entityManager->getRepository(Course::class)->find($courseId); |
||
| 359 | $id = $request->attributes->getInt('id'); |
||
| 360 | $resourceNode = $this->getResourceNodeRepository()->findOneBy(['id' => $id]); |
||
| 361 | |||
| 362 | if (null === $resourceNode) { |
||
| 363 | throw new NotFoundHttpException($this->trans('Resource not found')); |
||
| 364 | } |
||
| 365 | |||
| 366 | $link = null; |
||
| 367 | foreach ($resourceNode->getResourceLinks() as $resourceLink) { |
||
| 368 | if ($resourceLink->getSession() === $session) { |
||
| 369 | $link = $resourceLink; |
||
| 370 | |||
| 371 | break; |
||
| 372 | } |
||
| 373 | } |
||
| 374 | |||
| 375 | if (null === $link) { |
||
| 376 | $link = new ResourceLink(); |
||
| 377 | $link->setResourceNode($resourceNode) |
||
| 378 | ->setSession($session) |
||
| 379 | ->setCourse($course) |
||
| 380 | ->setVisibility(ResourceLink::VISIBILITY_DRAFT) |
||
| 381 | ; |
||
| 382 | $entityManager->persist($link); |
||
| 383 | } else { |
||
| 384 | if (ResourceLink::VISIBILITY_PUBLISHED === $link->getVisibility()) { |
||
| 385 | $link->setVisibility(ResourceLink::VISIBILITY_DRAFT); |
||
| 386 | } else { |
||
| 387 | $link->setVisibility(ResourceLink::VISIBILITY_PUBLISHED); |
||
| 388 | } |
||
| 389 | } |
||
| 390 | |||
| 391 | $entityManager->flush(); |
||
| 392 | |||
| 393 | $json = $serializer->serialize( |
||
| 394 | $link, |
||
| 395 | 'json', |
||
| 396 | [ |
||
| 397 | 'groups' => ['ctool:read'], |
||
| 398 | ] |
||
| 399 | ); |
||
| 400 | |||
| 401 | return JsonResponse::fromJsonString($json); |
||
| 402 | } |
||
| 403 | |||
| 404 | #[Route( |
||
| 405 | '/{tool}/{type}/change_visibility/{visibility}', |
||
| 406 | name: 'chamilo_core_resource_change_visibility_all', |
||
| 407 | methods: ['POST'] |
||
| 408 | )] |
||
| 409 | public function changeVisibilityAll( |
||
| 410 | Request $request, |
||
| 411 | CToolRepository $toolRepository, |
||
| 412 | CShortcutRepository $shortcutRepository, |
||
| 413 | ToolChain $toolChain, |
||
| 414 | EntityManagerInterface $entityManager, |
||
| 415 | Security $security |
||
| 416 | ): Response { |
||
| 417 | /** @var User $user */ |
||
| 418 | $user = $security->getUser(); |
||
| 419 | $isAdmin = ($user->isSuperAdmin() || $user->isAdmin()); |
||
| 420 | $isCourseTeacher = ($user->hasRole('ROLE_CURRENT_COURSE_TEACHER') || $user->hasRole('ROLE_CURRENT_COURSE_SESSION_TEACHER')); |
||
| 421 | |||
| 422 | if (!($isCourseTeacher || $isAdmin)) { |
||
| 423 | throw new AccessDeniedHttpException(); |
||
| 424 | } |
||
| 425 | |||
| 426 | $visibility = $request->attributes->get('visibility'); |
||
| 427 | |||
| 428 | $session = null; |
||
| 429 | if ($this->getSession()) { |
||
| 430 | $sessionId = $this->getSession()->getId(); |
||
| 431 | $session = $entityManager->getRepository(Session::class)->find($sessionId); |
||
| 432 | } |
||
| 433 | $courseId = $this->getCourse()->getId(); |
||
| 434 | $course = $entityManager->getRepository(Course::class)->find($courseId); |
||
| 435 | |||
| 436 | $result = $toolRepository->getResourcesByCourse($course, $session) |
||
| 437 | ->addSelect('tool') |
||
| 438 | ->innerJoin('resource.tool', 'tool') |
||
| 439 | ->getQuery() |
||
| 440 | ->getResult() |
||
| 441 | ; |
||
| 442 | |||
| 443 | $skipTools = ['course_tool', |
||
| 444 | // 'chat', |
||
| 445 | // 'notebook', |
||
| 446 | // 'wiki' |
||
| 447 | ]; |
||
| 448 | |||
| 449 | /** @var CTool $item */ |
||
| 450 | foreach ($result as $item) { |
||
| 451 | if (\in_array($item->getTitle(), $skipTools, true)) { |
||
| 452 | continue; |
||
| 453 | } |
||
| 454 | $toolModel = $toolChain->getToolFromName($item->getTool()->getTitle()); |
||
| 455 | |||
| 456 | if (!\in_array($toolModel->getCategory(), ['authoring', 'interaction'], true)) { |
||
| 457 | continue; |
||
| 458 | } |
||
| 459 | |||
| 460 | $resourceNode = $item->getResourceNode(); |
||
| 461 | |||
| 462 | /** @var ResourceLink $link */ |
||
| 463 | $link = null; |
||
| 464 | foreach ($resourceNode->getResourceLinks() as $resourceLink) { |
||
| 465 | if ($resourceLink->getSession() === $session) { |
||
| 466 | $link = $resourceLink; |
||
| 467 | |||
| 468 | break; |
||
| 469 | } |
||
| 470 | } |
||
| 471 | |||
| 472 | if (null === $link) { |
||
| 473 | $link = new ResourceLink(); |
||
| 474 | $link->setResourceNode($resourceNode) |
||
| 475 | ->setSession($session) |
||
| 476 | ->setCourse($course) |
||
| 477 | ->setVisibility(ResourceLink::VISIBILITY_DRAFT) |
||
| 478 | ; |
||
| 479 | $entityManager->persist($link); |
||
| 480 | } |
||
| 481 | |||
| 482 | if ('show' === $visibility) { |
||
| 483 | $link->setVisibility(ResourceLink::VISIBILITY_PUBLISHED); |
||
| 484 | } elseif ('hide' === $visibility) { |
||
| 485 | $link->setVisibility(ResourceLink::VISIBILITY_DRAFT); |
||
| 486 | } |
||
| 487 | } |
||
| 488 | |||
| 489 | $entityManager->flush(); |
||
| 490 | |||
| 491 | return new Response(null, Response::HTTP_NO_CONTENT); |
||
| 492 | } |
||
| 493 | |||
| 494 | #[Route('/resource_files/{resourceNodeId}/variants', name: 'chamilo_core_resource_files_variants', methods: ['GET'])] |
||
| 495 | public function getVariants(string $resourceNodeId, EntityManagerInterface $em): JsonResponse |
||
| 496 | { |
||
| 497 | $variants = $em->getRepository(ResourceFile::class)->createQueryBuilder('rf') |
||
| 498 | ->join('rf.resourceNode', 'rn') |
||
| 499 | ->leftJoin('rn.creator', 'creator') |
||
| 500 | ->where('rf.resourceNode = :resourceNodeId') |
||
| 501 | ->andWhere('rf.accessUrl IS NOT NULL') |
||
| 502 | ->setParameter('resourceNodeId', $resourceNodeId) |
||
| 503 | ->getQuery() |
||
| 504 | ->getResult() |
||
| 505 | ; |
||
| 506 | |||
| 507 | $data = []; |
||
| 508 | |||
| 509 | /** @var ResourceFile $variant */ |
||
| 510 | foreach ($variants as $variant) { |
||
| 511 | $data[] = [ |
||
| 512 | 'id' => $variant->getId(), |
||
| 513 | 'title' => $variant->getOriginalName(), |
||
| 514 | 'mimeType' => $variant->getMimeType(), |
||
| 515 | 'size' => $variant->getSize(), |
||
| 516 | 'updatedAt' => $variant->getUpdatedAt()->format('Y-m-d H:i:s'), |
||
| 517 | 'url' => $variant->getAccessUrl() ? $variant->getAccessUrl()->getUrl() : null, |
||
| 518 | 'path' => $this->resourceNodeRepository->getResourceFileUrl($variant->getResourceNode(), [], null, $variant), |
||
| 519 | 'creator' => $variant->getResourceNode()->getCreator() ? $variant->getResourceNode()->getCreator()->getFullName() : 'Unknown', |
||
| 520 | ]; |
||
| 521 | } |
||
| 522 | |||
| 523 | return $this->json($data); |
||
| 524 | } |
||
| 525 | |||
| 526 | #[Route('/resource_files/{id}/delete_variant', methods: ['DELETE'], name: 'chamilo_core_resource_files_delete_variant')] |
||
| 527 | public function deleteVariant(int $id, EntityManagerInterface $em): JsonResponse |
||
| 528 | { |
||
| 529 | $variant = $em->getRepository(ResourceFile::class)->find($id); |
||
| 530 | if (!$variant) { |
||
| 531 | return $this->json(['error' => 'Variant not found'], Response::HTTP_NOT_FOUND); |
||
| 532 | } |
||
| 533 | |||
| 534 | $em->remove($variant); |
||
| 535 | $em->flush(); |
||
| 536 | |||
| 537 | return $this->json(['success' => true]); |
||
| 538 | } |
||
| 539 | |||
| 540 | private function processFile(Request $request, ResourceNode $resourceNode, string $mode = 'show', string $filter = '', ?array $allUserInfo = null, ?ResourceFile $resourceFile = null): mixed |
||
| 541 | { |
||
| 542 | $this->denyAccessUnlessGranted( |
||
| 543 | ResourceNodeVoter::VIEW, |
||
| 544 | $resourceNode, |
||
| 545 | $this->trans('Unauthorised view access to resource') |
||
| 546 | ); |
||
| 547 | |||
| 548 | $resourceFile ??= $resourceNode->getResourceFiles()->first(); |
||
| 549 | |||
| 550 | if (!$resourceFile) { |
||
| 551 | throw $this->createNotFoundException($this->trans('File not found for resource')); |
||
| 552 | } |
||
| 553 | |||
| 554 | $fileName = $resourceFile->getOriginalName(); |
||
| 555 | $fileSize = $resourceFile->getSize(); |
||
| 556 | $mimeType = $resourceFile->getMimeType() ?: ''; |
||
| 557 | [$start, $end, $length] = $this->getRange($request, $fileSize); |
||
| 558 | $resourceNodeRepo = $this->getResourceNodeRepository(); |
||
| 559 | |||
| 560 | // Convert the file name to ASCII using iconv |
||
| 561 | $fileName = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $fileName); |
||
| 562 | |||
| 563 | // MIME normalization for HTML |
||
| 564 | $looksLikeHtmlByExt = (bool) preg_match('/\.x?html?$/i', (string) $fileName); |
||
| 565 | if ('' === $mimeType || false === stripos($mimeType, 'html')) { |
||
| 566 | if ($looksLikeHtmlByExt) { |
||
| 567 | $mimeType = 'text/html; charset=UTF-8'; |
||
| 568 | } |
||
| 569 | } |
||
| 570 | |||
| 571 | switch ($mode) { |
||
| 572 | case 'download': |
||
| 573 | $forceDownload = true; |
||
| 574 | |||
| 575 | break; |
||
| 576 | |||
| 577 | case 'show': |
||
| 578 | default: |
||
| 579 | $forceDownload = false; |
||
| 580 | // If it's an image then send it to Glide. |
||
| 581 | if (str_contains($mimeType, 'image')) { |
||
| 582 | $glide = $this->getGlide(); |
||
| 583 | $server = $glide->getServer(); |
||
| 584 | $params = $request->query->all(); |
||
| 585 | |||
| 586 | // The filter overwrites the params from GET. |
||
| 587 | if (!empty($filter)) { |
||
| 588 | $params = $glide->getFilters()[$filter] ?? []; |
||
| 589 | } |
||
| 590 | |||
| 591 | // The image was cropped manually by the user, so we force to render this version, |
||
| 592 | // no matter other crop parameters. |
||
| 593 | $crop = $resourceFile->getCrop(); |
||
| 594 | if (!empty($crop)) { |
||
| 595 | $params['crop'] = $crop; |
||
| 596 | } |
||
| 597 | |||
| 598 | $filePath = $resourceNodeRepo->getFilename($resourceFile); |
||
| 599 | |||
| 600 | $response = $server->getImageResponse($filePath, $params); |
||
| 601 | |||
| 602 | $disposition = $response->headers->makeDisposition( |
||
| 603 | ResponseHeaderBag::DISPOSITION_INLINE, |
||
| 604 | $fileName |
||
| 605 | ); |
||
| 606 | $response->headers->set('Content-Disposition', $disposition); |
||
| 607 | |||
| 608 | return $response; |
||
| 609 | } |
||
| 610 | |||
| 611 | // Modify the HTML content before displaying it. |
||
| 612 | if (str_contains($mimeType, 'html')) { |
||
| 613 | $content = $resourceNodeRepo->getResourceNodeFileContent($resourceNode, $resourceFile); |
||
| 614 | |||
| 615 | if (null !== $allUserInfo) { |
||
| 616 | $tagsToReplace = $allUserInfo[0]; |
||
| 617 | $replacementValues = $allUserInfo[1]; |
||
| 618 | $content = str_replace($tagsToReplace, $replacementValues, $content); |
||
| 619 | } |
||
| 620 | |||
| 621 | $content = $this->injectGlossaryJs($request, $content, $resourceNode); |
||
| 622 | |||
| 623 | $response = new Response(); |
||
| 624 | $disposition = $response->headers->makeDisposition( |
||
| 625 | ResponseHeaderBag::DISPOSITION_INLINE, |
||
| 626 | $fileName |
||
| 627 | ); |
||
| 628 | $response->headers->set('Content-Disposition', $disposition); |
||
| 629 | $response->headers->set('Content-Type', 'text/html; charset=UTF-8'); |
||
| 630 | |||
| 631 | // Existing translate_html logic |
||
| 632 | if ('true' === $this->getSettingsManager()->getSetting('editor.translate_html')) { |
||
| 633 | $user = $this->userHelper->getCurrent(); |
||
| 634 | if (null !== $user) { |
||
| 635 | // Overwrite user_json, otherwise it will be loaded by the TwigListener.php |
||
| 636 | $userJson = json_encode(['locale' => $user->getLocale()]); |
||
| 637 | $js = $this->renderView( |
||
| 638 | '@ChamiloCore/Layout/document.html.twig', |
||
| 639 | ['breadcrumb' => '', 'user_json' => $userJson] |
||
| 640 | ); |
||
| 641 | // Insert inside the head tag. |
||
| 642 | $content = str_replace('</head>', $js.'</head>', $content); |
||
| 643 | } |
||
| 644 | } |
||
| 645 | $response->setContent($content); |
||
| 646 | |||
| 647 | return $response; |
||
| 648 | } |
||
| 649 | |||
| 650 | break; |
||
| 651 | } |
||
| 652 | |||
| 653 | $response = new StreamedResponse( |
||
| 654 | function () use ($resourceNodeRepo, $resourceFile, $start, $length): void { |
||
| 655 | $stream = $resourceNodeRepo->getResourceNodeFileStream( |
||
| 656 | $resourceFile->getResourceNode(), |
||
| 657 | $resourceFile |
||
| 658 | ); |
||
| 659 | |||
| 660 | $this->echoBuffer($stream, $start, $length); |
||
| 661 | } |
||
| 662 | ); |
||
| 663 | |||
| 664 | $this->setHeadersToStreamedResponse( |
||
| 665 | $response, |
||
| 666 | $forceDownload, |
||
| 667 | $fileName, |
||
| 668 | $mimeType ?: 'application/octet-stream', |
||
| 669 | $length, |
||
| 670 | $start, |
||
| 671 | $end, |
||
| 672 | $fileSize |
||
| 673 | ); |
||
| 674 | |||
| 675 | return $response; |
||
| 676 | } |
||
| 677 | |||
| 678 | private function injectGlossaryJs( |
||
| 714 | } |
||
| 715 | |||
| 716 | |||
| 717 | /** |
||
| 718 | * Normalize generated HTML documents coming from templates/editors. |
||
| 719 | * |
||
| 720 | * This method tries to fix the pattern: |
||
| 721 | * <head>...</head><!DOCTYPE html><html>...<head>...</head><body>...</body></html> |
||
| 722 | * |
||
| 723 | * It will: |
||
| 724 | * - Extract the first <head>...</head> block (if it appears before <!DOCTYPE). |
||
| 725 | * - Keep the proper <!DOCTYPE html><html>... document. |
||
| 726 | * - Inject the inner content of the first head into the main <head> of the document. |
||
| 727 | */ |
||
| 728 | private function normalizeGeneratedHtml(string $content): string |
||
| 790 | } |
||
| 791 | } |
||
| 792 |