Completed
Push — master ( f67c92...339b0b )
by Julito
15:21
created

ResourceRepository::addResourceToGroup()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 6
nc 1
nop 3
dl 0
loc 12
rs 10
c 0
b 0
f 0
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\RouterInterface;
34
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
35
36
/**
37
 * Class ResourceRepository.
38
 * Extends EntityRepository is needed to process settings.
39
 */
40
class ResourceRepository extends EntityRepository
41
{
42
    /**
43
     * @var EntityRepository
44
     */
45
    protected $repository;
46
47
    /**
48
     * @var FilesystemInterface
49
     */
50
    protected $fs;
51
52
    /**
53
     * @var EntityManager
54
     */
55
    protected $entityManager;
56
57
    /**
58
     * The entity class FQN.
59
     *
60
     * @var string
61
     */
62
    protected $className;
63
64
    /** @var RouterInterface */
65
    protected $router;
66
67
    protected $resourceNodeRepository;
68
69
    /**
70
     * @var AuthorizationCheckerInterface
71
     */
72
    protected $authorizationChecker;
73
74
    /** @var MountManager */
75
    protected $mountManager;
76
77
    /** @var SlugifyInterface */
78
    protected $slugify;
79
80
    /**
81
     * ResourceRepository constructor.
82
     */
83
    public function __construct(
84
        AuthorizationCheckerInterface $authorizationChecker,
85
        EntityManager $entityManager,
86
        MountManager $mountManager,
87
        RouterInterface $router,
88
        SlugifyInterface $slugify,
89
        string $className
90
    ) {
91
        $this->authorizationChecker = $authorizationChecker;
92
        $this->repository = $entityManager->getRepository($className);
93
        // Flysystem mount name is saved in config/packages/oneup_flysystem.yaml @todo add it as a service.
94
        $this->fs = $mountManager->getFilesystem('resources_fs');
95
        $this->mountManager = $mountManager;
96
        $this->router = $router;
97
        $this->resourceNodeRepository = $entityManager->getRepository('ChamiloCoreBundle:Resource\ResourceNode');
98
        $this->slugify = $slugify;
99
    }
100
101
    public function getAuthorizationChecker(): AuthorizationCheckerInterface
102
    {
103
        return $this->authorizationChecker;
104
    }
105
106
    /**
107
     * @return mixed
108
     */
109
    public function create()
110
    {
111
        return new $this->className();
112
    }
113
114
    public function getRouter(): RouterInterface
115
    {
116
        return $this->router;
117
    }
118
119
    /**
120
     * @return ResourceNodeRepository
121
     */
122
    public function getResourceNodeRepository()
123
    {
124
        return $this->resourceNodeRepository;
125
    }
126
127
    /**
128
     * @return FilesystemInterface
129
     */
130
    public function getFileSystem()
131
    {
132
        return $this->fs;
133
    }
134
135
    public function getEntityManager(): EntityManager
136
    {
137
        return $this->getRepository()->getEntityManager();
138
    }
139
140
    /**
141
     * @return EntityRepository
142
     */
143
    public function getRepository()
144
    {
145
        return $this->repository;
146
    }
147
148
    /**
149
     * @return FormInterface
150
     */
151
    public function getForm(FormFactory $formFactory, AbstractResource $resource = null, $options = [])
152
    {
153
        $className = $this->repository->getClassName();
154
        $shortName = (new \ReflectionClass($className))->getShortName();
155
156
        // @todo remove hardcode class loading
157
        $formType = 'Chamilo\CoreBundle\Form\Resource\\'.$shortName.'Type';
158
        if ($resource === null) {
159
            $resource = new $className();
160
        }
161
162
        return $formFactory->create($formType, $resource, $options);
163
    }
164
165
    /**
166
     * @param mixed $id
167
     * @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...
168
     * @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...
169
     */
170
    public function find($id, $lockMode = null, $lockVersion = null) //: ?AbstractResource
171
    {
172
        return $this->getRepository()->find($id);
173
    }
174
175
    public function findOneBy(array $criteria, array $orderBy = null): ?AbstractResource
176
    {
177
        return $this->getRepository()->findOneBy($criteria, $orderBy);
178
    }
179
180
    public function createNodeForResource(AbstractResource $resource, User $creator, ResourceNode $parent = null, UploadedFile $file = null): ResourceNode
181
    {
182
        $em = $this->getEntityManager();
183
184
        $resourceType = $this->getResourceType();
185
        $resourceNode = new ResourceNode();
186
        $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

186
        /** @scrutinizer ignore-call */ 
187
        $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...
187
        $extension = $this->slugify->slugify(pathinfo($resourceName, PATHINFO_EXTENSION));
188
189
        if (empty($extension)) {
190
            $slug = $this->slugify->slugify($resourceName);
191
        } else {
192
            $originalExtension = pathinfo($resourceName, PATHINFO_EXTENSION);
193
            $originalBasename = \basename($resourceName, $originalExtension);
194
            $slug = sprintf('%s.%s', $this->slugify->slugify($originalBasename), $originalExtension);
195
        }
196
197
        $resourceNode
198
            ->setSlug($slug)
199
            ->setCreator($creator)
200
            ->setResourceType($resourceType)
201
        ;
202
203
        if (null !== $parent) {
204
            $resourceNode->setParent($parent);
205
        }
206
207
        $resource->setResourceNode($resourceNode);
208
        $em->persist($resourceNode);
209
        $em->persist($resource);
210
211
        if (null !== $file) {
212
            $this->addFile($resource, $file);
213
        }
214
215
        return $resourceNode;
216
    }
217
218
    public function updateNodeForResource(AbstractResource $resource): ResourceNode
219
    {
220
        $em = $this->getEntityManager();
221
222
        $resourceNode = $resource->getResourceNode();
223
        $resourceName = $resource->getResourceName();
224
225
        if ($resourceNode->hasResourceFile()) {
226
            $resourceFile = $resourceNode->getResourceFile();
227
            $originalName = $resourceFile->getOriginalName();
228
            $originalExtension = pathinfo($originalName, PATHINFO_EXTENSION);
229
230
            $originalBasename = \basename($resourceName, $originalExtension);
231
            $slug = sprintf(
232
                '%s.%s',
233
                $this->slugify->slugify($originalBasename),
234
                $this->slugify->slugify($originalExtension)
235
            );
236
237
            $newOriginalName = sprintf('%s.%s', $resourceName, $originalExtension);
238
            $resourceFile->setOriginalName($newOriginalName);
239
240
            $em->persist($resourceFile);
241
        } else {
242
            $slug = $this->slugify->slugify($resourceName);
243
        }
244
245
        $resourceNode->setSlug($slug);
246
247
        $em->persist($resourceNode);
248
        $em->persist($resource);
249
250
        $em->flush();
251
252
        return $resourceNode;
253
    }
254
255
    public function addFile(AbstractResource $resource, UploadedFile $file): ?ResourceFile
256
    {
257
        $resourceNode = $resource->getResourceNode();
258
259
        if (null === $resourceNode) {
260
            throw new \LogicException('Resource node is null');
261
        }
262
263
        $resourceFile = $resourceNode->getResourceFile();
264
        if (null === $resourceFile) {
265
            $resourceFile = new ResourceFile();
266
        }
267
268
        $em = $this->getEntityManager();
269
        //$resourceFile->setMimeType($file->getMimeType());
270
        $resourceFile->setFile($file);
271
        $resourceFile->setName($resource->getResourceName());
272
        $em->persist($resourceFile);
273
274
        $resourceNode->setResourceFile($resourceFile);
275
        $em->persist($resourceNode);
276
277
        return $resourceFile;
278
    }
279
280
    //unction createNodeForResource(AbstractResource $resource, User $creator, ResourceNode $parent = null, UploadedFile $file = null): ResourceNode
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
358
    public function addResourceToMe(ResourceNode $resourceNode): ResourceLink
359
    {
360
        $resourceLink = new ResourceLink();
361
        $resourceLink
362
            ->setResourceNode($resourceNode)
363
            ->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

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

422
        /** @scrutinizer ignore-call */ 
423
        $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...
423
            $resourceNode,
424
            $course,
425
            $right
426
        );
427
        $resourceLink->setSession($session);
428
        $this->getEntityManager()->persist($resourceLink);
429
430
        return $resourceLink;
431
    }
432
433
    /**
434
     * @return ResourceLink
435
     */
436
    public function addResourceToCourseGroup(
437
        ResourceNode $resourceNode,
438
        Course $course,
439
        CGroupInfo $group,
440
        ResourceRight $right
441
    ) {
442
        $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

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

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