Passed
Push — master ( 72f3da...dcd5ef )
by Yannick
09:41
created

ResourceController::link()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 31
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 20
nc 5
nop 3
dl 0
loc 31
rs 8.9777
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/* For licensing terms, see /license.txt */
6
7
namespace Chamilo\CoreBundle\Controller;
8
9
use Chamilo\CoreBundle\Entity\Course;
10
use Chamilo\CoreBundle\Entity\ResourceFile;
11
use Chamilo\CoreBundle\Entity\ResourceLink;
12
use Chamilo\CoreBundle\Entity\ResourceNode;
13
use Chamilo\CoreBundle\Entity\Session;
14
use Chamilo\CoreBundle\Entity\User;
15
use Chamilo\CoreBundle\Repository\ResourceFileRepository;
16
use Chamilo\CoreBundle\Repository\ResourceNodeRepository;
17
use Chamilo\CoreBundle\Repository\ResourceWithLinkInterface;
18
use Chamilo\CoreBundle\Repository\TrackEDownloadsRepository;
19
use Chamilo\CoreBundle\Security\Authorization\Voter\ResourceNodeVoter;
20
use Chamilo\CoreBundle\ServiceHelper\AccessUrlHelper;
21
use Chamilo\CoreBundle\ServiceHelper\UserHelper;
22
use Chamilo\CoreBundle\Settings\SettingsManager;
23
use Chamilo\CoreBundle\Tool\ToolChain;
24
use Chamilo\CoreBundle\Traits\ControllerTrait;
25
use Chamilo\CoreBundle\Traits\CourseControllerTrait;
26
use Chamilo\CoreBundle\Traits\GradebookControllerTrait;
27
use Chamilo\CoreBundle\Traits\ResourceControllerTrait;
28
use Chamilo\CourseBundle\Controller\CourseControllerInterface;
29
use Chamilo\CourseBundle\Entity\CTool;
30
use Chamilo\CourseBundle\Repository\CLinkRepository;
31
use Chamilo\CourseBundle\Repository\CShortcutRepository;
32
use Chamilo\CourseBundle\Repository\CToolRepository;
33
use Doctrine\Common\Collections\ArrayCollection;
34
use Doctrine\Common\Collections\Criteria;
35
use Doctrine\ORM\EntityManagerInterface;
36
use Symfony\Bundle\SecurityBundle\Security;
37
use Symfony\Component\Filesystem\Exception\FileNotFoundException;
38
use Symfony\Component\HttpFoundation\JsonResponse;
39
use Symfony\Component\HttpFoundation\RedirectResponse;
40
use Symfony\Component\HttpFoundation\Request;
41
use Symfony\Component\HttpFoundation\Response;
42
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
43
use Symfony\Component\HttpFoundation\StreamedResponse;
44
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
45
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
46
use Symfony\Component\Routing\Attribute\Route;
47
use Symfony\Component\Routing\RouterInterface;
48
use Symfony\Component\Serializer\SerializerInterface;
49
use ZipStream\Option\Archive;
50
use ZipStream\ZipStream;
51
52
/**
53
 * @author Julio Montoya <[email protected]>.
54
 */
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();
0 ignored issues
show
Comprehensibility Best Practice introduced by
$labels was never initialized. Although not strictly required by PHP, it is generally a good practice to add $labels = array(); before regardless.
Loading history...
97
        $data[] = $size;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.
Loading history...
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');
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'])]
144
    public function view(
145
        Request $request,
146
        TrackEDownloadsRepository $trackEDownloadsRepository,
147
        SettingsManager $settingsManager,
148
        AccessUrlHelper $accessUrlHelper
149
    ): Response {
150
151
        $id = $request->get('id');
152
        $resourceFileId = $request->get('resourceFileId');
153
        $filter = (string) $request->get('filter');
154
        $resourceNode = $this->getResourceNodeRepository()->findOneBy(['uuid' => $id]);
155
156
        if (null === $resourceNode) {
157
            throw new FileNotFoundException($this->trans('Resource not found'));
158
        }
159
160
        $resourceFile = null;
161
        if ($resourceFileId) {
162
            $resourceFile = $this->resourceFileRepository->find($resourceFileId);
163
        }
164
165
        if (!$resourceFile) {
166
            $accessUrlSpecificFiles = $settingsManager->getSetting('course.access_url_specific_files') && $accessUrlHelper->isMultiple();
167
            $currentUrl = $accessUrlHelper->getCurrent()?->getUrl();
168
169
            $resourceFiles = $resourceNode->getResourceFiles();
170
171
            if ($accessUrlSpecificFiles) {
172
                foreach ($resourceFiles as $file) {
173
                    if ($file->getAccessUrl() && $file->getAccessUrl()->getUrl() === $currentUrl) {
174
                        $resourceFile = $file;
175
                        break;
176
                    }
177
                }
178
            }
179
180
            if (!$resourceFile) {
181
                $resourceFile = $resourceFiles->filter(fn($file) => $file->getAccessUrl() === null)->first();
182
            }
183
        }
184
185
        if (!$resourceFile) {
186
            throw new FileNotFoundException($this->trans('Resource file not found for the given resource node'));
187
        }
188
189
        $user = $this->userHelper->getCurrent();
190
        $firstResourceLink = $resourceNode->getResourceLinks()->first();
191
        if ($firstResourceLink && $user) {
192
            $url = $resourceFile->getOriginalName();
193
            $trackEDownloadsRepository->saveDownload($user, $firstResourceLink, $url);
194
        }
195
196
        $cid = (int) $request->query->get('cid');
197
        $sid = (int) $request->query->get('sid');
198
        $allUserInfo = null;
199
        if ($cid && $user) {
200
            $allUserInfo = $this->getAllInfoToCertificate(
201
                $user->getId(),
202
                $cid,
203
                $sid,
204
                false
205
            );
206
        }
207
208
        return $this->processFile($request, $resourceNode, 'show', $filter, $allUserInfo, $resourceFile);
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'])]
217
    public function link(Request $request, RouterInterface $router, CLinkRepository $cLinkRepository): RedirectResponse
218
    {
219
        $tool = $request->get('tool');
220
        $type = $request->get('type');
221
        $id = $request->get('id');
222
        $resourceNode = $this->getResourceNodeRepository()->find($id);
223
224
        if (null === $resourceNode) {
225
            throw new FileNotFoundException('Resource not found');
226
        }
227
228
        if ('course_tool' === $tool && 'links' === $type) {
229
            $cLink = $cLinkRepository->findOneBy(['resourceNode' => $resourceNode]);
230
            if ($cLink) {
231
                $url = $cLink->getUrl();
232
233
                return $this->redirect($url);
234
            }
235
236
            throw new FileNotFoundException('CLink not found for the given resource node');
237
        } else {
238
            $repo = $this->getRepositoryFromRequest($request);
239
            if ($repo instanceof ResourceWithLinkInterface) {
240
                $resource = $repo->getResourceFromResourceNode($resourceNode->getId());
241
                $url = $repo->getLink($resource, $router, $this->getCourseUrlQueryToArray());
242
243
                return $this->redirect($url);
244
            }
245
246
            $this->abort('No redirect');
0 ignored issues
show
Bug Best Practice introduced by
In this branch, the function will implicitly return null which is incompatible with the type-hinted return Symfony\Component\HttpFoundation\RedirectResponse. Consider adding a return statement or allowing null as return value.

For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example:

interface ReturnsInt {
    public function returnsIntHinted(): int;
}

class MyClass implements ReturnsInt {
    public function returnsIntHinted(): int
    {
        if (foo()) {
            return 123;
        }
        // here: null is implicitly returned
    }
}
Loading history...
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'])]
254
    public function download(
255
        Request $request,
256
        TrackEDownloadsRepository $trackEDownloadsRepository,
257
        SettingsManager $settingsManager,
258
        AccessUrlHelper $accessUrlHelper
259
    ): Response {
260
        $id = $request->get('id');
261
        $resourceNode = $this->getResourceNodeRepository()->findOneBy(['uuid' => $id]);
262
263
        if (null === $resourceNode) {
264
            throw new FileNotFoundException($this->trans('Resource not found'));
265
        }
266
267
        $repo = $this->getRepositoryFromRequest($request);
268
269
        $this->denyAccessUnlessGranted(
270
            ResourceNodeVoter::VIEW,
271
            $resourceNode,
272
            $this->trans('Unauthorised access to resource')
273
        );
274
275
        $accessUrlSpecificFiles = $settingsManager->getSetting('course.access_url_specific_files') && $accessUrlHelper->isMultiple();
276
        $currentUrl = $accessUrlHelper->getCurrent()?->getUrl();
277
278
        $resourceFiles = $resourceNode->getResourceFiles();
279
        $resourceFile = null;
280
281
        if ($accessUrlSpecificFiles) {
282
            foreach ($resourceFiles as $file) {
283
                if ($file->getAccessUrl() && $file->getAccessUrl()->getUrl() === $currentUrl) {
284
                    $resourceFile = $file;
285
                    break;
286
                }
287
            }
288
        }
289
290
        $resourceFile ??= $resourceFiles->filter(fn($file) => $file->getAccessUrl() === null)->first();
291
292
        // If resource node has a file just download it. Don't download the children.
293
        if ($resourceFile) {
294
            $user = $this->userHelper->getCurrent();
295
            $firstResourceLink = $resourceNode->getResourceLinks()->first();
296
297
            if ($firstResourceLink && $user) {
298
                $url = $resourceFile->getOriginalName();
299
                $trackEDownloadsRepository->saveDownload($user, $firstResourceLink, $url);
300
            }
301
302
            // Redirect to download single file.
303
            return $this->processFile($request, $resourceNode, 'download', '', null, $resourceFile);
304
        }
305
306
        $zipName = $resourceNode->getSlug().'.zip';
307
        $resourceNodeRepo = $repo->getResourceNodeRepository();
308
        $type = $repo->getResourceType();
309
310
        $criteria = Criteria::create()
311
            ->where(Criteria::expr()->neq('resourceFiles', null)) // must have a file
312
            ->andWhere(Criteria::expr()->eq('resourceType', $type)) // only download same type
313
        ;
314
315
        $qb = $resourceNodeRepo->getChildrenQueryBuilder($resourceNode);
316
        $qbAlias = $qb->getRootAliases()[0];
317
318
        $qb
319
            ->leftJoin(\sprintf('%s.resourceFiles', $qbAlias), 'resourceFiles') // must have a file
320
            ->addCriteria($criteria)
321
        ;
322
323
        /** @var ArrayCollection|ResourceNode[] $children */
324
        $children = $qb->getQuery()->getResult();
325
        $count = \count($children);
326
        if (0 === $count) {
327
            $params = $this->getResourceParams($request);
328
            $params['id'] = $id;
329
330
            $this->addFlash('warning', $this->trans('No files'));
331
332
            return $this->redirectToRoute('chamilo_core_resource_list', $params);
333
        }
334
335
        $response = new StreamedResponse(
336
            function () use ($zipName, $children, $repo): void {
337
                // Define suitable options for ZipStream Archive.
338
                $options = new Archive();
339
                $options->setContentType('application/octet-stream');
340
                // initialise zipstream with output zip filename and options.
341
                $zip = new ZipStream($zipName, $options);
342
343
                /** @var ResourceNode $node */
344
                foreach ($children as $node) {
345
                    $resourceFiles = $node->getResourceFiles();
346
                    $resourceFile = $resourceFiles->filter(fn($file) => $file->getAccessUrl() === null)->first();
347
348
                    if ($resourceFile) {
349
                        $stream = $repo->getResourceNodeFileStream($resourceFile);
350
                        $fileName = $resourceFile->getOriginalName();
351
                        $zip->addFileFromStream($fileName, $stream);
352
                    }
353
                }
354
                $zip->finish();
355
            }
356
        );
357
358
        // Convert the file name to ASCII using iconv
359
        $zipName = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $zipName);
360
361
        $disposition = $response->headers->makeDisposition(
362
            ResponseHeaderBag::DISPOSITION_ATTACHMENT,
363
            $zipName // Transliterator::transliterate($zipName)
364
        );
365
        $response->headers->set('Content-Disposition', $disposition);
366
        $response->headers->set('Content-Type', 'application/octet-stream');
367
368
        return $response;
369
    }
370
371
    #[Route('/{tool}/{type}/{id}/change_visibility', name: 'chamilo_core_resource_change_visibility', methods: ['POST'])]
372
    public function changeVisibility(
373
        Request $request,
374
        EntityManagerInterface $entityManager,
375
        SerializerInterface $serializer,
376
        Security $security,
377
    ): Response {
378
        $user = $security->getUser();
379
        $isAdmin = ($user->hasRole('ROLE_SUPER_ADMIN') || $user->hasRole('ROLE_ADMIN'));
380
        $isCourseTeacher = ($user->hasRole('ROLE_CURRENT_COURSE_TEACHER') || $user->hasRole('ROLE_CURRENT_COURSE_SESSION_TEACHER'));
381
382
        if (!($isCourseTeacher || $isAdmin)) {
383
            throw new AccessDeniedHttpException();
384
        }
385
386
        $session = null;
387
        if ($this->getSession()) {
388
            $sessionId = $this->getSession()->getId();
389
            $session = $entityManager->getRepository(Session::class)->find($sessionId);
390
        }
391
        $courseId = $this->getCourse()->getId();
392
        $course = $entityManager->getRepository(Course::class)->find($courseId);
393
        $id = $request->attributes->getInt('id');
394
        $resourceNode = $this->getResourceNodeRepository()->findOneBy(['id' => $id]);
395
396
        if (null === $resourceNode) {
397
            throw new NotFoundHttpException($this->trans('Resource not found'));
398
        }
399
400
        $link = null;
401
        foreach ($resourceNode->getResourceLinks() as $resourceLink) {
402
            if ($resourceLink->getSession() === $session) {
403
                $link = $resourceLink;
404
405
                break;
406
            }
407
        }
408
409
        if (null === $link) {
410
            $link = new ResourceLink();
411
            $link->setResourceNode($resourceNode)
412
                ->setSession($session)
413
                ->setCourse($course)
414
                ->setVisibility(ResourceLink::VISIBILITY_DRAFT)
415
            ;
416
            $entityManager->persist($link);
417
        } else {
418
            if (ResourceLink::VISIBILITY_PUBLISHED === $link->getVisibility()) {
419
                $link->setVisibility(ResourceLink::VISIBILITY_DRAFT);
420
            } else {
421
                $link->setVisibility(ResourceLink::VISIBILITY_PUBLISHED);
422
            }
423
        }
424
425
        $entityManager->flush();
426
427
        $json = $serializer->serialize(
428
            $link,
429
            'json',
430
            [
431
                'groups' => ['ctool:read'],
432
            ]
433
        );
434
435
        return JsonResponse::fromJsonString($json);
436
    }
437
438
    #[Route(
439
        '/{tool}/{type}/change_visibility/{visibility}',
440
        name: 'chamilo_core_resource_change_visibility_all',
441
        methods: ['POST']
442
    )]
443
    public function changeVisibilityAll(
444
        Request $request,
445
        CToolRepository $toolRepository,
446
        CShortcutRepository $shortcutRepository,
447
        ToolChain $toolChain,
448
        EntityManagerInterface $entityManager,
449
        Security $security
450
    ): Response {
451
        $user = $security->getUser();
452
        $isAdmin = ($user->hasRole('ROLE_SUPER_ADMIN') || $user->hasRole('ROLE_ADMIN'));
453
        $isCourseTeacher = ($user->hasRole('ROLE_CURRENT_COURSE_TEACHER') || $user->hasRole('ROLE_CURRENT_COURSE_SESSION_TEACHER'));
454
455
        if (!($isCourseTeacher || $isAdmin)) {
456
            throw new AccessDeniedHttpException();
457
        }
458
459
        $visibility = $request->attributes->get('visibility');
460
461
        $session = null;
462
        if ($this->getSession()) {
463
            $sessionId = $this->getSession()->getId();
464
            $session = $entityManager->getRepository(Session::class)->find($sessionId);
465
        }
466
        $courseId = $this->getCourse()->getId();
467
        $course = $entityManager->getRepository(Course::class)->find($courseId);
468
469
        $result = $toolRepository->getResourcesByCourse($course, $session)
470
            ->addSelect('tool')
471
            ->innerJoin('resource.tool', 'tool')
472
            ->getQuery()
473
            ->getResult()
474
        ;
475
476
        $skipTools = ['course_tool', 'chat', 'notebook', 'wiki'];
477
478
        /** @var CTool $item */
479
        foreach ($result as $item) {
480
            if (\in_array($item->getTitle(), $skipTools, true)) {
481
                continue;
482
            }
483
            $toolModel = $toolChain->getToolFromName($item->getTool()->getTitle());
484
485
            if (!\in_array($toolModel->getCategory(), ['authoring', 'interaction'], true)) {
0 ignored issues
show
Bug introduced by
The method getCategory() does not exist on Chamilo\CoreBundle\Tool\AbstractTool. It seems like you code against a sub-type of said class. However, the method does not exist in Chamilo\CoreBundle\Tool\AbstractCourseTool. Are you sure you never get one of those? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

485
            if (!\in_array($toolModel->/** @scrutinizer ignore-call */ getCategory(), ['authoring', 'interaction'], true)) {
Loading history...
486
                continue;
487
            }
488
489
            $resourceNode = $item->getResourceNode();
490
491
            /** @var ResourceLink $link */
492
            $link = null;
493
            foreach ($resourceNode->getResourceLinks() as $resourceLink) {
494
                if ($resourceLink->getSession() === $session) {
495
                    $link = $resourceLink;
496
497
                    break;
498
                }
499
            }
500
501
            if (null === $link) {
502
                $link = new ResourceLink();
503
                $link->setResourceNode($resourceNode)
504
                    ->setSession($session)
505
                    ->setCourse($course)
506
                    ->setVisibility(ResourceLink::VISIBILITY_DRAFT)
507
                ;
508
                $entityManager->persist($link);
509
            }
510
511
            if ('show' === $visibility) {
512
                $link->setVisibility(ResourceLink::VISIBILITY_PUBLISHED);
513
            } elseif ('hide' === $visibility) {
514
                $link->setVisibility(ResourceLink::VISIBILITY_DRAFT);
515
            }
516
        }
517
518
        $entityManager->flush();
519
520
        return new Response(null, Response::HTTP_NO_CONTENT);
521
    }
522
523
    #[Route('/resource_files/{resourceNodeId}/variants', name: 'chamilo_core_resource_files_variants', methods: ['GET'])]
524
    public function getVariants(string $resourceNodeId, EntityManagerInterface $em): JsonResponse
525
    {
526
        $variants = $em->getRepository(ResourceFile::class)->createQueryBuilder('rf')
527
            ->join('rf.resourceNode', 'rn')
528
            ->leftJoin('rn.creator', 'creator')
529
            ->where('rf.resourceNode = :resourceNodeId')
530
            ->andWhere('rf.accessUrl IS NOT NULL')
531
            ->setParameter('resourceNodeId', $resourceNodeId)
532
            ->getQuery()
533
            ->getResult();
534
535
        $data = [];
536
537
        /* @var ResourceFile $variant */
538
        foreach ($variants as $variant) {
539
            $data[] = [
540
                'id' => $variant->getId(),
541
                'title' => $variant->getOriginalName(),
542
                'mimeType' => $variant->getMimeType(),
543
                'size' => $variant->getSize(),
544
                'updatedAt' => $variant->getUpdatedAt()->format('Y-m-d H:i:s'),
545
                'url' => $variant->getAccessUrl() ? $variant->getAccessUrl()->getUrl() : null,
546
                'path' => $this->resourceNodeRepository->getResourceFileUrl($variant->getResourceNode(), [], null, $variant),
547
                'creator' => $variant->getResourceNode()->getCreator() ? $variant->getResourceNode()->getCreator()->getFullName() : 'Unknown',
548
            ];
549
        }
550
551
        return $this->json($data);
552
    }
553
554
    #[Route('/resource_files/{id}/delete_variant', methods: ['DELETE'], name: 'chamilo_core_resource_files_delete_variant')]
555
    public function deleteVariant(int $id, EntityManagerInterface $em): JsonResponse
556
    {
557
        $variant = $em->getRepository(ResourceFile::class)->find($id);
558
        if (!$variant) {
559
            return $this->json(['error' => 'Variant not found'], Response::HTTP_NOT_FOUND);
560
        }
561
562
        $em->remove($variant);
563
        $em->flush();
564
565
        return $this->json(['success' => true]);
566
    }
567
568
    private function processFile(Request $request, ResourceNode $resourceNode, string $mode = 'show', string $filter = '', ?array $allUserInfo = null, ?ResourceFile $resourceFile = null): mixed
569
    {
570
        $this->denyAccessUnlessGranted(
571
            ResourceNodeVoter::VIEW,
572
            $resourceNode,
573
            $this->trans('Unauthorised view access to resource')
574
        );
575
576
        $resourceFile ??= $resourceNode->getResourceFiles()->first();
577
578
        if (!$resourceFile) {
579
            throw $this->createNotFoundException($this->trans('File not found for resource'));
580
        }
581
582
        $fileName = $resourceFile->getOriginalName();
583
        $fileSize = $resourceFile->getSize();
584
        $mimeType = $resourceFile->getMimeType();
585
        [$start, $end, $length] = $this->getRange($request, $fileSize);
586
        $resourceNodeRepo = $this->getResourceNodeRepository();
587
588
        // Convert the file name to ASCII using iconv
589
        $fileName = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $fileName);
590
591
        switch ($mode) {
592
            case 'download':
593
                $forceDownload = true;
594
595
                break;
596
597
            case 'show':
598
            default:
599
                $forceDownload = false;
600
                // If it's an image then send it to Glide.
601
                if (str_contains($mimeType, 'image')) {
602
                    $glide = $this->getGlide();
603
                    $server = $glide->getServer();
604
                    $params = $request->query->all();
605
606
                    // The filter overwrites the params from GET.
607
                    if (!empty($filter)) {
608
                        $params = $glide->getFilters()[$filter] ?? [];
609
                    }
610
611
                    // The image was cropped manually by the user, so we force to render this version,
612
                    // no matter other crop parameters.
613
                    $crop = $resourceFile->getCrop();
614
                    if (!empty($crop)) {
615
                        $params['crop'] = $crop;
616
                    }
617
618
                    $filePath = $resourceNodeRepo->getFilename($resourceFile);
619
620
                    $response = $server->getImageResponse($filePath, $params);
621
622
                    $disposition = $response->headers->makeDisposition(
623
                        ResponseHeaderBag::DISPOSITION_INLINE,
624
                        $fileName
625
                    );
626
                    $response->headers->set('Content-Disposition', $disposition);
627
628
                    return $response;
629
                }
630
631
                // Modify the HTML content before displaying it.
632
                if (str_contains($mimeType, 'html')) {
633
                    $content = $resourceNodeRepo->getResourceNodeFileContent($resourceNode, $resourceFile);
634
635
                    if (null !== $allUserInfo) {
636
                        $tagsToReplace = $allUserInfo[0];
637
                        $replacementValues = $allUserInfo[1];
638
                        $content = str_replace($tagsToReplace, $replacementValues, $content);
639
                    }
640
641
                    $response = new Response();
642
                    $disposition = $response->headers->makeDisposition(
643
                        ResponseHeaderBag::DISPOSITION_INLINE,
644
                        $fileName
645
                    );
646
                    $response->headers->set('Content-Disposition', $disposition);
647
                    $response->headers->set('Content-Type', 'text/html');
648
649
                    // @todo move into a function/class
650
                    if ('true' === $this->getSettingsManager()->getSetting('editor.translate_html')) {
651
                        $user = $this->userHelper->getCurrent();
652
                        if (null !== $user) {
653
                            // Overwrite user_json, otherwise it will be loaded by the TwigListener.php
654
                            $userJson = json_encode(['locale' => $user->getLocale()]);
655
                            $js = $this->renderView(
656
                                '@ChamiloCore/Layout/document.html.twig',
657
                                ['breadcrumb' => '', 'user_json' => $userJson]
658
                            );
659
                            // Insert inside the head tag.
660
                            $content = str_replace('</head>', $js.'</head>', $content);
661
                        }
662
                    }
663
                    if ('true' === $this->getSettingsManager()->getSetting('course.enable_bootstrap_in_documents_html')) {
664
                        // It adds the bootstrap and awesome css
665
                        $links = '<link href="'.api_get_path(WEB_PATH).'libs/bootstrap/bootstrap.min.css" rel="stylesheet">';
666
                        $links .= '<link href="'.api_get_path(WEB_PATH).'libs/bootstrap/font-awesome.min.css" rel="stylesheet">';
667
                        // Insert inside the head tag.
668
                        $content = str_replace('</head>', $links.'</head>', $content);
669
                    }
670
                    $response->setContent($content);
671
672
                    return $response;
673
                }
674
675
                break;
676
        }
677
678
        $response = new StreamedResponse(
679
            function () use ($resourceNodeRepo, $resourceFile, $start, $length): void {
680
                $this->streamFileContent($resourceNodeRepo, $resourceFile, $start, $length);
681
            }
682
        );
683
684
        $disposition = $response->headers->makeDisposition(
685
            $forceDownload ? ResponseHeaderBag::DISPOSITION_ATTACHMENT : ResponseHeaderBag::DISPOSITION_INLINE,
686
            $fileName
687
        );
688
        $response->headers->set('Content-Disposition', $disposition);
689
        $response->headers->set('Content-Type', $mimeType ?: 'application/octet-stream');
690
        $response->headers->set('Content-Length', (string) $length);
691
        $response->headers->set('Accept-Ranges', 'bytes');
692
        $response->headers->set('Content-Range', "bytes $start-$end/$fileSize");
693
        $response->setStatusCode(
694
            $start > 0 || $end < $fileSize - 1 ? Response::HTTP_PARTIAL_CONTENT : Response::HTTP_OK
695
        );
696
697
        return $response;
698
    }
699
700
    private function getRange(Request $request, int $fileSize): array
701
    {
702
        $range = $request->headers->get('Range');
703
704
        if ($range) {
705
            [, $range] = explode('=', $range, 2);
706
            [$start, $end] = explode('-', $range);
707
708
            $start = (int) $start;
709
            $end = ('' === $end) ? $fileSize - 1 : (int) $end;
710
711
            $length = $end - $start + 1;
712
        } else {
713
            $start = 0;
714
            $end = $fileSize - 1;
715
            $length = $fileSize;
716
        }
717
718
        return [$start, $end, $length];
719
    }
720
721
    private function streamFileContent(ResourceNodeRepository $resourceNodeRepo, ResourceFile $resourceFile, int $start, int $length): void
722
    {
723
        $stream = $resourceNodeRepo->getResourceNodeFileStream($resourceFile->getResourceNode(), $resourceFile);
724
725
        fseek($stream, $start);
726
727
        $bytesSent = 0;
728
729
        while ($bytesSent < $length && !feof($stream)) {
730
            $buffer = fread($stream, min(1024 * 8, $length - $bytesSent));
731
732
            echo $buffer;
733
734
            $bytesSent += \strlen($buffer);
735
        }
736
737
        fclose($stream);
738
    }
739
}
740