Completed
Push — master ( fc1588...7621d0 )
by Julito
16:55
created

ResourceRepository::getResourcesByCreator()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 38
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 19
nc 2
nop 2
dl 0
loc 38
rs 9.6333
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\Entity\Course;
9
use Chamilo\CoreBundle\Entity\Resource\AbstractResource;
10
use Chamilo\CoreBundle\Entity\Resource\ResourceFile;
11
use Chamilo\CoreBundle\Entity\Resource\ResourceLink;
12
use Chamilo\CoreBundle\Entity\Resource\ResourceNode;
13
use Chamilo\CoreBundle\Entity\Resource\ResourceRight;
14
use Chamilo\CoreBundle\Entity\Resource\ResourceType;
15
use Chamilo\CoreBundle\Entity\Session;
16
use Chamilo\CoreBundle\Entity\Tool;
17
use Chamilo\CoreBundle\Entity\Usergroup;
18
use Chamilo\CoreBundle\Security\Authorization\Voter\ResourceNodeVoter;
19
use Chamilo\CourseBundle\Entity\CGroupInfo;
20
use Chamilo\UserBundle\Entity\User;
21
use Cocur\Slugify\SlugifyInterface;
22
use Doctrine\ORM\EntityManager;
23
use Doctrine\ORM\Query\Expr\Join;
24
use Doctrine\ORM\QueryBuilder;
25
use League\Flysystem\FilesystemInterface;
26
use League\Flysystem\MountManager;
27
use Sylius\Bundle\ResourceBundle\Doctrine\ORM\EntityRepository;
28
use Symfony\Component\Filesystem\Exception\FileNotFoundException;
29
use Symfony\Component\Form\FormFactory;
30
use Symfony\Component\Form\FormInterface;
31
use Symfony\Component\HttpFoundation\File\UploadedFile;
32
use Symfony\Component\Routing\RouterInterface;
33
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
34
35
/**
36
 * Class ResourceRepository.
37
 * Extends EntityRepository is needed to process settings.
38
 */
39
class ResourceRepository extends EntityRepository
40
{
41
    /**
42
     * @var EntityRepository
43
     */
44
    protected $repository;
45
46
    /**
47
     * @var FilesystemInterface
48
     */
49
    protected $fs;
50
51
    /**
52
     * @var EntityManager
53
     */
54
    protected $entityManager;
55
56
    /**
57
     * The entity class FQN.
58
     *
59
     * @var string
60
     */
61
    protected $className;
62
63
    /** @var RouterInterface */
64
    protected $router;
65
66
    protected $resourceNodeRepository;
67
68
    /**
69
     * @var AuthorizationCheckerInterface
70
     */
71
    protected $authorizationChecker;
72
73
    /** @var MountManager */
74
    protected $mountManager;
75
76
    /** @var SlugifyInterface */
77
    protected $slugify;
78
79
    /**
80
     * ResourceRepository constructor.
81
     */
82
    public function __construct(
83
        AuthorizationCheckerInterface $authorizationChecker,
84
        EntityManager $entityManager,
85
        MountManager $mountManager,
86
        RouterInterface $router,
87
        SlugifyInterface $slugify,
88
        string $className
89
    ) {
90
        $this->authorizationChecker = $authorizationChecker;
91
        $this->repository = $entityManager->getRepository($className);
92
        // Flysystem mount name is saved in config/packages/oneup_flysystem.yaml @todo add it as a service.
93
        $this->fs = $mountManager->getFilesystem('resources_fs');
94
        $this->mountManager = $mountManager;
95
        $this->router = $router;
96
        $this->resourceNodeRepository = $entityManager->getRepository('ChamiloCoreBundle:Resource\ResourceNode');
97
        $this->slugify = $slugify;
98
    }
99
100
    public function getAuthorizationChecker(): AuthorizationCheckerInterface
101
    {
102
        return $this->authorizationChecker;
103
    }
104
105
    /**
106
     * @return mixed
107
     */
108
    public function create()
109
    {
110
        return new $this->className();
111
    }
112
113
    public function getRouter(): RouterInterface
114
    {
115
        return $this->router;
116
    }
117
118
    /**
119
     * @return ResourceNodeRepository
120
     */
121
    public function getResourceNodeRepository()
122
    {
123
        return $this->resourceNodeRepository;
124
    }
125
126
    /**
127
     * @return FilesystemInterface
128
     */
129
    public function getFileSystem()
130
    {
131
        return $this->fs;
132
    }
133
134
    public function getEntityManager(): EntityManager
135
    {
136
        return $this->getRepository()->getEntityManager();
137
    }
138
139
    /**
140
     * @return EntityRepository
141
     */
142
    public function getRepository()
143
    {
144
        return $this->repository;
145
    }
146
147
    /**
148
     * @return FormInterface
149
     */
150
    public function getForm(FormFactory $formFactory, AbstractResource $resource = null, $options = [])
151
    {
152
        $className = $this->repository->getClassName();
153
        $shortName = (new \ReflectionClass($className))->getShortName();
154
155
        // @todo remove hardcode class loading
156
        $formType = 'Chamilo\CoreBundle\Form\Resource\\'.$shortName.'Type';
157
        if ($resource === null) {
158
            $resource = new $className();
159
        }
160
161
        return $formFactory->create($formType, $resource, $options);
162
    }
163
164
    /**
165
     * @param mixed $id
166
     * @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...
167
     * @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...
168
     */
169
    public function find($id, $lockMode = null, $lockVersion = null) //: ?AbstractResource
170
    {
171
        return $this->getRepository()->find($id);
172
    }
173
174
    public function findOneBy(array $criteria, array $orderBy = null): ?AbstractResource
175
    {
176
        return $this->getRepository()->findOneBy($criteria, $orderBy);
177
    }
178
179
    public function createNodeForResource(AbstractResource $resource, User $creator, ResourceNode $parent = null, UploadedFile $file = null): ResourceNode
180
    {
181
        $em = $this->getEntityManager();
182
183
        $resourceType = $this->getResourceType();
184
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
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
    //unction createNodeForResource(AbstractResource $resource, User $creator, ResourceNode $parent = null, UploadedFile $file = null): ResourceNode
280
    public function addResourceNode(AbstractResource $resource, User $creator, AbstractResource $parent = null): ResourceNode
281
    {
282
        if (null !== $parent) {
283
            $parent = $parent->getResourceNode();
284
        }
285
286
        return $this->createNodeForResource($resource, $creator, $parent);
287
    }
288
289
    public function addResourceToCourse(AbstractResource $resource, int $visibility, User $creator, Course $course, Session $session = null, CGroupInfo $group = null)
290
    {
291
        $node = $this->createNodeForResource($resource, $creator, $course->getResourceNode());
292
293
        $this->addResourceNodeToCourse($node, $visibility, $course, $session, $group);
294
    }
295
296
    /**
297
     * @param int        $visibility
298
     * @param Course     $course
299
     * @param Session    $session
300
     * @param CGroupInfo $group
301
     */
302
    public function addResourceNodeToCourse(ResourceNode $resourceNode, $visibility, $course, $session, $group): void
303
    {
304
        $visibility = (int) $visibility;
305
        if (empty($visibility)) {
306
            $visibility = ResourceLink::VISIBILITY_PUBLISHED;
307
        }
308
309
        $link = new ResourceLink();
310
        $link
311
            ->setCourse($course)
312
            ->setSession($session)
313
            ->setGroup($group)
314
            //->setUser($toUser)
315
            ->setResourceNode($resourceNode)
316
            ->setVisibility($visibility)
317
        ;
318
319
        $rights = [];
320
        switch ($visibility) {
321
            case ResourceLink::VISIBILITY_PENDING:
322
            case ResourceLink::VISIBILITY_DRAFT:
323
                $editorMask = ResourceNodeVoter::getEditorMask();
324
                $resourceRight = new ResourceRight();
325
                $resourceRight
326
                    ->setMask($editorMask)
327
                    ->setRole(ResourceNodeVoter::ROLE_CURRENT_COURSE_TEACHER)
328
                ;
329
                $rights[] = $resourceRight;
330
                break;
331
        }
332
333
        if (!empty($rights)) {
334
            foreach ($rights as $right) {
335
                $link->addResourceRight($right);
336
            }
337
        }
338
339
        $em = $this->getEntityManager();
340
        $em->persist($link);
341
    }
342
343
    /**
344
     * @return ResourceType
345
     */
346
    public function getResourceType()
347
    {
348
        $em = $this->getEntityManager();
349
        $entityName = $this->getRepository()->getClassName();
350
351
        return $em->getRepository('ChamiloCoreBundle:Resource\ResourceType')->findOneBy(
352
            ['entityName' => $entityName]
353
        );
354
    }
355
356
    public function addResourceToMe(ResourceNode $resourceNode): ResourceLink
357
    {
358
        $resourceLink = new ResourceLink();
359
        $resourceLink
360
            ->setResourceNode($resourceNode)
361
            ->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

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

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

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

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