Completed
Push — master ( 83f4f4...7038dd )
by Julito
11:28
created

ResourceRepository::setResourceTitle()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
c 0
b 0
f 0
nc 2
nop 2
dl 0
loc 6
rs 10
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
namespace Chamilo\CoreBundle\Repository;
6
7
use APY\DataGridBundle\Grid\Action\RowAction;
8
use APY\DataGridBundle\Grid\Row;
9
use Chamilo\CoreBundle\Component\Resource\Settings;
10
use Chamilo\CoreBundle\Component\Resource\Template;
11
use Chamilo\CoreBundle\Entity\AbstractResource;
12
use Chamilo\CoreBundle\Entity\Course;
13
use Chamilo\CoreBundle\Entity\ResourceFile;
14
use Chamilo\CoreBundle\Entity\ResourceInterface;
15
use Chamilo\CoreBundle\Entity\ResourceLink;
16
use Chamilo\CoreBundle\Entity\ResourceNode;
17
use Chamilo\CoreBundle\Entity\ResourceRight;
18
use Chamilo\CoreBundle\Entity\ResourceType;
19
use Chamilo\CoreBundle\Entity\Session;
20
use Chamilo\CoreBundle\Entity\User;
21
use Chamilo\CoreBundle\Entity\Usergroup;
22
use Chamilo\CoreBundle\Security\Authorization\Voter\ResourceNodeVoter;
23
use Chamilo\CoreBundle\ToolChain;
24
use Chamilo\CourseBundle\Entity\CDocument;
25
use Chamilo\CourseBundle\Entity\CGroupInfo;
26
use Cocur\Slugify\SlugifyInterface;
27
use Doctrine\ORM\EntityManager;
28
use Doctrine\ORM\EntityRepository;
29
use Doctrine\ORM\QueryBuilder;
30
use League\Flysystem\FilesystemInterface;
31
use Symfony\Component\Filesystem\Exception\FileNotFoundException;
32
use Symfony\Component\Form\FormFactory;
33
use Symfony\Component\Form\FormInterface;
34
use Symfony\Component\HttpFoundation\File\UploadedFile;
35
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
36
use Symfony\Component\Routing\RouterInterface;
37
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
38
39
/**
40
 * Class ResourceRepository.
41
 * Extends EntityRepository is needed to process settings.
42
 */
43
class ResourceRepository extends EntityRepository
44
{
45
    /**
46
     * @var EntityRepository
47
     */
48
    protected $repository;
49
50
    /**
51
     * @var FilesystemInterface
52
     */
53
    protected $fs;
54
55
    /**
56
     * @var EntityManager
57
     */
58
    protected $entityManager;
59
60
    /**
61
     * The entity class FQN.
62
     *
63
     * @var string
64
     */
65
    protected $className;
66
67
    /** @var RouterInterface */
68
    protected $router;
69
70
    /** @var ResourceNodeRepository */
71
    protected $resourceNodeRepository;
72
73
    /**
74
     * @var AuthorizationCheckerInterface
75
     */
76
    protected $authorizationChecker;
77
78
    /** @var SlugifyInterface */
79
    protected $slugify;
80
81
    /** @var ToolChain */
82
    protected $toolChain;
83
    protected $settings;
84
    protected $templates;
85
    protected $resourceType;
86
87
    /**
88
     * ResourceRepository constructor.
89
     */
90
    public function __construct(
91
        AuthorizationCheckerInterface $authorizationChecker,
92
        EntityManager $entityManager,
93
        RouterInterface $router,
94
        SlugifyInterface $slugify,
95
        ToolChain $toolChain,
96
        ResourceNodeRepository $resourceNodeRepository,
97
        string $className
98
    ) {
99
        $this->authorizationChecker = $authorizationChecker;
100
        $this->repository = $entityManager->getRepository($className);
101
        $this->router = $router;
102
        $this->resourceNodeRepository = $resourceNodeRepository;
103
        $this->slugify = $slugify;
104
        $this->toolChain = $toolChain;
105
        $this->settings = new Settings();
106
        $this->templates = new Template();
107
    }
108
109
    public function getAuthorizationChecker(): AuthorizationCheckerInterface
110
    {
111
        return $this->authorizationChecker;
112
    }
113
114
    /**
115
     * @return AbstractResource
116
     */
117
    public function create()
118
    {
119
        $class = $this->repository->getClassName();
120
121
        return new $class();
122
    }
123
124
    public function getRouter(): RouterInterface
125
    {
126
        return $this->router;
127
    }
128
129
    /**
130
     * @return ResourceNodeRepository
131
     */
132
    public function getResourceNodeRepository()
133
    {
134
        return $this->resourceNodeRepository;
135
    }
136
137
    public function getEntityManager(): EntityManager
138
    {
139
        return $this->getRepository()->getEntityManager();
140
    }
141
142
    /**
143
     * @return EntityRepository
144
     */
145
    public function getRepository()
146
    {
147
        return $this->repository;
148
    }
149
150
    /**
151
     * @return FormInterface
152
     */
153
    public function getForm(FormFactory $formFactory, AbstractResource $resource = null, $options = [])
154
    {
155
        $formType = $this->getResourceFormType();
156
157
        if (null === $resource) {
158
            $className = $this->repository->getClassName();
159
            $resource = new $className();
160
        }
161
162
        return $formFactory->create($formType, $resource, $options);
163
    }
164
165
    /**
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
     * @return ResourceInterface
170
     */
171
    public function find($id, $lockMode = null, $lockVersion = null)
172
    {
173
        return $this->getRepository()->find($id);
174
    }
175
176
    public function findOneBy(array $criteria, array $orderBy = null)
177
    {
178
        return $this->getRepository()->findOneBy($criteria, $orderBy);
179
    }
180
181
    public function updateNodeForResource(ResourceInterface $resource): ResourceNode
182
    {
183
        $em = $this->getEntityManager();
184
185
        $resourceNode = $resource->getResourceNode();
186
        $resourceName = $resource->getResourceName();
187
188
        if ($resourceNode->hasResourceFile()) {
189
            $resourceFile = $resourceNode->getResourceFile();
190
            if ($resourceFile) {
0 ignored issues
show
introduced by
$resourceFile is of type Chamilo\CoreBundle\Entity\ResourceFile, thus it always evaluated to true.
Loading history...
191
                $originalName = $resourceFile->getOriginalName();
192
                $originalExtension = pathinfo($originalName, PATHINFO_EXTENSION);
193
194
                //$originalBasename = \basename($resourceName, $originalExtension);
195
                /*$slug = sprintf(
196
                    '%s.%s',
197
                    $this->slugify->slugify($originalBasename),
198
                    $this->slugify->slugify($originalExtension)
199
                );*/
200
201
                $newOriginalName = sprintf('%s.%s', $resourceName, $originalExtension);
202
                $resourceFile->setOriginalName($newOriginalName);
203
204
                $em->persist($resourceFile);
205
            }
206
        } else {
207
            //$slug = $this->slugify->slugify($resourceName);
208
        }
209
210
        $resourceNode->setTitle($resourceName);
211
        //$resourceNode->setSlug($slug);
212
213
        $em->persist($resourceNode);
214
        $em->persist($resource);
215
216
        $em->flush();
217
218
        return $resourceNode;
219
    }
220
221
    public function addFile(ResourceInterface $resource, UploadedFile $file): ?ResourceFile
222
    {
223
        $resourceNode = $resource->getResourceNode();
224
225
        if (null === $resourceNode) {
226
            throw new \LogicException('Resource node is null');
227
        }
228
229
        $resourceFile = $resourceNode->getResourceFile();
230
        if (null === $resourceFile) {
231
            $resourceFile = new ResourceFile();
232
        }
233
234
        $em = $this->getEntityManager();
235
        $resourceFile->setFile($file);
236
        $resourceFile->setName($resource->getResourceName());
237
        $em->persist($resourceFile);
238
239
        $resourceNode->setResourceFile($resourceFile);
240
        $em->persist($resourceNode);
241
242
        return $resourceFile;
243
    }
244
245
    public function addResourceNode(AbstractResource $resource, User $creator, AbstractResource $parent = null): ResourceNode
246
    {
247
        if (null !== $parent) {
248
            $parent = $parent->getResourceNode();
249
        }
250
251
        return $this->createNodeForResource($resource, $creator, $parent);
252
    }
253
254
    public function addResourceToCourse(AbstractResource $resource, int $visibility, User $creator, Course $course, Session $session = null, CGroupInfo $group = null, UploadedFile $file = null)
255
    {
256
        $resourceNode = $this->createNodeForResource($resource, $creator, $course->getResourceNode(), $file);
257
258
        $this->addResourceNodeToCourse($resourceNode, $visibility, $course, $session, $group);
259
    }
260
261
    public function addResourceToCourseWithParent(AbstractResource $resource, ResourceNode $parentNode, int $visibility, User $creator, Course $course, Session $session = null, CGroupInfo $group = null, UploadedFile $file = null)
262
    {
263
        $resourceNode = $this->createNodeForResource($resource, $creator, $parentNode, $file);
264
265
        $this->addResourceNodeToCourse($resourceNode, $visibility, $course, $session, $group);
266
    }
267
268
    public function addResourceNodeToCourse(ResourceNode $resourceNode, int $visibility, Course $course, Session $session = null, CGroupInfo $group = null, User $toUser = null): void
269
    {
270
        if (0 === $visibility) {
271
            $visibility = ResourceLink::VISIBILITY_PUBLISHED;
272
        }
273
274
        $link = new ResourceLink();
275
        $link
276
            ->setCourse($course)
277
            ->setSession($session)
278
            ->setGroup($group)
279
            ->setUser($toUser)
280
            ->setResourceNode($resourceNode)
281
            ->setVisibility($visibility)
282
        ;
283
284
        $rights = [];
285
        switch ($visibility) {
286
            case ResourceLink::VISIBILITY_PENDING:
287
            case ResourceLink::VISIBILITY_DRAFT:
288
                $editorMask = ResourceNodeVoter::getEditorMask();
289
                $resourceRight = new ResourceRight();
290
                $resourceRight
291
                    ->setMask($editorMask)
292
                    ->setRole(ResourceNodeVoter::ROLE_CURRENT_COURSE_TEACHER)
293
                ;
294
                $rights[] = $resourceRight;
295
296
                break;
297
        }
298
299
        if (!empty($rights)) {
300
            foreach ($rights as $right) {
301
                $link->addResourceRight($right);
302
            }
303
        }
304
305
        $em = $this->getEntityManager();
306
        $em->persist($resourceNode);
307
        $em->persist($link);
308
    }
309
310
    public function addResourceToMe(ResourceNode $resourceNode): ResourceLink
311
    {
312
        $resourceLink = new ResourceLink();
313
        $resourceLink->setResourceNode($resourceNode);
314
315
        $this->getEntityManager()->persist($resourceLink);
316
        $this->getEntityManager()->flush();
317
318
        return $resourceLink;
319
    }
320
321
    public function addResourceToEveryone(ResourceNode $resourceNode, ResourceRight $right): ResourceLink
322
    {
323
        $resourceLink = new ResourceLink();
324
        $resourceLink
325
            ->setResourceNode($resourceNode)
326
            ->addResourceRight($right)
327
        ;
328
329
        $this->getEntityManager()->persist($resourceLink);
330
        $this->getEntityManager()->flush();
331
332
        return $resourceLink;
333
    }
334
335
    public function addResourceToUser(ResourceNode $resourceNode, User $toUser): ResourceLink
336
    {
337
        $resourceLink = $this->addResourceNodeToUser($resourceNode, $toUser);
338
        $this->getEntityManager()->persist($resourceLink);
339
340
        return $resourceLink;
341
    }
342
343
    public function addResourceNodeToUser(ResourceNode $resourceNode, User $toUser): ResourceLink
344
    {
345
        $resourceLink = new ResourceLink();
346
        $resourceLink
347
            ->setResourceNode($resourceNode)
348
            ->setVisibility(ResourceLink::VISIBILITY_PUBLISHED)
349
            ->setUser($toUser);
350
351
        return $resourceLink;
352
    }
353
354
    public function addResourceToCourseGroup(ResourceNode $resourceNode, CGroupInfo $group)
355
    {
356
        $exists = $resourceNode->getResourceLinks()->exists(
357
            function ($key, $element) use ($group) {
358
                if ($element->getGroup()) {
359
                    return $group->getIid() == $element->getGroup()->getIid();
360
                }
361
            }
362
        );
363
364
        if (false === $exists) {
365
            $resourceLink = new ResourceLink();
366
            $resourceLink
367
                ->setResourceNode($resourceNode)
368
                ->setGroup($group)
369
                ->setVisibility(ResourceLink::VISIBILITY_PUBLISHED)
370
            ;
371
            $this->getEntityManager()->persist($resourceLink);
372
373
            return $resourceLink;
374
        }
375
    }
376
377
    /*public function addResourceToSession(
378
        ResourceNode $resourceNode,
379
        Course $course,
380
        Session $session,
381
        ResourceRight $right
382
    ) {
383
        $resourceLink = $this->addResourceToCourse(
384
            $resourceNode,
385
            $course,
386
            $right
387
        );
388
        $resourceLink->setSession($session);
389
        $this->getEntityManager()->persist($resourceLink);
390
391
        return $resourceLink;
392
    }*/
393
394
    /**
395
     * @return ResourceLink
396
     */
397
    public function addResourceToGroup(
398
        ResourceNode $resourceNode,
399
        Usergroup $group,
400
        ResourceRight $right
401
    ) {
402
        $resourceLink = new ResourceLink();
403
        $resourceLink
404
            ->setResourceNode($resourceNode)
405
            ->setUserGroup($group)
406
            ->addResourceRight($right);
407
408
        return $resourceLink;
409
    }
410
411
    /**
412
     * @param array $userList User id list
413
     */
414
    public function addResourceToUserList(ResourceNode $resourceNode, array $userList)
415
    {
416
        $em = $this->getEntityManager();
417
418
        if (!empty($userList)) {
419
            $userRepo = $em->getRepository('ChamiloCoreBundle:User');
420
            foreach ($userList as $userId) {
421
                $toUser = $userRepo->find($userId);
422
                $resourceLink = $this->addResourceNodeToUser($resourceNode, $toUser);
423
                $em->persist($resourceLink);
424
            }
425
        }
426
    }
427
428
    /**
429
     * @return ResourceType
430
     */
431
    public function getResourceType()
432
    {
433
        $name = $this->getResourceTypeName();
434
        $repo = $this->getEntityManager()->getRepository('ChamiloCoreBundle:ResourceType');
435
        $this->resourceType = $repo->findOneBy(['name' => $name]);
436
437
        return $this->resourceType;
438
    }
439
440
    public function getResourceTypeName(): string
441
    {
442
        return $this->toolChain->getResourceTypeNameFromRepository(get_class($this));
443
    }
444
445
    public function getResourcesByCourse(Course $course, Session $session = null, CGroupInfo $group = null, ResourceNode $parentNode = null): QueryBuilder
446
    {
447
        $repo = $this->getRepository();
448
        $className = $repo->getClassName();
449
        $checker = $this->getAuthorizationChecker();
450
        $reflectionClass = $repo->getClassMetadata()->getReflectionClass();
451
452
        // Check if this resource type requires to load the base course resources when using a session
453
        $loadBaseSessionContent = $reflectionClass->hasProperty('loadCourseResourcesInSession');
454
        $resourceTypeName = $this->getResourceTypeName();
455
456
        $qb = $repo->getEntityManager()->createQueryBuilder()
457
            ->select('resource')
458
            ->from($className, 'resource')
459
            ->innerJoin('resource.resourceNode', 'node')
460
            ->innerJoin('node.resourceLinks', 'links')
461
            ->innerJoin('node.resourceType', 'type')
462
            //->innerJoin('links.course', 'course')
463
            ->leftJoin('node.resourceFile', 'file')
464
465
            ->where('type.name = :type')
466
            ->setParameter('type', $resourceTypeName)
467
            ->andWhere('links.course = :course')
468
            ->setParameter('course', $course)
469
            ->addSelect('node')
470
            ->addSelect('links')
471
            //->addSelect('course')
472
            ->addSelect('type')
473
            ->addSelect('file')
474
        ;
475
476
        $isAdmin = $checker->isGranted('ROLE_ADMIN') ||
477
            $checker->isGranted('ROLE_CURRENT_COURSE_TEACHER');
478
479
        // Do not show deleted resources
480
        $qb
481
            ->andWhere('links.visibility != :visibilityDeleted')
482
            ->setParameter('visibilityDeleted', ResourceLink::VISIBILITY_DELETED)
483
        ;
484
485
        if (false === $isAdmin) {
486
            $qb
487
                ->andWhere('links.visibility = :visibility')
488
                ->setParameter('visibility', ResourceLink::VISIBILITY_PUBLISHED)
489
            ;
490
            // @todo Add start/end visibility restrictions.
491
        }
492
493
        if (null === $session) {
494
            $qb->andWhere(
495
                $qb->expr()->orX(
496
                    $qb->expr()->isNull('links.session'),
497
                    $qb->expr()->eq('links.session', 0)
498
                )
499
            );
500
        } else {
501
            if ($loadBaseSessionContent) {
502
                // Load course base content.
503
                $qb->andWhere('links.session = :session OR links.session IS NULL');
504
                $qb->setParameter('session', $session);
505
            } else {
506
                // Load only session resources.
507
                $qb->andWhere('links.session = :session');
508
                $qb->setParameter('session', $session);
509
            }
510
        }
511
512
        if (null !== $parentNode) {
513
            $qb->andWhere('node.parent = :parentNode');
514
            $qb->setParameter('parentNode', $parentNode);
515
        }
516
517
        if (null === $group) {
518
            $qb->andWhere(
519
                $qb->expr()->orX(
520
                    $qb->expr()->isNull('links.group'),
521
                    $qb->expr()->eq('links.group', 0)
522
                )
523
            );
524
        } else {
525
            $qb->andWhere('links.group = :group');
526
            $qb->setParameter('group', $group);
527
        }
528
529
        return $qb;
530
    }
531
532
    public function getResourcesByCourseOnly(Course $course, ResourceNode $parentNode = null)
533
    {
534
        $repo = $this->getRepository();
535
        $className = $repo->getClassName();
536
        $checker = $this->getAuthorizationChecker();
537
        $resourceTypeName = $this->getResourceTypeName();
538
539
        $qb = $repo->getEntityManager()->createQueryBuilder()
540
            ->select('resource')
541
            ->from($className, 'resource')
542
            ->innerJoin(
543
                'resource.resourceNode',
544
                'node'
545
            )
546
            ->innerJoin('node.resourceLinks', 'links')
547
            ->innerJoin('node.resourceType', 'type')
548
            ->where('type.name = :type')
549
            ->setParameter('type', $resourceTypeName)
550
            ->andWhere('links.course = :course')
551
            ->setParameter('course', $course)
552
        ;
553
554
        $isAdmin = $checker->isGranted('ROLE_ADMIN') ||
555
            $checker->isGranted('ROLE_CURRENT_COURSE_TEACHER');
556
557
        // Do not show deleted resources
558
        $qb
559
            ->andWhere('links.visibility != :visibilityDeleted')
560
            ->setParameter('visibilityDeleted', ResourceLink::VISIBILITY_DELETED)
561
        ;
562
563
        if (false === $isAdmin) {
564
            $qb
565
                ->andWhere('links.visibility = :visibility')
566
                ->setParameter('visibility', ResourceLink::VISIBILITY_PUBLISHED)
567
            ;
568
            // @todo Add start/end visibility restrictrions
569
        }
570
571
        if (null !== $parentNode) {
572
            $qb->andWhere('node.parent = :parentNode');
573
            $qb->setParameter('parentNode', $parentNode);
574
        }
575
576
        return $qb;
577
    }
578
579
    /**
580
     * @return QueryBuilder
581
     */
582
    public function getResourcesByCreator(User $user, ResourceNode $parentNode = null)
583
    {
584
        $repo = $this->getRepository();
585
        $className = $repo->getClassName();
586
587
        $qb = $repo->getEntityManager()->createQueryBuilder()
588
            ->select('resource')
589
            ->from($className, 'resource')
590
            ->innerJoin(
591
                'resource.resourceNode',
592
                'node'
593
            )
594
            //->innerJoin('node.resourceLinks', 'links')
595
            //->where('node.resourceType = :type')
596
            //->setParameter('type',$type)
597
            ;
598
        /*$qb
599
            ->andWhere('links.visibility = :visibility')
600
            ->setParameter('visibility', ResourceLink::VISIBILITY_PUBLISHED)
601
        ;*/
602
603
        if (null !== $parentNode) {
604
            $qb->andWhere('node.parent = :parentNode');
605
            $qb->setParameter('parentNode', $parentNode);
606
        }
607
608
        $qb->andWhere('node.creator = :creator');
609
        $qb->setParameter('creator', $user);
610
611
        return $qb;
612
    }
613
614
    public function getResourcesByCourseLinkedToUser(User $user, Course $course, Session $session = null, CGroupInfo $group = null, ResourceNode $parentNode = null): QueryBuilder
615
    {
616
        $qb = $this->getResourcesByCourse($course, $session, $group, $parentNode);
617
618
        $qb
619
            ->andWhere('links.user = :user')
620
            ->setParameter('user', $user);
621
622
        return $qb;
623
    }
624
625
    public function getResourcesByLinkedUser(User $user, ResourceNode $parentNode = null): QueryBuilder
626
    {
627
        $repo = $this->getRepository();
628
        $className = $repo->getClassName();
629
        $checker = $this->getAuthorizationChecker();
630
        $resourceTypeName = $this->getResourceTypeName();
631
632
        $qb = $repo->getEntityManager()->createQueryBuilder()
633
            ->select('resource')
634
            ->from($className, 'resource')
635
            ->innerJoin(
636
                'resource.resourceNode',
637
                'node'
638
            )
639
            ->innerJoin('node.resourceLinks', 'links')
640
            ->innerJoin('node.resourceType', 'type')
641
            ->where('type.name = :type')
642
            ->setParameter('type', $resourceTypeName)
643
            ->andWhere('links.user = :user')
644
            ->setParameter('user', $user)
645
        ;
646
647
        $isAdmin = $checker->isGranted('ROLE_ADMIN') ||
648
            $checker->isGranted('ROLE_CURRENT_COURSE_TEACHER');
649
650
        // Do not show deleted resources
651
        $qb
652
            ->andWhere('links.visibility != :visibilityDeleted')
653
            ->setParameter('visibilityDeleted', ResourceLink::VISIBILITY_DELETED)
654
        ;
655
656
        if (false === $isAdmin) {
657
            $qb
658
                ->andWhere('links.visibility = :visibility')
659
                ->setParameter('visibility', ResourceLink::VISIBILITY_PUBLISHED)
660
            ;
661
            // @todo Add start/end visibility restrictrions
662
        }
663
664
        if (null !== $parentNode) {
665
            $qb->andWhere('node.parent = :parentNode');
666
            $qb->setParameter('parentNode', $parentNode);
667
        }
668
669
        return $qb;
670
    }
671
672
    public function getResourceFromResourceNode(int $resourceNodeId): ?AbstractResource
673
    {
674
        //return $this->getRepository()->findOneBy(['resourceNode' => $resourceNodeId]);
675
        //$className = $this->getClassName();
676
        /*var_dump(get_class($this->repository));
677
        var_dump(get_class($this->getRepository()));
678
        var_dump(get_class($this));*/
679
        //var_dump($className);
680
        // Include links
681
        $qb = $this->getRepository()->createQueryBuilder('resource')
682
            ->select('resource')
683
            ->addSelect('node')
684
            ->addSelect('links')
685
            //->addSelect('file')
686
            //->from($className, 'resource')
687
            ->innerJoin('resource.resourceNode', 'node')
688
        //    ->innerJoin('node.creator', 'userCreator')
689
            ->innerJoin('node.resourceLinks', 'links')
690
//            ->leftJoin('node.resourceFile', 'file')
691
            ->where('node.id = :id')
692
            ->setParameters(['id' => $resourceNodeId])
693
            //->addSelect('node')
694
        ;
695
696
        return $qb->getQuery()->getOneOrNullResult();
697
    }
698
699
    public function rowCanBeEdited(RowAction $action, Row $row, Session $session = null): ?RowAction
700
    {
701
        if (null !== $session) {
702
            /** @var AbstractResource $entity */
703
            $entity = $row->getEntity();
704
            $hasSession = $entity->getResourceNode()->hasSession($session);
705
            if ($hasSession->count() > 0) {
706
                return $action;
707
            }
708
709
            return null;
710
        }
711
712
        return $action;
713
    }
714
715
    public function delete(AbstractResource $resource)
716
    {
717
        $children = $resource->getResourceNode()->getChildren();
718
        foreach ($children as $child) {
719
            if ($child->hasResourceFile()) {
720
                $this->getEntityManager()->remove($child->getResourceFile());
721
            }
722
            $resourceNode = $this->getResourceFromResourceNode($child->getId());
723
            if ($resourceNode) {
724
                $this->delete($resourceNode);
725
            }
726
        }
727
        $this->getEntityManager()->remove($resource);
728
        $this->getEntityManager()->flush();
729
    }
730
731
    /**
732
     * Deletes several entities: AbstractResource (Ex: CDocument, CQuiz), ResourceNode,
733
     * ResourceLinks and ResourceFile (including files via Flysystem).
734
     */
735
    public function hardDelete(AbstractResource $resource)
736
    {
737
        $em = $this->getEntityManager();
738
        $em->remove($resource);
739
        $em->flush();
740
    }
741
742
    public function getResourceFileContent(AbstractResource $resource): string
743
    {
744
        try {
745
            $resourceNode = $resource->getResourceNode();
746
747
            return $this->resourceNodeRepository->getResourceNodeFileContent($resourceNode);
748
        } catch (\Throwable $exception) {
749
            throw new FileNotFoundException($resource);
750
        }
751
    }
752
753
    public function getResourceNodeFileContent(ResourceNode $resourceNode): string
754
    {
755
        return $this->resourceNodeRepository->getResourceNodeFileContent($resourceNode);
756
    }
757
758
    public function getResourceNodeFileStream(ResourceNode $resourceNode)
759
    {
760
        return $this->resourceNodeRepository->getResourceNodeFileStream($resourceNode);
761
    }
762
763
    public function getResourceFileDownloadUrl(AbstractResource $resource, array $extraParams = [], $referenceType = null): string
764
    {
765
        $extraParams['mode'] = 'download';
766
767
        return $this->getResourceFileUrl($resource, $extraParams, $referenceType);
768
    }
769
770
    public function getResourceFileUrl(AbstractResource $resource, array $extraParams = [], $referenceType = null): string
771
    {
772
        try {
773
            $resourceNode = $resource->getResourceNode();
774
            if ($resourceNode->hasResourceFile()) {
775
                $params = [
776
                    'tool' => $resourceNode->getResourceType()->getTool(),
777
                    'type' => $resourceNode->getResourceType(),
778
                    'id' => $resourceNode->getId(),
779
                ];
780
781
                if (!empty($extraParams)) {
782
                    $params = array_merge($params, $extraParams);
783
                }
784
785
                $referenceType = $referenceType ?? UrlGeneratorInterface::ABSOLUTE_PATH;
786
787
                return $this->router->generate('chamilo_core_resource_view_file', $params, $referenceType);
788
            }
789
790
            return '';
791
        } catch (\Throwable $exception) {
792
            throw new FileNotFoundException($resource);
793
        }
794
    }
795
796
    public function getResourceSettings(): Settings
797
    {
798
        return $this->settings;
799
    }
800
801
    public function getTemplates(): Template
802
    {
803
        return $this->templates;
804
    }
805
806
    /**
807
     * @param string $content
808
     *
809
     * @return bool
810
     */
811
    public function updateResourceFileContent(AbstractResource $resource, $content)
812
    {
813
        $resourceNode = $resource->getResourceNode();
814
        if ($resourceNode->hasResourceFile()) {
815
            $resourceFile = $resourceNode->getResourceFile();
816
            if ($resourceFile) {
0 ignored issues
show
introduced by
$resourceFile is of type Chamilo\CoreBundle\Entity\ResourceFile, thus it always evaluated to true.
Loading history...
817
                $title = $resource->getTitle();
0 ignored issues
show
Bug introduced by
The method getTitle() does not exist on Chamilo\CoreBundle\Entity\AbstractResource. It seems like you code against a sub-type of Chamilo\CoreBundle\Entity\AbstractResource such as Chamilo\CoreBundle\Entity\Course or Chamilo\CourseBundle\Entity\CLink or Chamilo\CourseBundle\Entity\CAnnouncement or Chamilo\CourseBundle\Entity\CThematicPlan or Chamilo\CourseBundle\Entity\CQuiz or Chamilo\CourseBundle\Entity\CCourseDescription or Chamilo\CourseBundle\Entity\CDocument or Chamilo\CourseBundle\Entity\CThematic or Chamilo\CourseBundle\Entity\CQuizQuestionCategory or Chamilo\CourseBundle\Entity\CStudentPublication or Chamilo\CourseBundle\Entity\CCalendarEvent. ( Ignorable by Annotation )

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

817
                /** @scrutinizer ignore-call */ 
818
                $title = $resource->getTitle();
Loading history...
818
                $handle = tmpfile();
819
                fwrite($handle, $content);
820
                $meta = stream_get_meta_data($handle);
821
                $file = new UploadedFile($meta['uri'], $title, 'text/html', null, true);
822
                $resource->setUploadFile($file);
823
824
                /*$fileName = $this->getResourceNodeRepository()->getFilename($resourceFile);
825
                $this->getResourceNodeRepository()->getFileSystem()->update($fileName, $content);
826
                $resourceFile->setSize(strlen($content));*/
827
                //$this->entityManager->persist($resource);
828
829
                return true;
830
            }
831
        }
832
833
        return false;
834
    }
835
836
    /**
837
     * Change all links visibility to DELETED.
838
     */
839
    public function softDelete(AbstractResource $resource)
840
    {
841
        $this->setLinkVisibility($resource, ResourceLink::VISIBILITY_DELETED);
842
    }
843
844
    public function setVisibilityPublished(AbstractResource $resource)
845
    {
846
        $this->setLinkVisibility($resource, ResourceLink::VISIBILITY_PUBLISHED);
847
    }
848
849
    public function setVisibilityDraft(AbstractResource $resource)
850
    {
851
        $this->setLinkVisibility($resource, ResourceLink::VISIBILITY_DRAFT);
852
    }
853
854
    public function setVisibilityPending(AbstractResource $resource)
855
    {
856
        $this->setLinkVisibility($resource, ResourceLink::VISIBILITY_PENDING);
857
    }
858
859
    public function setResourceTitle(AbstractResource $resource, $title)
860
    {
861
        $resource->setTitle($title);
0 ignored issues
show
Bug introduced by
The method setTitle() does not exist on Chamilo\CoreBundle\Entity\AbstractResource. It seems like you code against a sub-type of Chamilo\CoreBundle\Entity\AbstractResource such as Chamilo\CoreBundle\Entity\Course or Chamilo\CourseBundle\Entity\CLink or Chamilo\CourseBundle\Entity\CAnnouncement or Chamilo\CourseBundle\Entity\CThematicPlan or Chamilo\CourseBundle\Entity\CQuiz or Chamilo\CourseBundle\Entity\CCourseDescription or Chamilo\CourseBundle\Entity\CDocument or Chamilo\CourseBundle\Entity\CThematic or Chamilo\CourseBundle\Entity\CQuizQuestionCategory or Chamilo\CourseBundle\Entity\CStudentPublication or Chamilo\CourseBundle\Entity\CCalendarEvent. ( Ignorable by Annotation )

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

861
        $resource->/** @scrutinizer ignore-call */ 
862
                   setTitle($title);
Loading history...
862
        $resourceNode = $resource->getResourceNode();
863
        $resourceNode->setTitle($title);
864
        if ($resourceNode->hasResourceFile()) {
865
            //$resourceFile = $resourceNode->getResourceFile();
866
            //$resourceFile->setName($title);
867
868
            /*$fileName = $this->getResourceNodeRepository()->getFilename($resourceFile);
869
            error_log('$fileName');
870
            error_log($fileName);
871
            error_log($title);
872
            $this->getResourceNodeRepository()->getFileSystem()->rename($fileName, $title);
873
            $resourceFile->setName($title);
874
            $resourceFile->setOriginalName($title);*/
875
        }
876
    }
877
878
    public function createNodeForResource(ResourceInterface $resource, User $creator, ResourceNode $parentNode = null, UploadedFile $file = null): ResourceNode
879
    {
880
        $em = $this->getEntityManager();
881
882
        $resourceType = $this->getResourceType();
883
        $resourceName = $resource->getResourceName();
884
        $extension = $this->slugify->slugify(pathinfo($resourceName, PATHINFO_EXTENSION));
885
886
        if (empty($extension)) {
887
            $slug = $this->slugify->slugify($resourceName);
888
        } else {
889
            $originalExtension = pathinfo($resourceName, PATHINFO_EXTENSION);
890
            $originalBasename = \basename($resourceName, $originalExtension);
891
            $slug = sprintf('%s.%s', $this->slugify->slugify($originalBasename), $originalExtension);
892
        }
893
894
        $resourceNode = new ResourceNode();
895
        $resourceNode
896
            ->setTitle($resourceName)
897
            ->setSlug($slug)
898
            ->setCreator($creator)
899
            ->setResourceType($resourceType)
900
        ;
901
902
        if (null !== $parentNode) {
903
            $resourceNode->setParent($parentNode);
904
        }
905
906
        $resource->setResourceNode($resourceNode);
907
        $em->persist($resourceNode);
908
        $em->persist($resource);
909
910
        if (null !== $file) {
911
            $this->addFile($resource, $file);
912
        }
913
914
        return $resourceNode;
915
    }
916
917
    private function setLinkVisibility(AbstractResource $resource, int $visibility, bool $recursive = true): bool
918
    {
919
        $resourceNode = $resource->getResourceNode();
920
921
        if (null === $resourceNode) {
922
            return false;
923
        }
924
925
        $em = $this->getEntityManager();
926
        if ($recursive) {
927
            $children = $resourceNode->getChildren();
928
            if (!empty($children)) {
929
                /** @var ResourceNode $child */
930
                foreach ($children as $child) {
931
                    $criteria = ['resourceNode' => $child];
932
                    $childDocument = $this->getRepository()->findOneBy($criteria);
933
                    if ($childDocument) {
934
                        $this->setLinkVisibility($childDocument, $visibility);
935
                    }
936
                }
937
            }
938
        }
939
940
        $links = $resourceNode->getResourceLinks();
941
942
        if (!empty($links)) {
943
            /** @var ResourceLink $link */
944
            foreach ($links as $link) {
945
                $link->setVisibility($visibility);
946
                if (ResourceLink::VISIBILITY_DRAFT === $visibility) {
947
                    $editorMask = ResourceNodeVoter::getEditorMask();
948
                    $rights = [];
949
                    $resourceRight = new ResourceRight();
950
                    $resourceRight
951
                        ->setMask($editorMask)
952
                        ->setRole(ResourceNodeVoter::ROLE_CURRENT_COURSE_TEACHER)
953
                        ->setResourceLink($link)
954
                    ;
955
                    $rights[] = $resourceRight;
956
957
                    if (!empty($rights)) {
958
                        $link->setResourceRight($rights);
959
                    }
960
                } else {
961
                    $link->setResourceRight([]);
962
                }
963
                $em->persist($link);
964
            }
965
        }
966
        $em->flush();
967
968
        return true;
969
    }
970
}
971