Passed
Push — master ( 4a0c08...05aec1 )
by Julito
07:18
created

ResourceRepository::addFileFromPath()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 4
eloc 5
nc 2
nop 4
dl 0
loc 10
rs 10
c 1
b 1
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/* For licensing terms, see /license.txt */
6
7
namespace Chamilo\CoreBundle\Repository;
8
9
use Chamilo\CoreBundle\Component\Resource\Settings;
10
use Chamilo\CoreBundle\Component\Resource\Template;
11
use Chamilo\CoreBundle\Entity\AbstractResource;
12
use Chamilo\CoreBundle\Entity\Course;
13
use Chamilo\CoreBundle\Entity\ResourceFile;
14
use Chamilo\CoreBundle\Entity\ResourceInterface;
15
use Chamilo\CoreBundle\Entity\ResourceLink;
16
use Chamilo\CoreBundle\Entity\ResourceNode;
17
use Chamilo\CoreBundle\Entity\ResourceRight;
18
use Chamilo\CoreBundle\Entity\ResourceType;
19
use Chamilo\CoreBundle\Entity\Session;
20
use Chamilo\CoreBundle\Entity\User;
21
use Chamilo\CoreBundle\Security\Authorization\Voter\ResourceNodeVoter;
22
use Chamilo\CourseBundle\Entity\CGroup;
23
use Chamilo\CourseBundle\Traits\NonResourceRepository;
24
use DateTime;
25
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
26
use Doctrine\Common\Collections\ArrayCollection;
27
use Doctrine\DBAL\Types\Types;
28
use Doctrine\ORM\EntityRepository;
29
use Doctrine\ORM\QueryBuilder;
30
use Exception;
31
use LogicException;
32
use Symfony\Component\Filesystem\Exception\FileNotFoundException;
33
use Symfony\Component\Form\FormFactory;
34
use Symfony\Component\Form\FormInterface;
35
use Symfony\Component\HttpFoundation\File\UploadedFile;
36
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
37
use Throwable;
38
39
/**
40
 * Extends EntityRepository is needed to process settings.
41
 */
42
abstract class ResourceRepository extends ServiceEntityRepository
43
{
44
    use NonResourceRepository;
45
46
    protected Settings $settings;
47
    protected Template $templates;
48
    protected ?ResourceType $resourceType = null;
49
50
    public function setSettings(Settings $settings): self
51
    {
52
        $this->settings = $settings;
53
54
        return $this;
55
    }
56
57
    public function setTemplates(Template $templates): self
58
    {
59
        $this->templates = $templates;
60
61
        return $this;
62
    }
63
64
    public function getResourceSettings(): Settings
65
    {
66
        return $this->settings;
67
    }
68
69
    public function getTemplates(): Template
70
    {
71
        return $this->templates;
72
    }
73
74
    public function getClassName(): string
75
    {
76
        $class = static::class;
77
        //Chamilo\CoreBundle\Repository\Node\IllustrationRepository
78
        $class = str_replace('\\Repository\\', '\\Entity\\', $class);
79
        $class = str_replace('Repository', '', $class);
80
        if (!class_exists($class)) {
81
            throw new Exception(sprintf('Repo: %s not found ', $class));
82
        }
83
84
        return $class;
85
    }
86
87
    public function getCount(QueryBuilder $qb): int
88
    {
89
        $qb->select('count(resource)');
90
        $qb->setMaxResults(1);
91
92
        return (int) $qb->getQuery()->getSingleScalarResult();
93
    }
94
95
    /**
96
     * @return FormInterface
97
     */
98
    public function getForm(FormFactory $formFactory, ResourceInterface $resource = null, array $options = [])
99
    {
100
        $formType = $this->getResourceFormType();
101
102
        if (null === $resource) {
103
            $className = $this->repository->getClassName();
104
            $resource = new $className();
105
        }
106
107
        return $formFactory->create($formType, $resource, $options);
108
    }
109
110
    public function getResourceByResourceNode(ResourceNode $resourceNode): ?ResourceInterface
111
    {
112
        return $this->findOneBy([
113
            'resourceNode' => $resourceNode,
114
        ]);
115
    }
116
117
    /*public function findOneBy(array $criteria, array $orderBy = null)
118
    {
119
        return $this->findOneBy($criteria, $orderBy);
120
    }*/
121
122
    /*public function updateResource(AbstractResource $resource)
123
    {
124
        $em = $this->getEntityManager();
125
126
        $resourceNode = $resource->getResourceNode();
127
        $resourceNode->setTitle($resource->getResourceName());
128
129
        $links = $resource->getResourceLinkEntityList();
130
        if ($links) {
131
            foreach ($links as $link) {
132
                $link->setResourceNode($resourceNode);
133
134
                $rights = [];
135
                switch ($link->getVisibility()) {
136
                    case ResourceLink::VISIBILITY_PENDING:
137
                    case ResourceLink::VISIBILITY_DRAFT:
138
                        $editorMask = ResourceNodeVoter::getEditorMask();
139
                        $resourceRight = new ResourceRight();
140
                        $resourceRight
141
                            ->setMask($editorMask)
142
                            ->setRole(ResourceNodeVoter::ROLE_CURRENT_COURSE_TEACHER)
143
                        ;
144
                        $rights[] = $resourceRight;
145
146
                        break;
147
                }
148
149
                if (!empty($rights)) {
150
                    foreach ($rights as $right) {
151
                        $link->addResourceRight($right);
152
                    }
153
                }
154
                $em->persist($link);
155
            }
156
        }
157
158
        $em->persist($resourceNode);
159
        $em->persist($resource);
160
        $em->flush();
161
    }*/
162
163
    public function create(AbstractResource $resource): void
164
    {
165
        $this->getEntityManager()->persist($resource);
166
        $this->getEntityManager()->flush();
167
    }
168
169
    public function update(AbstractResource $resource, bool $andFlush = true): void
170
    {
171
        if (!$resource->hasResourceNode()) {
172
            throw new Exception('Resource needs a resource node');
173
        }
174
175
        $resource->getResourceNode()->setUpdatedAt(new DateTime());
176
        $resource->getResourceNode()->setTitle($resource->getResourceName());
177
        $this->getEntityManager()->persist($resource);
178
179
        if ($andFlush) {
180
            $this->getEntityManager()->flush();
181
        }
182
    }
183
184
    public function updateNodeForResource(ResourceInterface $resource): ResourceNode
185
    {
186
        $em = $this->getEntityManager();
187
188
        $resourceNode = $resource->getResourceNode();
189
        $resourceName = $resource->getResourceName();
190
191
        if ($resourceNode->hasResourceFile()) {
192
            $resourceFile = $resourceNode->getResourceFile();
193
            if (null !== $resourceFile) {
194
                $originalName = $resourceFile->getOriginalName();
195
                $originalExtension = pathinfo($originalName, PATHINFO_EXTENSION);
196
197
                //$originalBasename = \basename($resourceName, $originalExtension);
198
                /*$slug = sprintf(
199
                    '%s.%s',
200
                    $this->slugify->slugify($originalBasename),
201
                    $this->slugify->slugify($originalExtension)
202
                );*/
203
204
                $newOriginalName = sprintf('%s.%s', $resourceName, $originalExtension);
205
                $resourceFile->setOriginalName($newOriginalName);
206
207
                $em->persist($resourceFile);
208
            }
209
        }
210
        //$slug = $this->slugify->slugify($resourceName);
211
212
        $resourceNode->setTitle($resourceName);
213
        //$resourceNode->setSlug($slug);
214
215
        $em->persist($resourceNode);
216
        $em->persist($resource);
217
218
        $em->flush();
219
220
        return $resourceNode;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $resourceNode could return the type null which is incompatible with the type-hinted return Chamilo\CoreBundle\Entity\ResourceNode. Consider adding an additional type-check to rule them out.
Loading history...
221
    }
222
223
    public function findCourseResourceByTitle(
224
        string $title,
225
        ResourceNode $parentNode,
226
        Course $course,
227
        Session $session = null,
228
        CGroup $group = null
229
    ): ?ResourceInterface {
230
        $qb = $this->getResourcesByCourse($course, $session, $group, $parentNode);
231
        $this->addTitleQueryBuilder($title, $qb);
232
        $qb->setMaxResults(1);
233
234
        return $qb->getQuery()->getOneOrNullResult();
235
    }
236
237
    public function findCourseResourcesByTitle(
238
        string $title,
239
        ResourceNode $parentNode,
240
        Course $course,
241
        Session $session = null,
242
        CGroup $group = null
243
    ) {
244
        $qb = $this->getResourcesByCourse($course, $session, $group, $parentNode);
245
        $this->addTitleQueryBuilder($title, $qb);
246
247
        return $qb->getQuery()->getResult();
248
    }
249
250
    /**
251
     * @todo clean path
252
     */
253
    public function addFileFromPath(ResourceInterface $resource, string $fileName, string $path, bool $flush = true)
254
    {
255
        if (!empty($path) && file_exists($path) && !is_dir($path)) {
256
            $mimeType = mime_content_type($path);
257
            $file = new UploadedFile($path, $fileName, $mimeType, null, true);
258
259
            return $this->addFile($resource, $file, '', $flush);
260
        }
261
262
        return null;
263
    }
264
265
    public function addFileFromString(ResourceInterface $resource, string $fileName, string $mimeType, string $content, bool $flush = true): ?ResourceFile
266
    {
267
        $handle = tmpfile();
268
        fwrite($handle, $content);
269
        $meta = stream_get_meta_data($handle);
270
        $file = new UploadedFile($meta['uri'], $fileName, $mimeType, null, true);
271
272
        return $this->addFile($resource, $file, '', $flush);
273
    }
274
275
    public function addFileFromFileRequest(ResourceInterface $resource, string $fileKey, bool $flush = true): ?ResourceFile
276
    {
277
        $request = $this->getRequest();
278
        if ($request->files->has($fileKey)) {
279
            $file = $request->files->get($fileKey);
280
            if (null !== $file) {
281
                $resourceFile = $this->addFile($resource, $file);
282
                if ($flush) {
283
                    $this->getEntityManager()->flush();
284
                }
285
286
                return $resourceFile;
287
            }
288
        }
289
290
        return null;
291
    }
292
293
    public function addFile(ResourceInterface $resource, UploadedFile $file, string $description = '', bool $flush = false): ?ResourceFile
294
    {
295
        $resourceNode = $resource->getResourceNode();
296
297
        if (null === $resourceNode) {
298
            throw new LogicException('Resource node is null');
299
        }
300
301
        $resourceFile = $resourceNode->getResourceFile();
302
        if (null === $resourceFile) {
303
            $resourceFile = new ResourceFile();
304
        }
305
306
        $em = $this->getEntityManager();
307
        $resourceFile
308
            ->setFile($file)
309
            ->setDescription($description)
310
            ->setName($resource->getResourceName())
311
            ->setResourceNode($resourceNode)
312
        ;
313
        $em->persist($resourceFile);
314
        $resourceNode->setResourceFile($resourceFile);
315
        $em->persist($resourceNode);
316
317
        if ($flush) {
318
            $em->flush();
319
        }
320
321
        return $resourceFile;
322
    }
323
324
    public function addResourceNode(ResourceInterface $resource, User $creator, ResourceInterface $parent = null): ResourceNode
325
    {
326
        if (null !== $parent) {
327
            $parent = $parent->getResourceNode();
328
        }
329
330
        return $this->createNodeForResource($resource, $creator, $parent);
331
    }
332
333
    public function getResourceType(): ?ResourceType
334
    {
335
        $name = $this->getResourceTypeName();
336
        $repo = $this->getEntityManager()->getRepository(ResourceType::class);
337
        $this->resourceType = $repo->findOneBy([
338
            'name' => $name,
339
        ]);
340
341
        return $this->resourceType;
342
    }
343
344
    public function getResourceTypeName(): string
345
    {
346
        return $this->toolChain->getResourceTypeNameFromRepository(static::class);
0 ignored issues
show
Bug introduced by
The method getResourceTypeNameFromRepository() does not exist on null. ( Ignorable by Annotation )

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

346
        return $this->toolChain->/** @scrutinizer ignore-call */ getResourceTypeNameFromRepository(static::class);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
347
    }
348
349
    public function getResourcesByCourse(Course $course, Session $session = null, CGroup $group = null, ResourceNode $parentNode = null): QueryBuilder
350
    {
351
        $checker = $this->getAuthorizationChecker();
352
        $reflectionClass = $this->getClassMetadata()->getReflectionClass();
353
354
        // Check if this resource type requires to load the base course resources when using a session
355
        $loadBaseSessionContent = $reflectionClass->hasProperty('loadCourseResourcesInSession');
356
357
        $resourceTypeName = $this->getResourceTypeName();
358
        $qb = $this->createQueryBuilder('resource')
359
            ->select('resource')
360
            //->from($className, 'resource')
361
            ->innerJoin('resource.resourceNode', 'node')
362
            ->innerJoin('node.resourceLinks', 'links')
363
            ->innerJoin('node.resourceType', 'type')
364
            ->leftJoin('node.resourceFile', 'file')
365
366
            ->where('type.name = :type')
367
            ->setParameter('type', $resourceTypeName, Types::STRING)
368
            ->andWhere('links.course = :course')
369
            ->setParameter('course', $course)
370
            ->addSelect('node')
371
            ->addSelect('links')
372
            //->addSelect('course')
373
            ->addSelect('type')
374
            ->addSelect('file')
375
        ;
376
377
        $isAdmin =
378
            $checker->isGranted('ROLE_ADMIN') ||
379
            $checker->isGranted('ROLE_CURRENT_COURSE_TEACHER');
380
381
        // Do not show deleted resources.
382
        $qb
383
            ->andWhere('links.visibility != :visibilityDeleted')
384
            ->setParameter('visibilityDeleted', ResourceLink::VISIBILITY_DELETED, Types::INTEGER)
385
        ;
386
387
        if (!$isAdmin) {
388
            $qb
389
                ->andWhere('links.visibility = :visibility')
390
                ->setParameter('visibility', ResourceLink::VISIBILITY_PUBLISHED, Types::INTEGER)
391
            ;
392
            // @todo Add start/end visibility restrictions.
393
        }
394
395
        if (null === $session) {
396
            $qb->andWhere(
397
                $qb->expr()->orX(
398
                    $qb->expr()->isNull('links.session'),
399
                    $qb->expr()->eq('links.session', 0)
400
                )
401
            );
402
        } elseif ($loadBaseSessionContent) {
403
            // Load course base content.
404
            $qb->andWhere('links.session = :session OR links.session IS NULL');
405
            $qb->setParameter('session', $session);
406
        } else {
407
            // Load only session resources.
408
            $qb->andWhere('links.session = :session');
409
            $qb->setParameter('session', $session);
410
        }
411
412
        if (null !== $parentNode) {
413
            $qb->andWhere('node.parent = :parentNode');
414
            $qb->setParameter('parentNode', $parentNode);
415
        }
416
417
        if (null === $group) {
418
            $qb->andWhere(
419
                $qb->expr()->orX(
420
                    $qb->expr()->isNull('links.group'),
421
                    $qb->expr()->eq('links.group', 0)
422
                )
423
            );
424
        } else {
425
            $qb->andWhere('links.group = :group');
426
            $qb->setParameter('group', $group);
427
        }
428
429
        return $qb;
430
    }
431
432
    /**
433
     * Get resources only from the base course.
434
     */
435
    public function getResourcesByCourseOnly(Course $course, ResourceNode $parentNode = null): QueryBuilder
436
    {
437
        $checker = $this->getAuthorizationChecker();
438
        $resourceTypeName = $this->getResourceTypeName();
439
440
        $qb = $this->createQueryBuilder('resource')
441
            ->select('resource')
442
            ->innerJoin('resource.resourceNode', 'node')
443
            ->innerJoin('node.resourceLinks', 'links')
444
            ->innerJoin('node.resourceType', 'type')
445
            ->where('type.name = :type')
446
            ->setParameter('type', $resourceTypeName, Types::STRING)
447
            ->andWhere('links.course = :course')
448
            ->setParameter('course', $course)
449
        ;
450
451
        $isAdmin = $checker->isGranted('ROLE_ADMIN') || $checker->isGranted('ROLE_CURRENT_COURSE_TEACHER');
452
453
        // Do not show deleted resources
454
        $qb
455
            ->andWhere('links.visibility != :visibilityDeleted')
456
            ->setParameter('visibilityDeleted', ResourceLink::VISIBILITY_DELETED, Types::INTEGER)
457
        ;
458
459
        if (!$isAdmin) {
460
            $qb
461
                ->andWhere('links.visibility = :visibility')
462
                ->setParameter('visibility', ResourceLink::VISIBILITY_PUBLISHED, Types::INTEGER)
463
            ;
464
            // @todo Add start/end visibility restrictions
465
        }
466
467
        if (null !== $parentNode) {
468
            $qb->andWhere('node.parent = :parentNode');
469
            $qb->setParameter('parentNode', $parentNode);
470
        }
471
472
        return $qb;
473
    }
474
475
    public function getResourceByCreatorFromTitle(
476
        string $title,
477
        User $user,
478
        ResourceNode $parentNode
479
    ): ?ResourceInterface {
480
        $qb = $this->getResourcesByCreator($user, $parentNode);
481
        $this->addTitleQueryBuilder($title, $qb);
482
        $qb->setMaxResults(1);
483
484
        return $qb->getQuery()->getOneOrNullResult();
485
    }
486
487
    public function getResourcesByCreator(User $user, ResourceNode $parentNode = null): QueryBuilder
488
    {
489
        $qb = $this->createQueryBuilder('resource')
490
            ->select('resource')
491
            ->innerJoin('resource.resourceNode', 'node')
492
            //->innerJoin('node.resourceLinks', 'links')
493
            //->where('node.resourceType = :type')
494
            //->setParameter('type',$type)
495
            ;
496
        /*$qb
497
            ->andWhere('links.visibility = :visibility')
498
            ->setParameter('visibility', ResourceLink::VISIBILITY_PUBLISHED)
499
        ;*/
500
501
        if (null !== $parentNode) {
502
            $qb->andWhere('node.parent = :parentNode');
503
            $qb->setParameter('parentNode', $parentNode);
504
        }
505
506
        $this->addCreatorQueryBuilder($user, $qb);
507
508
        return $qb;
509
    }
510
511
    public function getResourcesByCourseLinkedToUser(
512
        User $user,
513
        Course $course,
514
        Session $session = null,
515
        CGroup $group = null,
516
        ResourceNode $parentNode = null
517
    ): QueryBuilder {
518
        $qb = $this->getResourcesByCourse($course, $session, $group, $parentNode);
519
        $qb->andWhere('node.creator = :user OR (links.user = :user OR links.user IS NULL)');
520
        $qb->setParameter('user', $user);
521
522
        return $qb;
523
    }
524
525
    public function getResourcesByLinkedUser(User $user, ResourceNode $parentNode = null): QueryBuilder
526
    {
527
        $checker = $this->getAuthorizationChecker();
528
        $resourceTypeName = $this->getResourceTypeName();
529
530
        $qb = $this->createQueryBuilder('resource')
531
            ->select('resource')
532
            ->innerJoin('resource.resourceNode', 'node')
533
            ->innerJoin('node.resourceLinks', 'links')
534
            ->innerJoin('node.resourceType', 'type')
535
            ->where('type.name = :type')
536
            ->setParameter('type', $resourceTypeName, Types::STRING)
537
            ->andWhere('links.user = :user')
538
            ->setParameter('user', $user)
539
        ;
540
541
        $isAdmin = $checker->isGranted('ROLE_ADMIN') ||
542
            $checker->isGranted('ROLE_CURRENT_COURSE_TEACHER');
543
544
        // Do not show deleted resources
545
        $qb
546
            ->andWhere('links.visibility != :visibilityDeleted')
547
            ->setParameter('visibilityDeleted', ResourceLink::VISIBILITY_DELETED)
548
        ;
549
550
        if (!$isAdmin) {
551
            $qb
552
                ->andWhere('links.visibility = :visibility')
553
                ->setParameter('visibility', ResourceLink::VISIBILITY_PUBLISHED)
554
            ;
555
            // @todo Add start/end visibility restrictrions
556
        }
557
558
        if (null !== $parentNode) {
559
            $qb->andWhere('node.parent = :parentNode');
560
            $qb->setParameter('parentNode', $parentNode);
561
        }
562
563
        return $qb;
564
    }
565
566
    public function getResourceFromResourceNode(int $resourceNodeId): ?ResourceInterface
567
    {
568
        $qb = $this->createQueryBuilder('resource')
569
            ->select('resource')
570
            ->addSelect('node')
571
            ->addSelect('links')
572
            ->innerJoin('resource.resourceNode', 'node')
573
        //    ->innerJoin('node.creator', 'userCreator')
574
            ->innerJoin('node.resourceLinks', 'links')
575
//            ->leftJoin('node.resourceFile', 'file')
576
            ->where('node.id = :id')
577
            ->setParameters([
578
                'id' => $resourceNodeId,
579
            ])
580
            //->addSelect('node')
581
        ;
582
583
        return $qb->getQuery()->getOneOrNullResult();
584
    }
585
586
    public function delete(ResourceInterface $resource): void
587
    {
588
        $children = $resource->getResourceNode()->getChildren();
589
        foreach ($children as $child) {
590
            if ($child->hasResourceFile()) {
591
                $this->getEntityManager()->remove($child->getResourceFile());
592
            }
593
            $resourceNode = $this->getResourceFromResourceNode($child->getId());
594
            if (null !== $resourceNode) {
595
                $this->delete($resourceNode);
596
            }
597
        }
598
        $this->getEntityManager()->remove($resource);
599
        $this->getEntityManager()->flush();
600
    }
601
602
    /**
603
     * Deletes several entities: AbstractResource (Ex: CDocument, CQuiz), ResourceNode,
604
     * ResourceLinks and ResourceFile (including files via Flysystem).
605
     */
606
    public function hardDelete(AbstractResource $resource): void
607
    {
608
        $em = $this->getEntityManager();
609
        $em->remove($resource);
610
        $em->flush();
611
    }
612
613
    public function getResourceFileContent(AbstractResource $resource): string
614
    {
615
        try {
616
            $resourceNode = $resource->getResourceNode();
617
618
            return $this->resourceNodeRepository->getResourceNodeFileContent($resourceNode);
0 ignored issues
show
Bug introduced by
The method getResourceNodeFileContent() does not exist on null. ( Ignorable by Annotation )

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

618
            return $this->resourceNodeRepository->/** @scrutinizer ignore-call */ getResourceNodeFileContent($resourceNode);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
619
        } catch (Throwable $throwable) {
620
            throw new FileNotFoundException($resource->getResourceName());
621
        }
622
    }
623
624
    public function getResourceNodeFileContent(ResourceNode $resourceNode): string
625
    {
626
        return $this->resourceNodeRepository->getResourceNodeFileContent($resourceNode);
627
    }
628
629
    public function getResourceNodeFileStream(ResourceNode $resourceNode)
630
    {
631
        return $this->resourceNodeRepository->getResourceNodeFileStream($resourceNode);
632
    }
633
634
    public function getResourceFileDownloadUrl(AbstractResource $resource, array $extraParams = [], $referenceType = null): string
635
    {
636
        $extraParams['mode'] = 'download';
637
638
        return $this->getResourceFileUrl($resource, $extraParams, $referenceType);
639
    }
640
641
    public function getResourceFileUrl(AbstractResource $resource, array $extraParams = [], $referenceType = null): string
642
    {
643
        try {
644
            $resourceNode = $resource->getResourceNode();
645
            if ($resourceNode->hasResourceFile()) {
646
                $params = [
647
                    'tool' => $resourceNode->getResourceType()->getTool(),
648
                    'type' => $resourceNode->getResourceType(),
649
                    'id' => $resourceNode->getId(),
650
                ];
651
652
                if (!empty($extraParams)) {
653
                    $params = array_merge($params, $extraParams);
654
                }
655
656
                $referenceType ??= UrlGeneratorInterface::ABSOLUTE_PATH;
657
658
                $mode = $params['mode'] ?? 'view';
659
                // Remove mode from params and sent directly to the controller.
660
                unset($params['mode']);
661
662
                switch ($mode) {
663
                    case 'download':
664
                        return $this->router->generate('chamilo_core_resource_download', $params, $referenceType);
0 ignored issues
show
Bug introduced by
The method generate() does not exist on null. ( Ignorable by Annotation )

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

664
                        return $this->router->/** @scrutinizer ignore-call */ generate('chamilo_core_resource_download', $params, $referenceType);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
665
                    case 'view':
666
                        return $this->router->generate('chamilo_core_resource_view', $params, $referenceType);
667
                }
668
            }
669
670
            return '';
671
        } catch (Throwable $exception) {
672
            throw new FileNotFoundException($resource->getResourceName());
673
        }
674
    }
675
676
    /**
677
     * @return bool
678
     */
679
    public function updateResourceFileContent(AbstractResource $resource, string $content)
680
    {
681
        error_log('updateResourceFileContent');
682
683
        $resourceNode = $resource->getResourceNode();
684
        if ($resourceNode->hasResourceFile()) {
685
            $resourceNode->setContent($content);
686
            error_log('updated');
687
            $resourceNode->getResourceFile()->setSize(\strlen($content));
688
            /*
689
            error_log('has file');
690
            $resourceFile = $resourceNode->getResourceFile();
691
            if ($resourceFile) {
692
                error_log('$resourceFile');
693
                $title = $resource->getResourceName();
694
                $handle = tmpfile();
695
                fwrite($handle, $content);
696
                error_log($title);
697
                error_log($content);
698
                $meta = stream_get_meta_data($handle);
699
                $file = new UploadedFile($meta['uri'], $title, 'text/html', null, true);
700
                $resource->setUploadFile($file);
701
702
                return true;
703
            }*/
704
        }
705
        error_log('false');
706
707
        return false;
708
    }
709
710
    public function setResourceName(AbstractResource $resource, $title): void
711
    {
712
        $resource->setResourceName($title);
713
        $resourceNode = $resource->getResourceNode();
714
        $resourceNode->setTitle($title);
715
        if ($resourceNode->hasResourceFile()) {
716
            //$resourceNode->getResourceFile()->getFile()->
717
            //$resourceNode->getResourceFile()->setName($title);
718
            //$resourceFile->setName($title);
719
720
            /*$fileName = $this->getResourceNodeRepository()->getFilename($resourceFile);
721
            error_log('$fileName');
722
            error_log($fileName);
723
            error_log($title);
724
            $this->getResourceNodeRepository()->getFileSystem()->rename($fileName, $title);
725
            $resourceFile->setName($title);
726
            $resourceFile->setOriginalName($title);*/
727
        }
728
    }
729
730
    /**
731
     * Change all links visibility to DELETED.
732
     */
733
    public function softDelete(AbstractResource $resource): void
734
    {
735
        $this->setLinkVisibility($resource, ResourceLink::VISIBILITY_DELETED);
736
    }
737
738
    public function setVisibilityPublished(AbstractResource $resource): void
739
    {
740
        $this->setLinkVisibility($resource, ResourceLink::VISIBILITY_PUBLISHED);
741
    }
742
743
    public function setVisibilityDeleted(AbstractResource $resource): void
744
    {
745
        $this->setLinkVisibility($resource, ResourceLink::VISIBILITY_DELETED);
746
    }
747
748
    public function setVisibilityDraft(AbstractResource $resource): void
749
    {
750
        $this->setLinkVisibility($resource, ResourceLink::VISIBILITY_DRAFT);
751
    }
752
753
    public function setVisibilityPending(AbstractResource $resource): void
754
    {
755
        $this->setLinkVisibility($resource, ResourceLink::VISIBILITY_PENDING);
756
    }
757
758
    public function createNodeForResource(ResourceInterface $resource, User $creator, ResourceNode $parentNode = null, UploadedFile $file = null): ResourceNode
759
    {
760
        $em = $this->getEntityManager();
761
762
        $resourceType = $this->getResourceType();
763
        $resourceName = $resource->getResourceName();
764
        $extension = $this->slugify->slugify(pathinfo($resourceName, PATHINFO_EXTENSION));
0 ignored issues
show
Bug introduced by
The method slugify() does not exist on null. ( Ignorable by Annotation )

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

764
        /** @scrutinizer ignore-call */ 
765
        $extension = $this->slugify->slugify(pathinfo($resourceName, PATHINFO_EXTENSION));

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
765
766
        if (empty($extension)) {
767
            $slug = $this->slugify->slugify($resourceName);
768
        } else {
769
            $originalExtension = pathinfo($resourceName, PATHINFO_EXTENSION);
770
            $originalBasename = basename($resourceName, $originalExtension);
771
            $slug = sprintf('%s.%s', $this->slugify->slugify($originalBasename), $originalExtension);
772
        }
773
774
        $resourceNode = new ResourceNode();
775
        $resourceNode
776
            ->setTitle($resourceName)
777
            ->setSlug($slug)
778
            ->setCreator($creator)
779
            ->setResourceType($resourceType)
780
        ;
781
782
        if (null !== $parentNode) {
783
            $resourceNode->setParent($parentNode);
784
        }
785
786
        $resource->setResourceNode($resourceNode);
787
        $em->persist($resourceNode);
788
        $em->persist($resource);
789
790
        if (null !== $file) {
791
            $this->addFile($resource, $file);
792
        }
793
794
        return $resourceNode;
795
    }
796
797
    public function getTotalSpaceByCourse(Course $course, CGroup $group = null, Session $session = null): int
798
    {
799
        $qb = $this->createQueryBuilder('resource');
800
        $qb
801
            ->select('SUM(file.size) as total')
802
            ->innerJoin('resource.resourceNode', 'node')
803
            ->innerJoin('node.resourceLinks', 'l')
804
            ->innerJoin('node.resourceFile', 'file')
805
            ->where('l.course = :course')
806
            ->andWhere('l.visibility <> :visibility')
807
            ->andWhere('file IS NOT NULL')
808
            ->setParameters(
809
                [
810
                    'course' => $course,
811
                    'visibility' => ResourceLink::VISIBILITY_DELETED,
812
                ]
813
            )
814
        ;
815
816
        if (null === $group) {
817
            $qb->andWhere('l.group IS NULL');
818
        } else {
819
            $qb
820
                ->andWhere('l.group = :group')
821
                ->setParameter('group', $group)
822
            ;
823
        }
824
825
        if (null === $session) {
826
            $qb->andWhere('l.session IS NULL');
827
        } else {
828
            $qb
829
                ->andWhere('l.session = :session')
830
                ->setParameter('session', $session)
831
            ;
832
        }
833
834
        $query = $qb->getQuery();
835
836
        return (int) $query->getSingleScalarResult();
837
    }
838
839
    public function addTitleDecoration(AbstractResource $resource, Course $course, Session $session = null): string
840
    {
841
        if (null === $session) {
842
            return '';
843
        }
844
845
        $link = $resource->getFirstResourceLinkFromCourseSession($course, $session);
846
        if (null === $link) {
847
            return '';
848
        }
849
850
        return '<img title="'.$session->getName().'" src="/img/icons/22/star.png" />';
851
    }
852
853
    public function isGranted(string $subject, AbstractResource $resource): bool
854
    {
855
        return $this->getAuthorizationChecker()->isGranted($subject, $resource->getResourceNode());
856
    }
857
858
    /**
859
     * Changes the visibility of the children that matches the exact same link.
860
     */
861
    public function copyVisibilityToChildren(ResourceNode $resourceNode, ResourceLink $link): bool
862
    {
863
        $children = $resourceNode->getChildren();
864
865
        if (0 === $children->count()) {
866
            return false;
867
        }
868
869
        $em = $this->getEntityManager();
870
871
        /** @var ResourceNode $child */
872
        foreach ($children as $child) {
873
            if ($child->getChildren()->count() > 0) {
874
                $this->copyVisibilityToChildren($child, $link);
875
            }
876
877
            $links = $child->getResourceLinks();
878
            foreach ($links as $linkItem) {
879
                if ($linkItem->getUser() === $link->getUser() &&
880
                    $linkItem->getSession() === $link->getSession() &&
881
                    $linkItem->getCourse() === $link->getCourse() &&
882
                    $linkItem->getUserGroup() === $link->getUserGroup()
883
                ) {
884
                    $linkItem->setVisibility($link->getVisibility());
885
                    $em->persist($linkItem);
886
                }
887
            }
888
        }
889
890
        $em->flush();
891
892
        return true;
893
    }
894
895
    public function saveUpload(UploadedFile $file): ResourceInterface
896
    {
897
        throw new Exception('Implement saveUpload');
898
    }
899
900
    public function getResourceFormType(): string
901
    {
902
        throw new Exception('Implement getResourceFormType');
903
    }
904
905
    protected function getOrCreateQueryBuilder(QueryBuilder $qb = null, string $alias = 'resource'): QueryBuilder
906
    {
907
        return $qb ?: $this->createQueryBuilder($alias);
908
    }
909
910
    protected function addTitleQueryBuilder(?string $title, QueryBuilder $qb = null): QueryBuilder
911
    {
912
        $qb = $this->getOrCreateQueryBuilder($qb);
913
        if (null === $title) {
914
            return $qb;
915
        }
916
917
        $qb
918
            ->andWhere('node.title = :title')
919
            ->setParameter('title', $title)
920
        ;
921
922
        return $qb;
923
    }
924
925
    protected function addCreatorQueryBuilder(?User $user, QueryBuilder $qb = null): QueryBuilder
926
    {
927
        $qb = $this->getOrCreateQueryBuilder($qb);
928
        if (null === $user) {
929
            return $qb;
930
        }
931
932
        $qb
933
            ->andWhere('node.creator = :creator')
934
            ->setParameter('creator', $user)
935
        ;
936
937
        return $qb;
938
    }
939
940
    private function setLinkVisibility(AbstractResource $resource, int $visibility, bool $recursive = true): bool
941
    {
942
        $resourceNode = $resource->getResourceNode();
943
944
        if (null === $resourceNode) {
945
            return false;
946
        }
947
948
        $em = $this->getEntityManager();
949
        if ($recursive) {
950
            $children = $resourceNode->getChildren();
951
            if (!empty($children)) {
952
                /** @var ResourceNode $child */
953
                foreach ($children as $child) {
954
                    $criteria = [
955
                        'resourceNode' => $child,
956
                    ];
957
                    $childDocument = $this->findOneBy($criteria);
958
                    if ($childDocument) {
959
                        $this->setLinkVisibility($childDocument, $visibility);
960
                    }
961
                }
962
            }
963
        }
964
965
        $links = $resourceNode->getResourceLinks();
966
967
        if (!empty($links)) {
968
            /** @var ResourceLink $link */
969
            foreach ($links as $link) {
970
                $link->setVisibility($visibility);
971
                if (ResourceLink::VISIBILITY_DRAFT === $visibility) {
972
                    $editorMask = ResourceNodeVoter::getEditorMask();
973
                    //$rights = [];
974
                    $resourceRight = new ResourceRight();
975
                    $resourceRight
976
                        ->setMask($editorMask)
977
                        ->setRole(ResourceNodeVoter::ROLE_CURRENT_COURSE_TEACHER)
978
                        ->setResourceLink($link)
979
                    ;
980
                    $link->addResourceRight($resourceRight);
981
                } else {
982
                    $link->setResourceRights(new ArrayCollection());
983
                }
984
                $em->persist($link);
985
            }
986
        }
987
        $em->flush();
988
989
        return true;
990
    }
991
}
992