Completed
Push — master ( 711556...cbfb7e )
by Julito
13:30
created

ResourceRepository::addResourceToMe()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 7
c 0
b 0
f 0
nop 1
dl 0
loc 11
rs 10
nc 1
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
namespace Chamilo\CoreBundle\Repository;
5
6
use APY\DataGridBundle\Grid\Action\RowAction;
7
use APY\DataGridBundle\Grid\Row;
8
use Chamilo\CoreBundle\Component\Utils\ResourceSettings;
9
use Chamilo\CoreBundle\Entity\Course;
10
use Chamilo\CoreBundle\Entity\Resource\AbstractResource;
11
use Chamilo\CoreBundle\Entity\Resource\ResourceFile;
12
use Chamilo\CoreBundle\Entity\Resource\ResourceLink;
13
use Chamilo\CoreBundle\Entity\Resource\ResourceNode;
14
use Chamilo\CoreBundle\Entity\Resource\ResourceRight;
15
use Chamilo\CoreBundle\Entity\Resource\ResourceType;
16
use Chamilo\CoreBundle\Entity\Session;
17
use Chamilo\CoreBundle\Entity\Tool;
18
use Chamilo\CoreBundle\Entity\Usergroup;
19
use Chamilo\CoreBundle\Security\Authorization\Voter\ResourceNodeVoter;
20
use Chamilo\CourseBundle\Entity\CGroupInfo;
21
use Chamilo\UserBundle\Entity\User;
22
use Cocur\Slugify\SlugifyInterface;
23
use Doctrine\ORM\EntityManager;
24
use Doctrine\ORM\Query\Expr\Join;
25
use Doctrine\ORM\QueryBuilder;
26
use League\Flysystem\FilesystemInterface;
27
use League\Flysystem\MountManager;
28
use Sylius\Bundle\ResourceBundle\Doctrine\ORM\EntityRepository;
29
use Symfony\Component\Filesystem\Exception\FileNotFoundException;
30
use Symfony\Component\Form\FormFactory;
31
use Symfony\Component\Form\FormInterface;
32
use Symfony\Component\HttpFoundation\File\UploadedFile;
33
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
34
use Symfony\Component\Routing\RouterInterface;
35
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
36
37
/**
38
 * Class ResourceRepository.
39
 * Extends EntityRepository is needed to process settings.
40
 */
41
class ResourceRepository extends EntityRepository
42
{
43
    /**
44
     * @var EntityRepository
45
     */
46
    protected $repository;
47
48
    /**
49
     * @var FilesystemInterface
50
     */
51
    protected $fs;
52
53
    /**
54
     * @var EntityManager
55
     */
56
    protected $entityManager;
57
58
    /**
59
     * The entity class FQN.
60
     *
61
     * @var string
62
     */
63
    protected $className;
64
65
    /** @var RouterInterface */
66
    protected $router;
67
68
    protected $resourceNodeRepository;
69
70
    /**
71
     * @var AuthorizationCheckerInterface
72
     */
73
    protected $authorizationChecker;
74
75
    /** @var MountManager */
76
    protected $mountManager;
77
78
    /** @var SlugifyInterface */
79
    protected $slugify;
80
81
    /**
82
     * ResourceRepository constructor.
83
     */
84
    public function __construct(
85
        AuthorizationCheckerInterface $authorizationChecker,
86
        EntityManager $entityManager,
87
        MountManager $mountManager,
88
        RouterInterface $router,
89
        SlugifyInterface $slugify,
90
        string $className
91
    ) {
92
        $this->authorizationChecker = $authorizationChecker;
93
        $this->repository = $entityManager->getRepository($className);
94
        // Flysystem mount name is saved in config/packages/oneup_flysystem.yaml @todo add it as a service.
95
        $this->fs = $mountManager->getFilesystem('resources_fs');
96
        $this->mountManager = $mountManager;
97
        $this->router = $router;
98
        $this->resourceNodeRepository = $entityManager->getRepository('ChamiloCoreBundle:Resource\ResourceNode');
99
        $this->slugify = $slugify;
100
    }
101
102
    public function getAuthorizationChecker(): AuthorizationCheckerInterface
103
    {
104
        return $this->authorizationChecker;
105
    }
106
107
    /**
108
     * @return mixed
109
     */
110
    public function create()
111
    {
112
        return new $this->className();
113
    }
114
115
    public function getRouter(): RouterInterface
116
    {
117
        return $this->router;
118
    }
119
120
    /**
121
     * @return ResourceNodeRepository
122
     */
123
    public function getResourceNodeRepository()
124
    {
125
        return $this->resourceNodeRepository;
126
    }
127
128
    /**
129
     * @return FilesystemInterface
130
     */
131
    public function getFileSystem()
132
    {
133
        return $this->fs;
134
    }
135
136
    public function getEntityManager(): EntityManager
137
    {
138
        return $this->getRepository()->getEntityManager();
139
    }
140
141
    /**
142
     * @return EntityRepository
143
     */
144
    public function getRepository()
145
    {
146
        return $this->repository;
147
    }
148
149
    /**
150
     * @return FormInterface
151
     */
152
    public function getForm(FormFactory $formFactory, AbstractResource $resource = null, $options = [])
153
    {
154
        $className = $this->repository->getClassName();
155
        $shortName = (new \ReflectionClass($className))->getShortName();
156
157
        // @todo remove hardcode class loading
158
        $formType = 'Chamilo\CoreBundle\Form\Resource\\'.$shortName.'Type';
159
        if ($resource === null) {
160
            $resource = new $className();
161
        }
162
163
        return $formFactory->create($formType, $resource, $options);
164
    }
165
166
    /**
167
     * @param mixed $id
168
     * @param null  $lockMode
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $lockMode is correct as it would always require null to be passed?
Loading history...
169
     * @param null  $lockVersion
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $lockVersion is correct as it would always require null to be passed?
Loading history...
170
     */
171
    public function find($id, $lockMode = null, $lockVersion = null) //: ?AbstractResource
172
    {
173
        return $this->getRepository()->find($id);
174
    }
175
176
    public function findOneBy(array $criteria, array $orderBy = null): ?AbstractResource
177
    {
178
        return $this->getRepository()->findOneBy($criteria, $orderBy);
179
    }
180
181
    public function createNodeForResource(AbstractResource $resource, User $creator, ResourceNode $parent = null, UploadedFile $file = null): ResourceNode
182
    {
183
        $em = $this->getEntityManager();
184
185
        $resourceType = $this->getResourceType();
186
        $resourceNode = new ResourceNode();
187
        $resourceName = $resource->getResourceName();
0 ignored issues
show
Bug introduced by
The method getResourceName() does not exist on Chamilo\CoreBundle\Entit...source\AbstractResource. Did you maybe mean getResourceNode()? ( Ignorable by Annotation )

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

187
        /** @scrutinizer ignore-call */ 
188
        $resourceName = $resource->getResourceName();

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...
188
        $extension = $this->slugify->slugify(pathinfo($resourceName, PATHINFO_EXTENSION));
189
190
        if (empty($extension)) {
191
            $slug = $this->slugify->slugify($resourceName);
192
        } else {
193
            $originalExtension = pathinfo($resourceName, PATHINFO_EXTENSION);
194
            $originalBasename = \basename($resourceName, $originalExtension);
195
            $slug = sprintf('%s.%s', $this->slugify->slugify($originalBasename), $originalExtension);
196
        }
197
198
        $resourceNode
199
            ->setSlug($slug)
200
            ->setCreator($creator)
201
            ->setResourceType($resourceType)
202
        ;
203
204
        if (null !== $parent) {
205
            $resourceNode->setParent($parent);
206
        }
207
208
        $resource->setResourceNode($resourceNode);
209
        $em->persist($resourceNode);
210
        $em->persist($resource);
211
212
        if (null !== $file) {
213
            $this->addFile($resource, $file);
214
        }
215
216
        return $resourceNode;
217
    }
218
219
    public function updateNodeForResource(AbstractResource $resource): ResourceNode
220
    {
221
        $em = $this->getEntityManager();
222
223
        $resourceNode = $resource->getResourceNode();
224
        $resourceName = $resource->getResourceName();
225
226
        if ($resourceNode->hasResourceFile()) {
227
            $resourceFile = $resourceNode->getResourceFile();
228
            $originalName = $resourceFile->getOriginalName();
229
            $originalExtension = pathinfo($originalName, PATHINFO_EXTENSION);
230
231
            $originalBasename = \basename($resourceName, $originalExtension);
232
            $slug = sprintf(
233
                '%s.%s',
234
                $this->slugify->slugify($originalBasename),
235
                $this->slugify->slugify($originalExtension)
236
            );
237
238
            $newOriginalName = sprintf('%s.%s', $resourceName, $originalExtension);
239
            $resourceFile->setOriginalName($newOriginalName);
240
241
            $em->persist($resourceFile);
242
        } else {
243
            $slug = $this->slugify->slugify($resourceName);
244
        }
245
246
        $resourceNode->setSlug($slug);
247
248
        $em->persist($resourceNode);
249
        $em->persist($resource);
250
251
        $em->flush();
252
253
        return $resourceNode;
254
    }
255
256
    public function addFile(AbstractResource $resource, UploadedFile $file): ?ResourceFile
257
    {
258
        $resourceNode = $resource->getResourceNode();
259
260
        if (null === $resourceNode) {
261
            throw new \LogicException('Resource node is null');
262
        }
263
264
        $resourceFile = $resourceNode->getResourceFile();
265
        if (null === $resourceFile) {
266
            $resourceFile = new ResourceFile();
267
        }
268
269
        $em = $this->getEntityManager();
270
        //$resourceFile->setMimeType($file->getMimeType());
271
        $resourceFile->setFile($file);
272
        $resourceFile->setName($resource->getResourceName());
273
        $em->persist($resourceFile);
274
275
        $resourceNode->setResourceFile($resourceFile);
276
        $em->persist($resourceNode);
277
278
        return $resourceFile;
279
    }
280
281
    public function addResourceNode(AbstractResource $resource, User $creator, AbstractResource $parent = null): ResourceNode
282
    {
283
        if (null !== $parent) {
284
            $parent = $parent->getResourceNode();
285
        }
286
287
        return $this->createNodeForResource($resource, $creator, $parent);
288
    }
289
290
    public function addResourceToCourse(AbstractResource $resource, int $visibility, User $creator, Course $course, Session $session = null, CGroupInfo $group = null)
291
    {
292
        $node = $this->createNodeForResource($resource, $creator, $course->getResourceNode());
293
294
        $this->addResourceNodeToCourse($node, $visibility, $course, $session, $group);
295
    }
296
297
    /**
298
     * @param int        $visibility
299
     * @param Course     $course
300
     * @param Session    $session
301
     * @param CGroupInfo $group
302
     */
303
    public function addResourceNodeToCourse(ResourceNode $resourceNode, $visibility, $course, $session, $group): void
304
    {
305
        $visibility = (int) $visibility;
306
        if (empty($visibility)) {
307
            $visibility = ResourceLink::VISIBILITY_PUBLISHED;
308
        }
309
310
        $link = new ResourceLink();
311
        $link
312
            ->setCourse($course)
313
            ->setSession($session)
314
            ->setGroup($group)
315
            //->setUser($toUser)
316
            ->setResourceNode($resourceNode)
317
            ->setVisibility($visibility)
318
        ;
319
320
        $rights = [];
321
        switch ($visibility) {
322
            case ResourceLink::VISIBILITY_PENDING:
323
            case ResourceLink::VISIBILITY_DRAFT:
324
                $editorMask = ResourceNodeVoter::getEditorMask();
325
                $resourceRight = new ResourceRight();
326
                $resourceRight
327
                    ->setMask($editorMask)
328
                    ->setRole(ResourceNodeVoter::ROLE_CURRENT_COURSE_TEACHER)
329
                ;
330
                $rights[] = $resourceRight;
331
                break;
332
        }
333
334
        if (!empty($rights)) {
335
            foreach ($rights as $right) {
336
                $link->addResourceRight($right);
337
            }
338
        }
339
340
        $em = $this->getEntityManager();
341
        $em->persist($link);
342
    }
343
344
    /**
345
     * @return ResourceType
346
     */
347
    public function getResourceType()
348
    {
349
        $em = $this->getEntityManager();
350
        $service = get_class($this);
351
352
        return $em->getRepository('ChamiloCoreBundle:Resource\ResourceType')->findOneBy(
353
            ['service' => $service]
354
        );
355
    }
356
357
    public function addResourceToMe(ResourceNode $resourceNode): ResourceLink
358
    {
359
        $resourceLink = new ResourceLink();
360
        $resourceLink
361
            ->setResourceNode($resourceNode)
362
            ->setPrivate(true);
0 ignored issues
show
Bug introduced by
The method setPrivate() does not exist on Chamilo\CoreBundle\Entity\Resource\ResourceLink. ( Ignorable by Annotation )

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

362
            ->/** @scrutinizer ignore-call */ setPrivate(true);

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...
363
364
        $this->getEntityManager()->persist($resourceLink);
365
        $this->getEntityManager()->flush();
366
367
        return $resourceLink;
368
    }
369
370
    public function addResourceToEveryone(ResourceNode $resourceNode, ResourceRight $right): ResourceLink
371
    {
372
        $resourceLink = new ResourceLink();
373
        $resourceLink
374
            ->setResourceNode($resourceNode)
375
            ->addResourceRight($right)
376
        ;
377
378
        $this->getEntityManager()->persist($resourceLink);
379
        $this->getEntityManager()->flush();
380
381
        return $resourceLink;
382
    }
383
384
    public function addResourceToCourse2(ResourceNode $resourceNode, Course $course, ResourceRight $right): ResourceLink
385
    {
386
        $resourceLink = new ResourceLink();
387
        $resourceLink
388
            ->setResourceNode($resourceNode)
389
            ->setCourse($course)
390
            ->addResourceRight($right);
391
        $this->getEntityManager()->persist($resourceLink);
392
        $this->getEntityManager()->flush();
393
394
        return $resourceLink;
395
    }
396
397
    public function addResourceToUser(ResourceNode $resourceNode, User $toUser): ResourceLink
398
    {
399
        $resourceLink = $this->addResourceNodeToUser($resourceNode, $toUser);
400
        $this->getEntityManager()->persist($resourceLink);
401
402
        return $resourceLink;
403
    }
404
405
    public function addResourceNodeToUser(ResourceNode $resourceNode, User $toUser): ResourceLink
406
    {
407
        $resourceLink = new ResourceLink();
408
        $resourceLink
409
            ->setResourceNode($resourceNode)
410
            ->setUser($toUser);
411
412
        return $resourceLink;
413
    }
414
415
    public function addResourceToSession(
416
        ResourceNode $resourceNode,
417
        Course $course,
418
        Session $session,
419
        ResourceRight $right
420
    ) {
421
        $resourceLink = $this->addResourceToCourse(
0 ignored issues
show
Bug introduced by
The call to Chamilo\CoreBundle\Repos...::addResourceToCourse() has too few arguments starting with course. ( Ignorable by Annotation )

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

421
        /** @scrutinizer ignore-call */ 
422
        $resourceLink = $this->addResourceToCourse(

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
Bug introduced by
Are you sure the assignment to $resourceLink is correct as $this->addResourceToCour...eNode, $course, $right) targeting Chamilo\CoreBundle\Repos...::addResourceToCourse() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
422
            $resourceNode,
423
            $course,
424
            $right
425
        );
426
        $resourceLink->setSession($session);
427
        $this->getEntityManager()->persist($resourceLink);
428
429
        return $resourceLink;
430
    }
431
432
    /**
433
     * @return ResourceLink
434
     */
435
    public function addResourceToCourseGroup(
436
        ResourceNode $resourceNode,
437
        Course $course,
438
        CGroupInfo $group,
439
        ResourceRight $right
440
    ) {
441
        $resourceLink = $this->addResourceToCourse(
0 ignored issues
show
Bug introduced by
The call to Chamilo\CoreBundle\Repos...::addResourceToCourse() has too few arguments starting with course. ( Ignorable by Annotation )

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

441
        /** @scrutinizer ignore-call */ 
442
        $resourceLink = $this->addResourceToCourse(

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
Bug introduced by
Are you sure the assignment to $resourceLink is correct as $this->addResourceToCour...eNode, $course, $right) targeting Chamilo\CoreBundle\Repos...::addResourceToCourse() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
442
            $resourceNode,
443
            $course,
444
            $right
445
        );
446
        $resourceLink->setGroup($group);
447
        $this->getEntityManager()->persist($resourceLink);
448
449
        return $resourceLink;
450
    }
451
452
    /**
453
     * @return ResourceLink
454
     */
455
    public function addResourceToGroup(
456
        ResourceNode $resourceNode,
457
        Usergroup $group,
458
        ResourceRight $right
459
    ) {
460
        $resourceLink = new ResourceLink();
461
        $resourceLink
462
            ->setResourceNode($resourceNode)
463
            ->setUserGroup($group)
464
            ->addResourceRight($right);
465
466
        return $resourceLink;
467
    }
468
469
    /**
470
     * @param array $userList User id list
471
     */
472
    public function addResourceToUserList(ResourceNode $resourceNode, array $userList)
473
    {
474
        $em = $this->getEntityManager();
475
476
        if (!empty($userList)) {
477
            foreach ($userList as $userId) {
478
                $toUser = $em->getRepository('ChamiloUserBundle:User')->find($userId);
479
480
                $resourceLink = $this->addResourceNodeToUser($resourceNode, $toUser);
481
                $em->persist($resourceLink);
482
            }
483
        }
484
    }
485
486
    /**
487
     * @return QueryBuilder
488
     */
489
    public function getResourcesByCourse(Course $course, Session $session = null, CGroupInfo $group = null, ResourceNode $parentNode = null)
490
    {
491
        $repo = $this->getRepository();
492
        $className = $repo->getClassName();
493
        $checker = $this->getAuthorizationChecker();
494
495
        $reflectionClass = $repo->getClassMetadata()->getReflectionClass();
496
497
        // Check if this resource type requires to load the base course resources when using a session
498
        $loadBaseSessionContent = $reflectionClass->hasProperty('loadCourseResourcesInSession');
499
500
        $type = $this->getResourceType();
501
502
        $qb = $repo->getEntityManager()->createQueryBuilder()
503
            ->select('resource')
504
            ->from($className, 'resource')
505
            ->innerJoin(
506
                ResourceNode::class,
507
                'node',
508
                Join::WITH,
509
                'resource.resourceNode = node.id'
510
            )
511
            ->innerJoin('node.resourceLinks', 'links')
512
            ->where('node.resourceType = :type')
513
            ->setParameter('type', $type);
514
        $qb
515
            ->andWhere('links.course = :course')
516
            ->setParameter('course', $course)
517
        ;
518
519
        $isAdmin = $checker->isGranted('ROLE_ADMIN') ||
520
            $checker->isGranted('ROLE_CURRENT_COURSE_TEACHER');
521
522
        // Do not show deleted resources
523
524
        $qb
525
            ->andWhere('links.visibility != :visibilityDeleted')
526
            ->setParameter('visibilityDeleted', ResourceLink::VISIBILITY_DELETED)
527
        ;
528
529
        if (false === $isAdmin) {
530
            $qb
531
                ->andWhere('links.visibility = :visibility')
532
                ->setParameter('visibility', ResourceLink::VISIBILITY_PUBLISHED)
533
            ;
534
            // @todo Add start/end visibility restrictrions
535
        }
536
537
        if (null === $session) {
538
            $qb->andWhere('links.session IS NULL');
539
        } else {
540
            if ($loadBaseSessionContent) {
541
                // Load course base content.
542
                $qb->andWhere('links.session = :session OR links.session IS NULL');
543
                $qb->setParameter('session', $session);
544
            } else {
545
                // Load only session resources.
546
                $qb->andWhere('links.session = :session');
547
                $qb->setParameter('session', $session);
548
            }
549
        }
550
551
        if (null !== $parentNode) {
552
            $qb->andWhere('node.parent = :parentNode');
553
            $qb->setParameter('parentNode', $parentNode);
554
        }
555
556
        if (null === $group) {
557
            $qb->andWhere('links.group IS NULL');
558
        }
559
560
        ///var_dump($qb->getQuery()->getSQL(), $type->getId(), $parentNode->getId());exit;
561
562
        return $qb;
563
    }
564
565
    /**
566
     * @return QueryBuilder
567
     */
568
    public function getResourcesByCreator(User $user, ResourceNode $parentNode = null)
569
    {
570
        $repo = $this->getRepository();
571
        $className = $repo->getClassName();
572
        $checker = $this->getAuthorizationChecker();
573
        $reflectionClass = $repo->getClassMetadata()->getReflectionClass();
574
        //$isPersonalResource = $reflectionClass->hasProperty('loadPersonalResources');
575
576
        $type = $this->getResourceType();
577
578
        $qb = $repo->getEntityManager()->createQueryBuilder()
579
            ->select('resource')
580
            ->from($className, 'resource')
581
            ->innerJoin(
582
                ResourceNode::class,
583
                'node',
584
                Join::WITH,
585
                'resource.resourceNode = node.id'
586
            )
587
            //->innerJoin('node.resourceLinks', 'links')
588
            //->where('node.resourceType = :type')
589
            //->setParameter('type',$type)
590
            ;
591
        /*$qb
592
            ->andWhere('links.visibility = :visibility')
593
            ->setParameter('visibility', ResourceLink::VISIBILITY_PUBLISHED)
594
        ;*/
595
596
        if (null !== $parentNode) {
597
            $qb->andWhere('node.parent = :parentNode');
598
            $qb->setParameter('parentNode', $parentNode);
599
        }
600
601
        $qb->andWhere('node.creator = :creator');
602
        $qb->setParameter('creator', $user);
603
        //var_dump($qb->getQuery()->getSQL(), $parentNode->getId());exit;
604
605
        return $qb;
606
    }
607
608
    public function getResourceFromResourceNode($resourceNodeId): ?AbstractResource
609
    {
610
        $resource = $this->getRepository()->findOneBy(['resourceNode' => $resourceNodeId]);
611
612
        return $resource;
613
    }
614
615
    /**
616
     * @param Session $session
617
     */
618
    public function rowCanBeEdited(RowAction $action, Row $row, Session $session = null): ?RowAction
619
    {
620
        if (null !== $session) {
621
            /** @var AbstractResource $entity */
622
            $entity = $row->getEntity();
623
            $hasSession = $entity->getResourceNode()->hasSession($session);
624
            if ($hasSession->count() > 0) {
625
                return $action;
626
            }
627
628
            return null;
629
        }
630
631
        return $action;
632
    }
633
634
    /**
635
     * Deletes several entities: AbstractResource (Ex: CDocument, CQuiz), ResourceNode,
636
     * ResourceLinks and ResourceFile (including files via Flysystem).
637
     */
638
    public function hardDelete(AbstractResource $resource)
639
    {
640
        $em = $this->getEntityManager();
641
        $em->remove($resource);
642
        $em->flush();
643
    }
644
645
    /**
646
     * Change all links visibility to DELETED.
647
     */
648
    public function softDelete(AbstractResource $resource)
649
    {
650
        $this->setLinkVisibility($resource, ResourceLink::VISIBILITY_DELETED);
651
    }
652
653
    public function setVisibilityPublished(AbstractResource $resource)
654
    {
655
        $this->setLinkVisibility($resource, ResourceLink::VISIBILITY_PUBLISHED);
656
    }
657
658
    public function setVisibilityDraft(AbstractResource $resource)
659
    {
660
        $this->setLinkVisibility($resource, ResourceLink::VISIBILITY_DRAFT);
661
    }
662
663
    public function setVisibilityPending(AbstractResource $resource)
664
    {
665
        $this->setLinkVisibility($resource, ResourceLink::VISIBILITY_PENDING);
666
    }
667
668
    public function getResourceFileContent(AbstractResource $resource): string
669
    {
670
        try {
671
            $resourceNode = $resource->getResourceNode();
672
            if ($resourceNode->hasResourceFile()) {
673
                $resourceFile = $resourceNode->getResourceFile();
674
                $fileName = $resourceFile->getFile()->getPathname();
675
676
                return $this->fs->read($fileName);
677
            }
678
679
            return '';
680
        } catch (\Throwable $exception) {
681
            throw new FileNotFoundException($resource);
682
        }
683
    }
684
685
    public function getResourceNodeFileContent(ResourceNode $resourceNode): string
686
    {
687
        try {
688
            if ($resourceNode->hasResourceFile()) {
689
                $resourceFile = $resourceNode->getResourceFile();
690
                $fileName = $resourceFile->getFile()->getPathname();
691
692
                return $this->fs->read($fileName);
693
            }
694
695
            return '';
696
        } catch (\Throwable $exception) {
697
            throw new FileNotFoundException($resourceNode);
698
        }
699
    }
700
701
    public function getResourceNodeFileStream(ResourceNode $resourceNode)
702
    {
703
        try {
704
            if ($resourceNode->hasResourceFile()) {
705
                $resourceFile = $resourceNode->getResourceFile();
706
                $fileName = $resourceFile->getFile()->getPathname();
707
708
                return $this->fs->readStream($fileName);
709
            }
710
711
            return '';
712
        } catch (\Throwable $exception) {
713
            throw new FileNotFoundException($resourceNode);
714
        }
715
    }
716
717
    public function getResourceFileUrl(AbstractResource $resource, array $extraParams = [], $referenceType = null): string
718
    {
719
        try {
720
            $resourceNode = $resource->getResourceNode();
721
            if ($resourceNode->hasResourceFile()) {
722
                $params = [
723
                    'tool' => $resourceNode->getResourceType()->getTool(),
724
                    'type' => $resourceNode->getResourceType(),
725
                    'id' => $resourceNode->getId(),
726
                ];
727
728
                if (!empty($extraParams)) {
729
                    $params = array_merge($params, $extraParams);
730
                }
731
732
                $referenceType = null === $referenceType ? UrlGeneratorInterface::ABSOLUTE_PATH : $referenceType;
733
734
                return $this->router->generate('chamilo_core_resource_view', $params, $referenceType);
735
            }
736
737
            return '';
738
        } catch (\Throwable $exception) {
739
            throw new FileNotFoundException($resource);
740
        }
741
    }
742
743
    /**
744
     * @param string $content
745
     *
746
     * @return bool
747
     */
748
    public function updateResourceFileContent(AbstractResource $resource, $content)
749
    {
750
        try {
751
            $resourceNode = $resource->getResourceNode();
752
            if ($resourceNode->hasResourceFile()) {
753
                $resourceFile = $resourceNode->getResourceFile();
754
                $fileName = $resourceFile->getFile()->getPathname();
755
756
                $this->fs->update($fileName, $content);
757
                $size = $this->fs->getSize($fileName);
758
                $resource->setSize($size);
0 ignored issues
show
Bug introduced by
The method setSize() does not exist on Chamilo\CoreBundle\Entit...source\AbstractResource. It seems like you code against a sub-type of Chamilo\CoreBundle\Entit...source\AbstractResource such as Chamilo\CourseBundle\Entity\CDocument. ( Ignorable by Annotation )

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

758
                $resource->/** @scrutinizer ignore-call */ 
759
                           setSize($size);
Loading history...
759
                $this->entityManager->persist($resource);
760
761
                return true;
762
            }
763
764
            return false;
765
        } catch (\Throwable $exception) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
766
        }
767
    }
768
769
    public function getResourceSettings(): ResourceSettings
770
    {
771
        $settings = new ResourceSettings();
772
        $settings
773
            ->setAllowNodeCreation(false)
774
            ->setAllowResourceCreation(false)
775
            ->setAllowResourceUpload(false)
776
        ;
777
778
        return $settings;
779
    }
780
781
    /**
782
     * @param string $tool
783
     *
784
     * @return Tool|null
785
     */
786
    private function getTool($tool)
787
    {
788
        return $this
789
            ->getEntityManager()
790
            ->getRepository('ChamiloCoreBundle:Tool')
791
            ->findOneBy(['name' => $tool]);
792
    }
793
794
    private function setLinkVisibility(AbstractResource $resource, int $visibility, bool $recursive = true): bool
795
    {
796
        $resourceNode = $resource->getResourceNode();
797
798
        if (null === $resourceNode) {
799
            return false;
800
        }
801
802
        $em = $this->getEntityManager();
803
        if ($recursive) {
804
            $children = $resourceNode->getChildren();
805
            if (!empty($children)) {
806
                /** @var ResourceNode $child */
807
                foreach ($children as $child) {
808
                    $criteria = ['resourceNode' => $child];
809
                    $childDocument = $this->getRepository()->findOneBy($criteria);
810
                    if ($childDocument) {
811
                        $this->setLinkVisibility($childDocument, $visibility);
812
                    }
813
                }
814
            }
815
        }
816
817
        $links = $resourceNode->getResourceLinks();
818
819
        if (!empty($links)) {
820
            /** @var ResourceLink $link */
821
            foreach ($links as $link) {
822
                $link->setVisibility($visibility);
823
                if (ResourceLink::VISIBILITY_DRAFT === $visibility) {
824
                    $editorMask = ResourceNodeVoter::getEditorMask();
825
                    $rights = [];
826
                    $resourceRight = new ResourceRight();
827
                    $resourceRight
828
                        ->setMask($editorMask)
829
                        ->setRole(ResourceNodeVoter::ROLE_CURRENT_COURSE_TEACHER)
830
                        ->setResourceLink($link)
831
                    ;
832
                    $rights[] = $resourceRight;
833
834
                    if (!empty($rights)) {
835
                        $link->setResourceRight($rights);
836
                    }
837
                } else {
838
                    $link->setResourceRight([]);
839
                }
840
                $em->persist($link);
841
            }
842
        }
843
        $em->flush();
844
845
        return true;
846
    }
847
}
848