Passed
Push — master ( 552ed8...6b0ca3 )
by Julito
12:25
created

ResourceController   F

Complexity

Total Complexity 86

Size/Duplication

Total Lines 1255
Duplicated Lines 0 %

Importance

Changes 8
Bugs 0 Features 1
Metric Value
eloc 601
c 8
b 0
f 1
dl 0
loc 1255
rs 1.999
wmc 86

20 Methods

Rating   Name   Duplication   Size   Complexity  
A previewAction() 0 36 3
A newAction() 0 5 1
B editAction() 0 77 7
A diskSpaceAction() 0 23 1
A newFolderAction() 0 5 1
A infoAction() 0 39 3
A changeVisibilityAction() 0 40 5
D getGrid() 0 313 15
A indexAction() 0 30 1
A listAction() 0 23 1
A deleteAction() 0 37 4
A deleteMassAction() 0 31 3
A uploadAction() 0 21 1
A getDocumentAction() 0 2 1
B showFile() 0 66 9
A viewAction() 0 23 3
B downloadAction() 0 83 6
B setBreadCrumb() 0 72 8
A getParentResourceNode() 0 25 5
B createResource() 0 152 8

How to fix   Complexity   

Complex Class

Complex classes like ResourceController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ResourceController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
namespace Chamilo\CoreBundle\Controller;
6
7
use APY\DataGridBundle\Grid\Action\MassAction;
8
use APY\DataGridBundle\Grid\Action\RowAction;
9
use APY\DataGridBundle\Grid\Column\Column;
10
use APY\DataGridBundle\Grid\Export\CSVExport;
11
use APY\DataGridBundle\Grid\Export\ExcelExport;
12
use APY\DataGridBundle\Grid\Grid;
13
use APY\DataGridBundle\Grid\Row;
14
use APY\DataGridBundle\Grid\Source\Entity;
15
use Chamilo\CoreBundle\Entity\Resource\AbstractResource;
16
use Chamilo\CoreBundle\Entity\Resource\ResourceInterface;
17
use Chamilo\CoreBundle\Entity\Resource\ResourceLink;
18
use Chamilo\CoreBundle\Entity\Resource\ResourceNode;
19
use Chamilo\CoreBundle\Repository\IllustrationRepository;
20
use Chamilo\CoreBundle\Repository\ResourceRepository;
21
use Chamilo\CoreBundle\Repository\ResourceWithLinkInterface;
22
use Chamilo\CoreBundle\Security\Authorization\Voter\ResourceNodeVoter;
23
use Chamilo\CourseBundle\Controller\CourseControllerInterface;
24
use Chamilo\CourseBundle\Controller\CourseControllerTrait;
25
use Chamilo\CourseBundle\Entity\CDocument;
26
use Chamilo\UserBundle\Entity\User;
27
use Doctrine\Common\Collections\ArrayCollection;
28
use Doctrine\Common\Collections\Criteria;
29
use Doctrine\ORM\QueryBuilder;
30
use FOS\CKEditorBundle\Form\Type\CKEditorType;
31
use Symfony\Component\Filesystem\Exception\FileNotFoundException;
32
use Symfony\Component\HttpFoundation\File\UploadedFile;
33
use Symfony\Component\HttpFoundation\JsonResponse;
34
use Symfony\Component\HttpFoundation\RedirectResponse;
35
use Symfony\Component\HttpFoundation\Request;
36
use Symfony\Component\HttpFoundation\Response;
37
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
38
use Symfony\Component\HttpFoundation\StreamedResponse;
39
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
40
use Symfony\Component\Routing\Annotation\Route;
41
use Symfony\Component\Routing\Router;
42
use Symfony\Component\Routing\RouterInterface;
43
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
44
use ZipStream\Option\Archive;
45
use ZipStream\ZipStream;
46
47
/**
48
 * Class ResourceController.
49
 *
50
 * @todo improve/refactor $this->denyAccessUnlessGranted
51
 * @Route("/resources")
52
 *
53
 * @author Julio Montoya <[email protected]>.
54
 */
55
class ResourceController extends AbstractResourceController implements CourseControllerInterface
56
{
57
    use CourseControllerTrait;
58
59
    /**
60
     * @Route("/{tool}/{type}", name="chamilo_core_resource_index")
61
     *
62
     * Example: /document/files (See the 'tool' and the 'resource_type' DB tables.)
63
     * For the tool value check the Tool entity.
64
     * For the type value check the ResourceType entity.
65
     */
66
    public function indexAction(Request $request, Grid $grid): Response
67
    {
68
        $tool = $request->get('tool');
69
        $type = $request->get('type');
70
71
        $parentResourceNode = $this->getParentResourceNode($request);
72
        $repository = $this->getRepositoryFromRequest($request);
73
        $settings = $repository->getResourceSettings();
74
75
        $grid = $this->getGrid($request, $repository, $grid, $parentResourceNode->getId());
76
77
        $breadcrumb = $this->getBreadCrumb();
78
        $breadcrumb->addChild(
79
            $this->trans($tool),
80
            [
81
                'uri' => '#',
82
            ]
83
        );
84
85
        // The base resource node is the course.
86
        $id = $parentResourceNode->getId();
87
88
        return $grid->getGridResponse(
89
            '@ChamiloTheme/Resource/index.html.twig',
90
            [
91
                'tool' => $tool,
92
                'type' => $type,
93
                'id' => $id,
94
                'parent_resource_node' => $parentResourceNode,
95
                'resource_settings' => $settings,
96
            ]
97
        );
98
    }
99
100
    /**
101
     * @Route("/{tool}/{type}/{id}/list", name="chamilo_core_resource_list")
102
     *
103
     * If node has children show it
104
     */
105
    public function listAction(Request $request, Grid $grid): Response
106
    {
107
        $tool = $request->get('tool');
108
        $type = $request->get('type');
109
        $resourceNodeId = $request->get('id');
110
111
        $repository = $this->getRepositoryFromRequest($request);
112
        $settings = $repository->getResourceSettings();
113
114
        $grid = $this->getGrid($request, $repository, $grid, $resourceNodeId);
115
116
        $this->setBreadCrumb($request);
117
        $parentResourceNode = $this->getParentResourceNode($request);
118
119
        return $grid->getGridResponse(
120
            '@ChamiloTheme/Resource/index.html.twig',
121
            [
122
                'parent_id' => $resourceNodeId,
123
                'tool' => $tool,
124
                'type' => $type,
125
                'id' => $resourceNodeId,
126
                'parent_resource_node' => $parentResourceNode,
127
                'resource_settings' => $settings,
128
            ]
129
        );
130
    }
131
132
    public function getGrid(Request $request, ResourceRepository $repository, Grid $grid, int $resourceNodeId): Grid
133
    {
134
        $class = $repository->getRepository()->getClassName();
135
136
        // The group 'resource' is set in the @GRID\Source annotation in the entity.
137
        $source = new Entity($class, 'resource');
138
        /** @var ResourceNode $parentNode */
139
        $parentNode = $repository->getResourceNodeRepository()->find($resourceNodeId);
140
141
        $this->denyAccessUnlessGranted(
142
            ResourceNodeVoter::VIEW,
143
            $parentNode,
144
            $this->trans('Unauthorised access to resource')
145
        );
146
147
        $settings = $repository->getResourceSettings();
148
149
        $course = $this->getCourse();
150
        $session = $this->getSession();
151
        /** @var QueryBuilder $qb */
152
        $qb = $repository->getResources($this->getUser(), $parentNode, $course, $session, null);
153
154
        // 3. Set QueryBuilder to the source.
155
        $source->initQueryBuilder($qb);
156
        $grid->setSource($source);
157
158
        $resourceParams = $this->getResourceParams($request);
159
160
        $grid->setRouteUrl($this->generateUrl('chamilo_core_resource_list', $resourceParams));
161
162
        //$grid->hideFilters();
163
        //$grid->setLimits(20);
164
        //$grid->isReadyForRedirect();
165
        //$grid->setMaxResults(1);
166
        //$grid->setLimits(2);
167
        //$grid->setColumns($columns);
168
        $routeParams = $resourceParams;
169
        $routeParams['id'] = null;
170
171
        /** @var Column $titleColumn */
172
        $titleColumn = $repository->getTitleColumn($grid);
173
        $titleColumn->setSafe(false); // allows links in the title
174
175
        // Title link.
176
        $titleColumn->setTitle($this->trans('Name'));
177
178
        //$repository->formatGrid();
179
        /*if ($grid->hasColumn('filetype')) {
180
            $grid->getColumn('filetype')->setTitle($this->trans('Type'));
181
        }*/
182
183
        $titleColumn->manipulateRenderCell(
184
            function ($value, Row $row, $router) use ($routeParams) {
185
                /** @var Router $router */
186
                /** @var ResourceInterface $entity */
187
                $entity = $row->getEntity();
188
                $resourceNode = $entity->getResourceNode();
189
                $id = $resourceNode->getId();
190
191
                $myParams = $routeParams;
192
                $myParams['id'] = $id;
193
                unset($myParams[0]);
194
195
                $icon = $resourceNode->getIcon().' &nbsp;';
196
                if ($resourceNode->hasResourceFile()) {
197
                    if ($resourceNode->isResourceFileAnImage()) {
198
                        $url = $router->generate(
199
                            'chamilo_core_resource_view',
200
                            $myParams
201
                        );
202
203
                        return $icon.'<a data-fancybox="gallery" href="'.$url.'">'.$value.'</a>';
204
                    }
205
206
                    if ($resourceNode->isResourceFileAVideo()) {
207
                        $url = $router->generate(
208
                            'chamilo_core_resource_view',
209
                            $myParams
210
                        );
211
212
                        return '
213
                        <video width="640" height="320" controls id="video'.$id.'" controls preload="metadata" style="display:none;">
214
                            <source src="'.$url.'" type="video/mp4">
215
                            Your browser doesn\'t support HTML5 video tag.
216
                        </video>
217
                        '.$icon.' <a data-fancybox="gallery"  data-width="640" data-height="360" href="#video'.$id.'">'.$value.'</a>';
218
                    }
219
220
                    $url = $router->generate(
221
                        'chamilo_core_resource_preview',
222
                        $myParams
223
                    );
224
225
                    return $icon.'<a data-fancybox="gallery" data-type="iframe" data-src="'.$url.'" href="javascript:;" >'.$value.'</a>';
226
                } else {
227
                    $url = $router->generate(
228
                        'chamilo_core_resource_list',
229
                        $myParams
230
                    );
231
232
                    return $icon.'<a href="'.$url.'">'.$value.'</a>';
233
                }
234
            }
235
        );
236
237
        if ($grid->hasColumn('filetype')) {
238
            $grid->getColumn('filetype')->manipulateRenderCell(
239
                function ($value, Row $row, $router) {
0 ignored issues
show
Unused Code introduced by
The parameter $router is not used and could be removed. ( Ignorable by Annotation )

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

239
                function ($value, Row $row, /** @scrutinizer ignore-unused */ $router) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
240
                    /** @var AbstractResource $entity */
241
                    $entity = $row->getEntity();
242
                    $resourceNode = $entity->getResourceNode();
243
244
                    if ($resourceNode->hasResourceFile()) {
245
                        $file = $resourceNode->getResourceFile();
246
247
                        return $file->getMimeType();
248
                    }
249
250
                    return $this->trans('Folder');
251
                }
252
            );
253
        }
254
255
        if ($grid->hasColumn('iid')) {
256
            $grid->setHiddenColumns(['iid']);
257
        }
258
259
        // Delete mass action.
260
        if ($this->isGranted(ResourceNodeVoter::DELETE, $parentNode)) {
261
            $deleteMassAction = new MassAction(
262
                'Delete',
263
                'ChamiloCoreBundle:Resource:deleteMass',
264
                true,
265
                $routeParams
266
            );
267
            $grid->addMassAction($deleteMassAction);
268
        }
269
270
        // Info action.
271
        $myRowAction = new RowAction(
272
            $this->trans('Info'),
273
            'chamilo_core_resource_info',
274
            false,
275
            '_self',
276
            [
277
                'class' => 'btn btn-secondary info_action',
278
                'icon' => 'fa-info-circle',
279
                'iframe' => false,
280
            ]
281
        );
282
283
        $setNodeParameters = function (RowAction $action, Row $row) use ($routeParams) {
284
            $id = $row->getEntity()->getResourceNode()->getId();
285
            $routeParams['id'] = $id;
286
            $action->setRouteParameters($routeParams);
287
            $attributes = $action->getAttributes();
288
            $attributes['data-action'] = $action->getRoute();
289
            $attributes['data-action-id'] = $action->getRoute().'_'.$id;
290
            $attributes['data-node-id'] = $id;
291
            $attributes['title'] = $this->trans('Info').' '.$row->getEntity()->getResourceName();
292
            $action->setAttributes($attributes);
293
294
            return $action;
295
        };
296
297
        $myRowAction->addManipulateRender($setNodeParameters);
298
        $grid->addRowAction($myRowAction);
299
300
        // Download action
301
        $myRowAction = new RowAction(
302
            $this->trans('Download'),
303
            'chamilo_core_resource_download',
304
            false,
305
            '_self',
306
            [
307
                'class' => 'btn btn-secondary download_action',
308
                'icon' => 'fa-download',
309
                'title' => $this->trans('Download'),
310
            ]
311
        );
312
313
        $setNodeDownloadParameters = function (RowAction $action, Row $row) use ($routeParams) {
314
            $id = $row->getEntity()->getResourceNode()->getId();
315
            $routeParams['id'] = $id;
316
            $action->setRouteParameters($routeParams);
317
            $attributes = $action->getAttributes();
318
            $action->setAttributes($attributes);
319
320
            return $action;
321
        };
322
        $myRowAction->addManipulateRender($setNodeDownloadParameters);
323
        $grid->addRowAction($myRowAction);
324
325
        // Set EDIT/DELETE
326
        $setNodeParameters = function (RowAction $action, Row $row) use ($routeParams) {
327
            $id = $row->getEntity()->getResourceNode()->getId();
328
329
            $allowedEdit = $this->isGranted(ResourceNodeVoter::EDIT, $row->getEntity()->getResourceNode());
330
331
            if (false === $allowedEdit) {
332
                return null;
333
            }
334
335
            $routeParams['id'] = $id;
336
337
            $action->setRouteParameters($routeParams);
338
            $attributes = $action->getAttributes();
339
            //$attributes['data-action'] = $action->getRoute();
340
            //$attributes['data-action-id'] = $action->getRoute().'_'.$id;
341
            //$attributes['data-node-id'] = $id;
342
            $action->setAttributes($attributes);
343
344
            return $action;
345
        };
346
347
        if ($this->isGranted(ResourceNodeVoter::EDIT, $parentNode)) {
348
            // Enable/Disable
349
            $myRowAction = new RowAction(
350
                '',
351
                'chamilo_core_resource_change_visibility',
352
                false,
353
                '_self'
354
            );
355
356
            $setVisibleParameters = function (RowAction $action, Row $row) use ($routeParams) {
357
                /** @var AbstractResource $resource */
358
                $resource = $row->getEntity();
359
                $allowedEdit = $this->isGranted(ResourceNodeVoter::EDIT, $resource->getResourceNode());
360
361
                if (false === $allowedEdit) {
362
                    return null;
363
                }
364
365
                $id = $resource->getResourceNode()->getId();
366
367
                $icon = 'fa-eye-slash';
368
                if ($this->hasCourse()) {
369
                    $link = $resource->getCourseSessionResourceLink($this->getCourse(), $this->getSession());
370
                } else {
371
                    $link = $resource->getFirstResourceLink();
372
                }
373
374
                if (null === $link) {
375
                    return null;
376
                }
377
                if (ResourceLink::VISIBILITY_PUBLISHED === $link->getVisibility()) {
378
                    $icon = 'fa-eye';
379
                }
380
                $routeParams['id'] = $id;
381
                $action->setRouteParameters($routeParams);
382
                $attributes = [
383
                    'class' => 'btn btn-secondary change_visibility',
384
                    'data-id' => $id,
385
                    'icon' => $icon,
386
                ];
387
                $action->setAttributes($attributes);
388
389
                return $action;
390
            };
391
392
            $myRowAction->addManipulateRender($setVisibleParameters);
393
            $grid->addRowAction($myRowAction);
394
395
            if ($settings->isAllowResourceEdit()) {
396
                // Edit action.
397
                $myRowAction = new RowAction(
398
                    $this->trans('Edit'),
399
                    'chamilo_core_resource_edit',
400
                    false,
401
                    '_self',
402
                    ['class' => 'btn btn-secondary', 'icon' => 'fa fa-pen']
403
                );
404
                $myRowAction->addManipulateRender($setNodeParameters);
405
                $grid->addRowAction($myRowAction);
406
            }
407
408
            // More action.
409
            /*$myRowAction = new RowAction(
410
                $this->trans('More'),
411
                'chamilo_core_resource_preview',
412
                false,
413
                '_self',
414
                ['class' => 'btn btn-secondary edit_resource', 'icon' => 'fa fa-ellipsis-h']
415
            );
416
417
            $myRowAction->addManipulateRender($setNodeParameters);
418
            $grid->addRowAction($myRowAction);*/
419
420
            // Delete action.
421
            $myRowAction = new RowAction(
422
                $this->trans('Delete'),
423
                'chamilo_core_resource_delete',
424
                true,
425
                '_self',
426
                [
427
                    'class' => 'btn btn-danger',
428
                    //'data_hidden' => true,
429
                ]
430
            );
431
            $myRowAction->addManipulateRender($setNodeParameters);
432
            $grid->addRowAction($myRowAction);
433
        }
434
435
        /*$grid->addExport(new CSVExport($this->trans('CSV export'), 'export', ['course' => $courseIdentifier]));
436
        $grid->addExport(
437
            new ExcelExport(
438
                $this->trans('Excel export'),
439
                'export',
440
                ['course' => $courseIdentifier]
441
            )
442
        );*/
443
444
        return $grid;
445
    }
446
447
    /**
448
     * @Route("/{tool}/{type}/{id}/new_folder", methods={"GET", "POST"}, name="chamilo_core_resource_new_folder")
449
     */
450
    public function newFolderAction(Request $request): Response
451
    {
452
        $this->setBreadCrumb($request);
453
454
        return $this->createResource($request, 'folder');
455
    }
456
457
    /**
458
     * @Route("/{tool}/{type}/{id}/new", methods={"GET", "POST"}, name="chamilo_core_resource_new")
459
     */
460
    public function newAction(Request $request): Response
461
    {
462
        $this->setBreadCrumb($request);
463
464
        return $this->createResource($request, 'file');
465
    }
466
467
    /**
468
     * @Route("/{tool}/{type}/{id}/disk_space", methods={"GET", "POST"}, name="chamilo_core_resource_disk_space")
469
     */
470
    public function diskSpaceAction(Request $request): Response
471
    {
472
        $this->setBreadCrumb($request);
473
474
        $nodeId = $request->get('id');
475
476
        $repository = $this->getRepositoryFromRequest($request);
477
478
        /** @var ResourceNode $resourceNode */
479
        $resourceNode = $repository->getResourceNodeRepository()->find($nodeId);
480
        $size = $repository->getResourceNodeRepository()->getSize($resourceNode, $repository->getResourceType());
481
482
        $this->denyAccessUnlessGranted(
483
            ResourceNodeVoter::VIEW,
484
            $resourceNode,
485
            $this->trans('Unauthorised access to resource')
486
        );
487
488
        return $this->render(
489
            '@ChamiloTheme/Resource/disk_space.html.twig',
490
            [
491
                'resourceNode' => $resourceNode,
492
                'size' => $size,
493
            ]
494
        );
495
    }
496
497
    /**
498
     * @Route("/{tool}/{type}/{id}/edit", methods={"GET", "POST"})
499
     */
500
    public function editAction(Request $request, IllustrationRepository $illustrationRepository): Response
501
    {
502
        $resourceNodeId = $request->get('id');
503
504
        $this->setBreadCrumb($request);
505
        $repository = $this->getRepositoryFromRequest($request);
506
        $resource = $repository->getResourceFromResourceNode($resourceNodeId);
507
        $resourceNode = $resource->getResourceNode();
508
509
        $this->denyAccessUnlessGranted(
510
            ResourceNodeVoter::EDIT,
511
            $resourceNode,
512
            $this->trans('Unauthorised access to resource')
513
        );
514
515
        $resourceNodeParentId = $resourceNode->getId();
516
517
        $routeParams = $this->getResourceParams($request);
518
        $routeParams['id'] = $resourceNodeParentId;
519
520
        $form = $repository->getForm($this->container->get('form.factory'), $resource);
521
522
        if ($resourceNode->hasEditableContent()) {
523
            $form->add(
524
                'content',
525
                CKEditorType::class,
526
                [
527
                    'mapped' => false,
528
                    'config' => [
529
                        'filebrowserImageBrowseRoute' => 'resources_filemanager',
530
                        'filebrowserImageBrowseRouteParameters' => $routeParams,
531
                    ],
532
                ]
533
            );
534
            $content = $repository->getResourceNodeFileContent($resourceNode);
535
            $form->get('content')->setData($content);
536
        }
537
538
        $form->handleRequest($request);
539
540
        if ($form->isSubmitted() && $form->isValid()) {
541
            /** @var AbstractResource $newResource */
542
            $newResource = $form->getData();
543
544
            if ($form->has('content')) {
545
                $data = $form->get('content')->getData();
546
                $repository->updateResourceFileContent($newResource, $data);
547
            }
548
549
            //$newResource->setTitle($form->get('title')->getData()); // already set in $form->getData()
550
            $repository->updateNodeForResource($newResource);
551
552
            if ($form->has('illustration')) {
553
                $illustration = $form->get('illustration')->getData();
554
                if ($illustration) {
555
                    $file = $illustrationRepository->addIllustration($newResource, $this->getUser(), $illustration);
556
                    $em = $illustrationRepository->getEntityManager();
557
                    $em->persist($file);
558
                    $em->flush();
559
                }
560
            }
561
562
            $this->addFlash('success', $this->trans('Updated'));
563
564
            //if ($newResource->getResourceNode()->hasResourceFile()) {
565
            $resourceNodeParentId = $newResource->getResourceNode()->getParent()->getId();
566
            //}
567
            $routeParams['id'] = $resourceNodeParentId;
568
569
            return $this->redirectToRoute('chamilo_core_resource_list', $routeParams);
570
        }
571
572
        return $this->render(
573
            '@ChamiloTheme/Resource/edit.html.twig',
574
            [
575
                'form' => $form->createView(),
576
                'parent' => $resourceNodeParentId,
577
            ]
578
        );
579
    }
580
581
    /**
582
     * Shows a resource information.
583
     *
584
     * @Route("/{tool}/{type}/{id}/info", methods={"GET"}, name="chamilo_core_resource_info")
585
     */
586
    public function infoAction(Request $request, IllustrationRepository $illustrationRepository): Response
587
    {
588
        $this->setBreadCrumb($request);
589
        $nodeId = $request->get('id');
590
591
        $repository = $this->getRepositoryFromRequest($request);
592
593
        /** @var AbstractResource $resource */
594
        $resource = $repository->getResourceFromResourceNode($nodeId);
595
596
        if (null === $resource) {
597
            throw new NotFoundHttpException();
598
        }
599
600
        $resourceNode = $resource->getResourceNode();
601
602
        if (null === $resourceNode) {
603
            throw new NotFoundHttpException();
604
        }
605
606
        $this->denyAccessUnlessGranted(
607
            ResourceNodeVoter::VIEW,
608
            $resourceNode,
609
            $this->trans('Unauthorised access to resource')
610
        );
611
612
        $tool = $request->get('tool');
613
        $type = $request->get('type');
614
615
        $illustration = $illustrationRepository->getIllustrationUrlFromNode($resource->getResourceNode());
616
617
        $params = [
618
            'resource' => $resource,
619
            'illustration' => $illustration,
620
            'tool' => $tool,
621
            'type' => $type,
622
        ];
623
624
        return $this->render('@ChamiloTheme/Resource/info.html.twig', $params);
625
    }
626
627
    /**
628
     * Preview a file. Mostly used when using a modal.
629
     *
630
     * @Route("/{tool}/{type}/{id}/preview", methods={"GET"}, name="chamilo_core_resource_preview")
631
     */
632
    public function previewAction(Request $request): Response
633
    {
634
        $this->setBreadCrumb($request);
635
        $nodeId = $request->get('id');
636
637
        $repository = $this->getRepositoryFromRequest($request);
638
639
        /** @var AbstractResource $resource */
640
        $resource = $repository->getResourceFromResourceNode($nodeId);
641
642
        if (null === $resource) {
643
            throw new NotFoundHttpException();
644
        }
645
646
        $resourceNode = $resource->getResourceNode();
647
648
        if (null === $resourceNode) {
649
            throw new NotFoundHttpException();
650
        }
651
652
        $this->denyAccessUnlessGranted(
653
            ResourceNodeVoter::VIEW,
654
            $resourceNode,
655
            $this->trans('Unauthorised access to resource')
656
        );
657
658
        $tool = $request->get('tool');
659
        $type = $request->get('type');
660
661
        $params = [
662
            'resource' => $resource,
663
            'tool' => $tool,
664
            'type' => $type,
665
        ];
666
667
        return $this->render('@ChamiloTheme/Resource/preview.html.twig', $params);
668
    }
669
670
    /**
671
     * @Route("/{tool}/{type}/{id}/change_visibility", name="chamilo_core_resource_change_visibility")
672
     */
673
    public function changeVisibilityAction(Request $request): Response
674
    {
675
        $id = $request->get('id');
676
677
        $repository = $this->getRepositoryFromRequest($request);
678
679
        /** @var AbstractResource $resource */
680
        $resource = $repository->getResourceFromResourceNode($id);
681
682
        if (null === $resource) {
683
            throw new NotFoundHttpException();
684
        }
685
686
        $resourceNode = $resource->getResourceNode();
687
688
        $this->denyAccessUnlessGranted(
689
            ResourceNodeVoter::EDIT,
690
            $resourceNode,
691
            $this->trans('Unauthorised access to resource')
692
        );
693
694
        /** @var ResourceLink $link */
695
        if ($this->hasCourse()) {
696
            $link = $resource->getCourseSessionResourceLink($this->getCourse(), $this->getSession());
697
        } else {
698
            $link = $resource->getFirstResourceLink();
699
        }
700
701
        $icon = 'fa-eye';
702
        // Use repository to change settings easily.
703
        if ($link && ResourceLink::VISIBILITY_PUBLISHED === $link->getVisibility()) {
704
            $repository->setVisibilityDraft($resource);
705
            $icon = 'fa-eye-slash';
706
        } else {
707
            $repository->setVisibilityPublished($resource);
708
        }
709
710
        $result = ['icon' => $icon];
711
712
        return new JsonResponse($result);
713
    }
714
715
    /**
716
     * @Route("/{tool}/{type}/{id}", name="chamilo_core_resource_delete")
717
     */
718
    public function deleteAction(Request $request): Response
719
    {
720
        $em = $this->getDoctrine()->getManager();
721
722
        $id = $request->get('id');
723
        $resourceNode = $this->getDoctrine()->getRepository('ChamiloCoreBundle:Resource\ResourceNode')->find($id);
724
        $parentId = $resourceNode->getParent()->getId();
725
726
        if (null === $resourceNode) {
727
            throw new NotFoundHttpException();
728
        }
729
730
        $this->denyAccessUnlessGranted(
731
            ResourceNodeVoter::DELETE,
732
            $resourceNode,
733
            $this->trans('Unauthorised access to resource')
734
        );
735
736
        $children = $resourceNode->getChildren();
737
738
        if (!empty($children)) {
739
            /** @var ResourceNode $child */
740
            foreach ($children as $child) {
741
                $em->remove($child);
742
            }
743
        }
744
745
        $em->remove($resourceNode);
746
        $this->addFlash('success', $this->trans('Deleted'));
747
        $em->flush();
748
749
        $routeParams = $this->getResourceParams($request);
750
        $routeParams['id'] = $parentId;
751
752
        return $this->redirectToRoute(
753
            'chamilo_core_resource_list',
754
            $routeParams
755
        );
756
    }
757
758
    /**
759
     * @Route("/{tool}/{type}/{id}", methods={"DELETE"}, name="chamilo_core_resource_delete_mass")
760
     */
761
    public function deleteMassAction($primaryKeys, $allPrimaryKeys, Request $request): Response
762
    {
763
        $em = $this->getDoctrine()->getManager();
764
        $repo = $this->getRepositoryFromRequest($request);
765
766
        $parentId = 0;
767
        foreach ($primaryKeys as $id) {
768
            $resource = $repo->find($id);
769
            $resourceNode = $resource->getResourceNode();
770
771
            if (null === $resourceNode) {
772
                continue;
773
            }
774
775
            $this->denyAccessUnlessGranted(
776
                ResourceNodeVoter::DELETE,
777
                $resourceNode,
778
                $this->trans('Unauthorised access to resource')
779
            );
780
781
            $parentId = $resourceNode->getParent()->getId();
782
            $em->remove($resource);
783
        }
784
785
        $this->addFlash('success', $this->trans('Deleted'));
786
        $em->flush();
787
788
        $routeParams = $this->getResourceParams($request);
789
        $routeParams['id'] = $parentId;
790
791
        return $this->redirectToRoute('chamilo_core_resource_list', $routeParams);
792
    }
793
794
    /**
795
     * Shows the associated resource file.
796
     *
797
     * @Route("/{tool}/{type}/{id}/view", methods={"GET"}, name="chamilo_core_resource_view")
798
     */
799
    public function viewAction(Request $request, RouterInterface $router): Response
800
    {
801
        $id = $request->get('id');
802
        $filter = $request->get('filter');
803
        $mode = $request->get('mode');
804
        $em = $this->getDoctrine();
805
        /** @var ResourceNode $resourceNode */
806
        $resourceNode = $em->getRepository('ChamiloCoreBundle:Resource\ResourceNode')->find($id);
807
808
        if (null === $resourceNode) {
809
            throw new FileNotFoundException('Resource not found');
810
        }
811
812
        $repo = $this->getRepositoryFromRequest($request);
813
814
        if ($repo instanceof ResourceWithLinkInterface) {
815
            $resource = $repo->getResourceFromResourceNode($resourceNode->getId());
816
            $url = $repo->getLink($resource, $router, $this->getCourseUrlQueryToArray());
0 ignored issues
show
Bug introduced by
It seems like $resource can also be of type null; however, parameter $resource of Chamilo\CoreBundle\Repos...inkInterface::getLink() does only seem to accept Chamilo\CoreBundle\Entit...ource\ResourceInterface, maybe add an additional type check? ( Ignorable by Annotation )

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

816
            $url = $repo->getLink(/** @scrutinizer ignore-type */ $resource, $router, $this->getCourseUrlQueryToArray());
Loading history...
817
818
            return $this->redirect($url);
819
        }
820
821
        return $this->showFile($request, $resourceNode, $mode, $filter);
822
    }
823
824
    /**
825
     * Gets a document when calling route resources_document_get_file.
826
1     *
827
     * @deprecated
828
     *
829
     * @throws \League\Flysystem\FileNotFoundException
830
     */
831
    public function getDocumentAction(Request $request): Response
832
    {
833
        /*$file = $request->get('file');
834
        $mode = $request->get('mode');
835
836
        // see list of filters in config/services.yaml
837
        $filter = $request->get('filter');
838
        $mode = !empty($mode) ? $mode : 'show';
839
840
        $repository = $this->getRepository('document', 'files');
841
        $nodeRepository = $repository->getResourceNodeRepository();
842
843
        $title = basename($file);
844
        // @todo improve criteria to avoid giving the wrong file.
845
        $criteria = ['slug' => $title];
846
847
        $resourceNode = $nodeRepository->findOneBy($criteria);
848
849
        if (null === $resourceNode) {
850
            throw new NotFoundHttpException();
851
        }
852
853
        return $this->showFile($request, $resourceNode, $mode, $glide,$filter);*/
854
    }
0 ignored issues
show
Bug Best Practice introduced by
In this branch, the function will implicitly return null which is incompatible with the type-hinted return Symfony\Component\HttpFoundation\Response. Consider adding a return statement or allowing null as return value.

For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example:

interface ReturnsInt {
    public function returnsIntHinted(): int;
}

class MyClass implements ReturnsInt {
    public function returnsIntHinted(): int
    {
        if (foo()) {
            return 123;
        }
        // here: null is implicitly returned
    }
}
Loading history...
855
856
    /**
857
     * @Route("/{tool}/{type}/{id}/download", methods={"GET"}, name="chamilo_core_resource_download")
858
     */
859
    public function downloadAction(Request $request)
860
    {
861
        $resourceNodeId = (int) $request->get('id');
862
        $courseNode = $this->getCourse()->getResourceNode();
863
864
        $repo = $this->getRepositoryFromRequest($request);
865
866
        if (empty($resourceNodeId)) {
867
            $resourceNode = $courseNode;
868
        } else {
869
            $resourceNode = $repo->getResourceNodeRepository()->find($resourceNodeId);
870
        }
871
872
        if (null === $resourceNode) {
873
            throw new NotFoundHttpException();
874
        }
875
876
        $this->denyAccessUnlessGranted(
877
            ResourceNodeVoter::VIEW,
878
            $resourceNode,
879
            $this->trans('Unauthorised access to resource')
880
        );
881
882
        // If resource node has a file just download it. Don't download the children.
883
        if ($resourceNode->hasResourceFile()) {
884
            // Redirect to download single file.
885
            return $this->showFile($request, $resourceNode, 'download');
886
        }
887
888
        $zipName = $resourceNode->getSlug().'.zip';
889
        $rootNodePath = $resourceNode->getPathForDisplay();
890
        $resourceNodeRepo = $repo->getResourceNodeRepository();
891
892
        $criteria = Criteria::create()
893
            ->where(Criteria::expr()->neq('resourceFile', null)) // must have a file
894
           // ->andWhere(Criteria::expr()->eq('resourceType', $type))
895
        ;
896
897
        /** @var ArrayCollection|ResourceNode[] $children */
898
        /** @var QueryBuilder $children */
899
        $qb = $resourceNodeRepo->getChildrenQueryBuilder($resourceNode);
900
        $qb->addCriteria($criteria);
901
        $children = $qb->getQuery()->getResult();
902
        $count = count($children);
903
        if (0 === $count) {
904
            $params = $this->getResourceParams($request);
905
            $params['id'] = $resourceNodeId;
906
907
            $this->addFlash('warning', $this->trans('No files'));
908
909
            return $this->redirectToRoute(
910
                'chamilo_core_resource_list',
911
                $params
912
            );
913
        }
914
915
        $response = new StreamedResponse(function () use ($rootNodePath, $zipName, $children, $repo) {
916
            // Define suitable options for ZipStream Archive.
917
            $options = new Archive();
918
            $options->setContentType('application/octet-stream');
919
            //initialise zipstream with output zip filename and options.
920
            $zip = new ZipStream($zipName, $options);
921
922
            /** @var ResourceNode $node */
923
            foreach ($children as $node) {
924
                //$resourceFile = $node->getResourceFile();
925
                //$systemName = $resourceFile->getFile()->getPathname();
926
                $stream = $repo->getResourceNodeFileStream($node);
927
                //error_log($node->getPathForDisplay());
928
                $fileToDisplay = str_replace($rootNodePath, '', $node->getPathForDisplay());
929
                $zip->addFileFromStream($fileToDisplay, $stream);
930
            }
931
            $zip->finish();
932
        });
933
934
        $disposition = $response->headers->makeDisposition(
935
            ResponseHeaderBag::DISPOSITION_ATTACHMENT,
936
            $zipName //Transliterator::transliterate($zipName)
937
        );
938
        $response->headers->set('Content-Disposition', $disposition);
939
        $response->headers->set('Content-Type', 'application/octet-stream');
940
941
        return $response;
942
    }
943
944
    /**
945
     * Upload form.
946
     *
947
     * @Route("/{tool}/{type}/{id}/upload", name="chamilo_core_resource_upload", methods={"GET", "POST"},
948
     *                                      options={"expose"=true})
949
     */
950
    public function uploadAction(Request $request, $tool, $type, $id): Response
951
    {
952
        $repository = $this->getRepositoryFromRequest($request);
953
        $resourceNode = $repository->getResourceNodeRepository()->find($id);
954
955
        $this->denyAccessUnlessGranted(
956
            ResourceNodeVoter::EDIT,
957
            $resourceNode,
958
            $this->trans('Unauthorised access to resource')
959
        );
960
961
        $this->setBreadCrumb($request);
962
963
        $routeParams = $this->getResourceParams($request);
964
        $routeParams['tool'] = $tool;
965
        $routeParams['type'] = $type;
966
        $routeParams['id'] = $id;
967
968
        return $this->render(
969
            '@ChamiloTheme/Resource/upload.html.twig',
970
            $routeParams
971
        );
972
    }
973
974
    public function setBreadCrumb(Request $request)
975
    {
976
        $tool = $request->get('tool');
977
        $type = $request->get('type');
978
        $resourceNodeId = $request->get('id');
979
980
        $routeParams = $this->getResourceParams($request);
981
982
        if (!empty($resourceNodeId)) {
983
            $breadcrumb = $this->getBreadCrumb();
984
            $toolParams = $routeParams;
985
            $toolParams['id'] = null;
986
987
            // Root tool link
988
            $breadcrumb->addChild(
989
                $this->trans($tool),
990
                [
991
                    'uri' => $this->generateUrl(
992
                        'chamilo_core_resource_index',
993
                        $toolParams
994
                    ),
995
                ]
996
            );
997
998
            $repo = $this->getRepositoryFromRequest($request);
999
1000
            /** @var ResourceInterface $parent */
1001
            $originalResource = $repo->findOneBy(['resourceNode' => $resourceNodeId]);
1002
            if (null === $originalResource) {
1003
                return;
1004
            }
1005
            $parent = $originalParent = $originalResource->getResourceNode();
1006
1007
            $parentList = [];
1008
            while (null !== $parent) {
1009
                if ($type !== $parent->getResourceType()->getName()) {
1010
                    break;
1011
                }
1012
                $parent = $parent->getParent();
1013
                if ($parent) {
1014
                    $resource = $repo->findOneBy(['resourceNode' => $parent->getId()]);
1015
                    if ($resource) {
1016
                        $parentList[] = $resource;
1017
                    }
1018
                }
1019
            }
1020
1021
            $parentList = array_reverse($parentList);
1022
            /** @var ResourceInterface $item */
1023
            foreach ($parentList as $item) {
1024
                $params = $routeParams;
1025
                $params['id'] = $item->getResourceNode()->getId();
1026
                $breadcrumb->addChild(
1027
                    $item->getResourceName(),
1028
                    [
1029
                        'uri' => $this->generateUrl(
1030
                            'chamilo_core_resource_list',
1031
                            $params
1032
                        ),
1033
                    ]
1034
                );
1035
            }
1036
1037
            $params = $routeParams;
1038
            $params['id'] = $originalParent->getId();
1039
1040
            $breadcrumb->addChild(
1041
                $originalResource->getResourceName(),
1042
                [
1043
                    'uri' => $this->generateUrl(
1044
                        'chamilo_core_resource_list',
1045
                        $params
1046
                    ),
1047
                ]
1048
            );
1049
        }
1050
    }
1051
1052
    private function getParentResourceNode(Request $request): ResourceNode
1053
    {
1054
        $parentNodeId = $request->get('id');
1055
1056
        $parentResourceNode = null;
1057
1058
        if (empty($parentNodeId)) {
1059
            if ($this->hasCourse()) {
1060
                $parentResourceNode = $this->getCourse()->getResourceNode();
1061
            } else {
1062
                if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
1063
                    /** @var User $user */
1064
                    $parentResourceNode = $this->getUser()->getResourceNode();
1065
                }
1066
            }
1067
        } else {
1068
            $repo = $this->getDoctrine()->getRepository('ChamiloCoreBundle:Resource\ResourceNode');
1069
            $parentResourceNode = $repo->find($parentNodeId);
1070
        }
1071
1072
        if (null === $parentResourceNode) {
1073
            throw new AccessDeniedException();
1074
        }
1075
1076
        return $parentResourceNode;
1077
    }
1078
1079
    /**
1080
     * @param string $mode
1081
     * @param string $filter
1082
     *
1083
     * @return mixed|StreamedResponse
1084
     */
1085
    private function showFile(Request $request, ResourceNode $resourceNode, $mode = 'show', $filter = '')
1086
    {
1087
        $this->denyAccessUnlessGranted(
1088
            ResourceNodeVoter::VIEW,
1089
            $resourceNode,
1090
            $this->trans('Unauthorised access to resource')
1091
        );
1092
1093
        $repo = $this->getRepositoryFromRequest($request);
1094
        $resourceFile = $resourceNode->getResourceFile();
1095
1096
        if (!$resourceFile) {
0 ignored issues
show
introduced by
$resourceFile is of type Chamilo\CoreBundle\Entity\Resource\ResourceFile, thus it always evaluated to true.
Loading history...
1097
            throw new NotFoundHttpException($this->trans('File not found for resource'));
1098
        }
1099
1100
        $fileName = $resourceNode->getSlug();
1101
        $mimeType = $resourceFile->getMimeType();
1102
1103
        switch ($mode) {
1104
            case 'download':
1105
                $forceDownload = true;
1106
1107
                break;
1108
            case 'show':
1109
            default:
1110
                $forceDownload = false;
1111
                // If it's an image then send it to Glide.
1112
                if (false !== strpos($mimeType, 'image')) {
1113
                    $glide = $this->getGlide();
1114
                    $server = $glide->getServer();
1115
                    $params = $request->query->all();
1116
1117
                    // The filter overwrites the params from get
1118
                    if (!empty($filter)) {
1119
                        $params = $glide->getFilters()[$filter] ?? [];
1120
                    }
1121
1122
                    // The image was cropped manually by the user, so we force to render this version,
1123
                    // no matter other crop parameters.
1124
                    $crop = $resourceFile->getCrop();
1125
                    if (!empty($crop)) {
1126
                        $params['crop'] = $crop;
1127
                    }
1128
1129
                    $fileName = $repo->getFilename($resourceFile);
1130
1131
                    return $server->getImageResponse($fileName, $params);
1132
                }
1133
1134
                break;
1135
        }
1136
1137
        $stream = $repo->getResourceNodeFileStream($resourceNode);
1138
1139
        $response = new StreamedResponse(function () use ($stream): void {
1140
            stream_copy_to_stream($stream, fopen('php://output', 'wb'));
0 ignored issues
show
Bug introduced by
It seems like fopen('php://output', 'wb') can also be of type false; however, parameter $dest of stream_copy_to_stream() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

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

1140
            stream_copy_to_stream($stream, /** @scrutinizer ignore-type */ fopen('php://output', 'wb'));
Loading history...
Bug introduced by
It seems like $stream can also be of type string; however, parameter $source of stream_copy_to_stream() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

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

1140
            stream_copy_to_stream(/** @scrutinizer ignore-type */ $stream, fopen('php://output', 'wb'));
Loading history...
1141
        });
1142
        $disposition = $response->headers->makeDisposition(
1143
            $forceDownload ? ResponseHeaderBag::DISPOSITION_ATTACHMENT : ResponseHeaderBag::DISPOSITION_INLINE,
1144
            $fileName
1145
            //Transliterator::transliterate($fileName)
1146
        );
1147
        $response->headers->set('Content-Disposition', $disposition);
1148
        $response->headers->set('Content-Type', $mimeType ?: 'application/octet-stream');
1149
1150
        return $response;
1151
    }
1152
1153
    /**
1154
     * @param string $fileType
1155
     *
1156
     * @return RedirectResponse|Response
1157
     */
1158
    private function createResource(Request $request, $fileType = 'file')
1159
    {
1160
        $resourceNodeParentId = $request->get('id');
1161
1162
        $repository = $this->getRepositoryFromRequest($request);
1163
1164
        // Default parent node is course.
1165
        $parentNode = $this->getParentResourceNode($request);
1166
        //var_dump($parentNode->getPath());
1167
1168
        $this->denyAccessUnlessGranted(
1169
            ResourceNodeVoter::CREATE,
1170
            $parentNode,
1171
            $this->trans('Unauthorised access to resource')
1172
        );
1173
1174
        $form = $repository->getForm($this->container->get('form.factory'), null);
1175
1176
        if ('file' === $fileType) {
1177
            $resourceParams = $this->getResourceParams($request);
1178
            $form->add(
1179
                'content',
1180
                CKEditorType::class,
1181
                [
1182
                    'mapped' => false,
1183
                    'config' => [
1184
                        'filebrowserImageBrowseRoute' => 'resources_filemanager',
1185
                        'filebrowserImageBrowseRouteParameters' => $resourceParams,
1186
                        'fullPage' => true,
1187
                    ],
1188
                ]
1189
            );
1190
        }
1191
1192
        $form->handleRequest($request);
1193
        if ($form->isSubmitted() && $form->isValid()) {
1194
            $em = $this->getDoctrine()->getManager();
1195
1196
            $course = $this->getCourse();
1197
            $session = $this->getSession();
1198
1199
            /** @var AbstractResource $newResource */
1200
            $newResource = $repository->saveResource($form, $course, $session, $fileType);
1201
1202
            $file = null;
1203
            if ('file' === $fileType && $newResource instanceof CDocument) {
1204
                $content = $form->get('content')->getViewData();
1205
                $newResource->setTitle($newResource->getTitle().'.html');
1206
                $fileName = $newResource->getTitle();
1207
1208
                $handle = tmpfile();
1209
                fwrite($handle, $content);
0 ignored issues
show
Bug introduced by
It seems like $handle can also be of type false; however, parameter $handle of fwrite() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

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

1209
                fwrite(/** @scrutinizer ignore-type */ $handle, $content);
Loading history...
1210
                $meta = stream_get_meta_data($handle);
0 ignored issues
show
Bug introduced by
It seems like $handle can also be of type false; however, parameter $stream of stream_get_meta_data() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

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

1210
                $meta = stream_get_meta_data(/** @scrutinizer ignore-type */ $handle);
Loading history...
1211
                $file = new UploadedFile($meta['uri'], $fileName, 'text/html', null, true);
1212
                $em->persist($newResource);
1213
            }
1214
1215
            $repository->addResourceToCourseWithParent(
1216
                $newResource,
1217
                $parentNode,
1218
                ResourceLink::VISIBILITY_PUBLISHED,
1219
                $this->getUser(),
1220
                $course,
1221
                $session,
1222
                null,
1223
                $file
1224
            );
1225
1226
            $em->flush();
1227
1228
            // Loops all sharing options
1229
            /*foreach ($shareList as $share) {
1230
                $idList = [];
1231
                if (isset($share['search'])) {
1232
                    $idList = explode(',', $share['search']);
1233
                }
1234
1235
                $resourceRight = null;
1236
                if (isset($share['mask'])) {
1237
                    $resourceRight = new ResourceRight();
1238
                    $resourceRight
1239
                        ->setMask($share['mask'])
1240
                        ->setRole($share['role'])
1241
                    ;
1242
                }
1243
1244
                // Build links
1245
                switch ($share['sharing']) {
1246
                    case 'everyone':
1247
                        $repository->addResourceToEveryone(
1248
                            $resourceNode,
1249
                            $resourceRight
1250
                        );
1251
                        break;
1252
                    case 'course':
1253
                        $repository->addResourceToCourse(
1254
                            $resourceNode,
1255
                            $course,
1256
                            $resourceRight
1257
                        );
1258
                        break;
1259
                    case 'session':
1260
                        $repository->addResourceToSession(
1261
                            $resourceNode,
1262
                            $course,
1263
                            $session,
1264
                            $resourceRight
1265
                        );
1266
                        break;
1267
                    case 'user':
1268
                        // Only for me
1269
                        if (isset($share['only_me'])) {
1270
                            $repository->addResourceOnlyToMe($resourceNode);
1271
                        } else {
1272
                            // To other users
1273
                            $repository->addResourceToUserList($resourceNode, $idList);
1274
                        }
1275
                        break;
1276
                    case 'group':
1277
                        // @todo
1278
                        break;
1279
                }*/
1280
            //}
1281
            $em->flush();
1282
            $this->addFlash('success', $this->trans('Saved'));
1283
1284
            $params = $this->getResourceParams($request);
1285
            $params['id'] = $resourceNodeParentId;
1286
1287
            return $this->redirectToRoute(
1288
                'chamilo_core_resource_list',
1289
                $params
1290
            );
1291
        }
1292
1293
        switch ($fileType) {
1294
            case 'folder':
1295
                $template = '@ChamiloTheme/Resource/new_folder.html.twig';
1296
1297
                break;
1298
            case 'file':
1299
                $template = '@ChamiloTheme/Resource/new.html.twig';
1300
1301
                break;
1302
        }
1303
1304
        return $this->render(
1305
            $template,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $template does not seem to be defined for all execution paths leading up to this point.
Loading history...
1306
            [
1307
                'form' => $form->createView(),
1308
                'parent' => $resourceNodeParentId,
1309
                'file_type' => $fileType,
1310
            ]
1311
        );
1312
    }
1313
}
1314