Completed
Push — master ( e487ad...a4fd9c )
by Julito
15:18
created

ResourceController   F

Complexity

Total Complexity 80

Size/Duplication

Total Lines 1193
Duplicated Lines 0 %

Importance

Changes 6
Bugs 0 Features 1
Metric Value
eloc 570
c 6
b 0
f 1
dl 0
loc 1193
rs 2
wmc 80

19 Methods

Rating   Name   Duplication   Size   Complexity  
A deleteAction() 0 28 2
A deleteMassAction() 0 31 3
A uploadAction() 0 21 1
A previewAction() 0 36 3
D getGrid() 0 312 15
A getDocumentAction() 0 2 1
A newAction() 0 5 1
A indexAction() 0 30 1
B showFile() 0 64 9
A viewAction() 0 13 2
B editAction() 0 78 7
B downloadAction() 0 74 5
B setBreadCrumb() 0 72 8
A newFolderAction() 0 5 1
A infoAction() 0 39 3
A getParentResourceNode() 0 25 5
B createResource() 0 150 7
A changeVisibilityAction() 0 40 5
A listAction() 0 23 1

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

This check looks for imports that have been defined, but are not used in the scope.

Loading history...
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

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

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...
237
                    /** @var AbstractResource $entity */
238
                    $entity = $row->getEntity();
239
                    $resourceNode = $entity->getResourceNode();
240
241
                    if ($resourceNode->hasResourceFile()) {
242
                        $file = $resourceNode->getResourceFile();
243
244
                        return $file->getMimeType();
245
                    }
246
247
                    return $this->trans('Folder');
248
                }
249
            );
250
        }
251
252
        if ($grid->hasColumn('iid')) {
253
            $grid->setHiddenColumns(['iid']);
254
        }
255
256
        // Delete mass action.
257
        if ($this->isGranted(ResourceNodeVoter::DELETE, $parentNode)) {
258
            $deleteMassAction = new MassAction(
259
                'Delete',
260
                'ChamiloCoreBundle:Resource:deleteMass',
261
                true,
262
                $routeParams
263
            );
264
            $grid->addMassAction($deleteMassAction);
265
        }
266
267
        // Info action.
268
        $myRowAction = new RowAction(
269
            $this->trans('Info'),
270
            'chamilo_core_resource_info',
271
            false,
272
            '_self',
273
            [
274
                'class' => 'btn btn-secondary info_action',
275
                'icon' => 'fa-info-circle',
276
                'iframe' => false,
277
            ]
278
        );
279
280
        $setNodeParameters = function (RowAction $action, Row $row) use ($routeParams) {
281
            $id = $row->getEntity()->getResourceNode()->getId();
282
            $routeParams['id'] = $id;
283
            $action->setRouteParameters($routeParams);
284
            $attributes = $action->getAttributes();
285
            $attributes['data-action'] = $action->getRoute();
286
            $attributes['data-action-id'] = $action->getRoute().'_'.$id;
287
            $attributes['data-node-id'] = $id;
288
289
            $action->setAttributes($attributes);
290
291
            return $action;
292
        };
293
294
        $myRowAction->addManipulateRender($setNodeParameters);
295
        $grid->addRowAction($myRowAction);
296
297
        // Download action
298
        $myRowAction = new RowAction(
299
            $this->trans('Download'),
300
            'chamilo_core_resource_download',
301
            false,
302
            '_self',
303
            [
304
                'class' => 'btn btn-secondary download_action',
305
                'icon' => 'fa-download',
306
            ]
307
        );
308
309
        $setNodeDownloadParameters = function (RowAction $action, Row $row) use ($routeParams) {
310
            $id = $row->getEntity()->getResourceNode()->getId();
311
            $routeParams['id'] = $id;
312
            $action->setRouteParameters($routeParams);
313
            $attributes = $action->getAttributes();
314
            $action->setAttributes($attributes);
315
316
            return $action;
317
        };
318
        $myRowAction->addManipulateRender($setNodeDownloadParameters);
319
        $grid->addRowAction($myRowAction);
320
321
        // Set EDIT/DELETE
322
        $setNodeParameters = function (RowAction $action, Row $row) use ($routeParams) {
323
            $id = $row->getEntity()->getResourceNode()->getId();
324
325
            $allowedEdit = $this->isGranted(ResourceNodeVoter::EDIT, $row->getEntity()->getResourceNode());
326
327
            if ($allowedEdit === false) {
328
                return null;
329
            }
330
331
            $routeParams['id'] = $id;
332
333
            $action->setRouteParameters($routeParams);
334
            $attributes = $action->getAttributes();
335
            //$attributes['data-action'] = $action->getRoute();
336
            //$attributes['data-action-id'] = $action->getRoute().'_'.$id;
337
            //$attributes['data-node-id'] = $id;
338
            $action->setAttributes($attributes);
339
340
            return $action;
341
        };
342
343
        if ($this->isGranted(ResourceNodeVoter::EDIT, $parentNode)) {
344
            // Enable/Disable
345
            $myRowAction = new RowAction(
346
                '',
347
                'chamilo_core_resource_change_visibility',
348
                false,
349
                '_self'
350
            );
351
352
            $setVisibleParameters = function (RowAction $action, Row $row) use ($routeParams) {
353
                /** @var AbstractResource $resource */
354
                $resource = $row->getEntity();
355
                $allowedEdit = $this->isGranted(ResourceNodeVoter::EDIT, $resource->getResourceNode());
356
357
                if ($allowedEdit === false) {
358
                    return null;
359
                }
360
361
                $id = $resource->getResourceNode()->getId();
362
363
                $icon = 'fa-eye-slash';
364
                if ($this->hasCourse()) {
365
                    $link = $resource->getCourseSessionResourceLink($this->getCourse(), $this->getSession());
366
                } else {
367
                    $link = $resource->getFirstResourceLink();
368
                }
369
370
                if ($link === null) {
371
                    return null;
372
                }
373
                if ($link->getVisibility() === ResourceLink::VISIBILITY_PUBLISHED) {
374
                    $icon = 'fa-eye';
375
                }
376
                $routeParams['id'] = $id;
377
                $action->setRouteParameters($routeParams);
378
                $attributes = [
379
                    'class' => 'btn btn-secondary change_visibility',
380
                    'data-id' => $id,
381
                    'icon' => $icon,
382
                ];
383
                $action->setAttributes($attributes);
384
385
                return $action;
386
            };
387
388
            $myRowAction->addManipulateRender($setVisibleParameters);
389
            $grid->addRowAction($myRowAction);
390
391
            if ($settings->isAllowResourceEdit()) {
392
                // Edit action.
393
                $myRowAction = new RowAction(
394
                    $this->trans('Edit'),
395
                    'chamilo_core_resource_edit',
396
                    false,
397
                    '_self',
398
                    ['class' => 'btn btn-secondary', 'icon' => 'fa fa-pen']
399
                );
400
                $myRowAction->addManipulateRender($setNodeParameters);
401
                $grid->addRowAction($myRowAction);
402
            }
403
404
            // More action.
405
            /*$myRowAction = new RowAction(
406
                $this->trans('More'),
407
                'chamilo_core_resource_preview',
408
                false,
409
                '_self',
410
                ['class' => 'btn btn-secondary edit_resource', 'icon' => 'fa fa-ellipsis-h']
411
            );
412
413
            $myRowAction->addManipulateRender($setNodeParameters);
414
            $grid->addRowAction($myRowAction);*/
415
416
            // Delete action.
417
            $myRowAction = new RowAction(
418
                $this->trans('Delete'),
419
                'chamilo_core_resource_delete',
420
                true,
421
                '_self',
422
                [
423
                    'class' => 'btn btn-danger',
424
                    //'data_hidden' => true,
425
                ]
426
            );
427
            $myRowAction->addManipulateRender($setNodeParameters);
428
            $grid->addRowAction($myRowAction);
429
        }
430
431
        /*$grid->addExport(new CSVExport($this->trans('CSV export'), 'export', ['course' => $courseIdentifier]));
432
        $grid->addExport(
433
            new ExcelExport(
434
                $this->trans('Excel export'),
435
                'export',
436
                ['course' => $courseIdentifier]
437
            )
438
        );*/
439
440
        return $grid;
441
    }
442
443
    /**
444
     * @Route("/{tool}/{type}/{id}/new_folder", methods={"GET", "POST"}, name="chamilo_core_resource_new_folder")
445
     */
446
    public function newFolderAction(Request $request): Response
447
    {
448
        $this->setBreadCrumb($request);
449
450
        return $this->createResource($request, 'folder');
451
    }
452
453
    /**
454
     * @Route("/{tool}/{type}/{id}/new", methods={"GET", "POST"}, name="chamilo_core_resource_new")
455
     */
456
    public function newAction(Request $request): Response
457
    {
458
        $this->setBreadCrumb($request);
459
460
        return $this->createResource($request, 'file');
461
    }
462
463
    /**
464
     * @Route("/{tool}/{type}/{id}/edit", methods={"GET", "POST"})
465
     */
466
    public function editAction(Request $request, IllustrationRepository $illustrationRepository): Response
467
    {
468
        $resourceNodeId = $request->get('id');
469
470
        $this->setBreadCrumb($request);
471
        $repository = $this->getRepositoryFromRequest($request);
472
        /** @var AbstractResource $resource */
473
        $resource = $repository->getRepository()->findOneBy(['resourceNode' => $resourceNodeId]);
474
        $resourceNode = $resource->getResourceNode();
475
476
        $this->denyAccessUnlessGranted(
477
            ResourceNodeVoter::EDIT,
478
            $resourceNode,
479
            $this->trans('Unauthorised access to resource')
480
        );
481
482
        $resourceNodeParentId = $resourceNode->getId();
483
484
        $routeParams = $this->getResourceParams($request);
485
        $routeParams['id'] = $resourceNodeParentId;
486
487
        $form = $repository->getForm($this->container->get('form.factory'), $resource);
488
489
        if ($resourceNode->hasEditableContent()) {
490
            $form->add(
491
                'content',
492
                CKEditorType::class,
493
                [
494
                    'mapped' => false,
495
                    'config' => [
496
                        'filebrowserImageBrowseRoute' => 'resources_filemanager',
497
                        'filebrowserImageBrowseRouteParameters' => $routeParams,
498
                    ],
499
                ]
500
            );
501
            $content = $repository->getResourceNodeFileContent($resourceNode);
502
            $form->get('content')->setData($content);
503
        }
504
505
        $form->handleRequest($request);
506
507
        if ($form->isSubmitted() && $form->isValid()) {
508
            /** @var AbstractResource $newResource */
509
            $newResource = $form->getData();
510
511
            if ($form->has('content')) {
512
                $data = $form->get('content')->getData();
513
                $repository->updateResourceFileContent($newResource, $data);
514
            }
515
516
            //$newResource->setTitle($form->get('title')->getData()); // already set in $form->getData()
517
            $repository->updateNodeForResource($newResource);
518
519
            if ($form->has('illustration')) {
520
                $illustration = $form->get('illustration')->getData();
521
                if ($illustration) {
522
                    $file = $illustrationRepository->addIllustration($newResource, $this->getUser(), $illustration);
523
                    $em = $illustrationRepository->getEntityManager();
524
                    $em->persist($file);
525
                    $em->flush();
526
                }
527
            }
528
529
            $this->addFlash('success', $this->trans('Updated'));
530
531
            //if ($newResource->getResourceNode()->hasResourceFile()) {
532
            $resourceNodeParentId = $newResource->getResourceNode()->getParent()->getId();
533
            //}
534
            $routeParams['id'] = $resourceNodeParentId;
535
536
            return $this->redirectToRoute('chamilo_core_resource_list', $routeParams);
537
        }
538
539
        return $this->render(
540
            '@ChamiloTheme/Resource/edit.html.twig',
541
            [
542
                'form' => $form->createView(),
543
                'parent' => $resourceNodeParentId,
544
            ]
545
        );
546
    }
547
548
    /**
549
     * Shows a resource information.
550
     *
551
     * @Route("/{tool}/{type}/{id}/info", methods={"GET"}, name="chamilo_core_resource_info")
552
     */
553
    public function infoAction(Request $request, IllustrationRepository $illustrationRepository): Response
554
    {
555
        $this->setBreadCrumb($request);
556
        $nodeId = $request->get('id');
557
558
        $repository = $this->getRepositoryFromRequest($request);
559
560
        /** @var AbstractResource $resource */
561
        $resource = $repository->getRepository()->findOneBy(['resourceNode' => $nodeId]);
562
563
        if (null === $resource) {
564
            throw new NotFoundHttpException();
565
        }
566
567
        $resourceNode = $resource->getResourceNode();
568
569
        if (null === $resourceNode) {
570
            throw new NotFoundHttpException();
571
        }
572
573
        $this->denyAccessUnlessGranted(
574
            ResourceNodeVoter::VIEW,
575
            $resourceNode,
576
            $this->trans('Unauthorised access to resource')
577
        );
578
579
        $tool = $request->get('tool');
580
        $type = $request->get('type');
581
582
        $illustration = $illustrationRepository->getIllustrationUrlFromNode($resource->getResourceNode());
583
584
        $params = [
585
            'resource' => $resource,
586
            'illustration' => $illustration,
587
            'tool' => $tool,
588
            'type' => $type,
589
        ];
590
591
        return $this->render('@ChamiloTheme/Resource/info.html.twig', $params);
592
    }
593
594
    /**
595
     * Preview a file. Mostly used when using a modal.
596
     *
597
     * @Route("/{tool}/{type}/{id}/preview", methods={"GET"}, name="chamilo_core_resource_preview")
598
     */
599
    public function previewAction(Request $request): Response
600
    {
601
        $this->setBreadCrumb($request);
602
        $nodeId = $request->get('id');
603
604
        $repository = $this->getRepositoryFromRequest($request);
605
606
        /** @var AbstractResource $resource */
607
        $resource = $repository->getRepository()->findOneBy(['resourceNode' => $nodeId]);
608
609
        if (null === $resource) {
610
            throw new NotFoundHttpException();
611
        }
612
613
        $resourceNode = $resource->getResourceNode();
614
615
        if (null === $resourceNode) {
616
            throw new NotFoundHttpException();
617
        }
618
619
        $this->denyAccessUnlessGranted(
620
            ResourceNodeVoter::VIEW,
621
            $resourceNode,
622
            $this->trans('Unauthorised access to resource')
623
        );
624
625
        $tool = $request->get('tool');
626
        $type = $request->get('type');
627
628
        $params = [
629
            'resource' => $resource,
630
            'tool' => $tool,
631
            'type' => $type,
632
        ];
633
634
        return $this->render('@ChamiloTheme/Resource/preview.html.twig', $params);
635
    }
636
637
    /**
638
     * @Route("/{tool}/{type}/{id}/change_visibility", name="chamilo_core_resource_change_visibility")
639
     */
640
    public function changeVisibilityAction(Request $request): Response
641
    {
642
        $id = $request->get('id');
643
644
        $repository = $this->getRepositoryFromRequest($request);
645
646
        /** @var AbstractResource $resource */
647
        $resource = $repository->getRepository()->findOneBy(['resourceNode' => $id]);
648
649
        if (null === $resource) {
650
            throw new NotFoundHttpException();
651
        }
652
653
        $resourceNode = $resource->getResourceNode();
654
655
        $this->denyAccessUnlessGranted(
656
            ResourceNodeVoter::EDIT,
657
            $resourceNode,
658
            $this->trans('Unauthorised access to resource')
659
        );
660
661
        /** @var ResourceLink $link */
662
        if ($this->hasCourse()) {
663
            $link = $resource->getCourseSessionResourceLink($this->getCourse(), $this->getSession());
664
        } else {
665
            $link = $resource->getFirstResourceLink();
666
        }
667
668
        $icon = 'fa-eye';
669
        // Use repository to change settings easily.
670
        if ($link && $link->getVisibility() === ResourceLink::VISIBILITY_PUBLISHED) {
671
            $repository->setVisibilityDraft($resource);
672
            $icon = 'fa-eye-slash';
673
        } else {
674
            $repository->setVisibilityPublished($resource);
675
        }
676
677
        $result = ['icon' => $icon];
678
679
        return new JsonResponse($result);
680
    }
681
682
    /**
683
     * @Route("/{tool}/{type}/{id}", name="chamilo_core_resource_delete")
684
     */
685
    public function deleteAction(Request $request): Response
686
    {
687
        $em = $this->getDoctrine()->getManager();
688
689
        $id = $request->get('id');
690
        $resourceNode = $this->getDoctrine()->getRepository('ChamiloCoreBundle:Resource\ResourceNode')->find($id);
691
        $parentId = $resourceNode->getParent()->getId();
692
693
        if (null === $resourceNode) {
694
            throw new NotFoundHttpException();
695
        }
696
697
        $this->denyAccessUnlessGranted(
698
            ResourceNodeVoter::DELETE,
699
            $resourceNode,
700
            $this->trans('Unauthorised access to resource')
701
        );
702
703
        $em->remove($resourceNode);
704
        $this->addFlash('success', $this->trans('Deleted'));
705
        $em->flush();
706
707
        $routeParams = $this->getResourceParams($request);
708
        $routeParams['id'] = $parentId;
709
710
        return $this->redirectToRoute(
711
            'chamilo_core_resource_list',
712
            $routeParams
713
        );
714
    }
715
716
    /**
717
     * @Route("/{tool}/{type}/{id}", methods={"DELETE"}, name="chamilo_core_resource_delete_mass")
718
     */
719
    public function deleteMassAction($primaryKeys, $allPrimaryKeys, Request $request): Response
720
    {
721
        $em = $this->getDoctrine()->getManager();
722
        $repo = $this->getRepositoryFromRequest($request);
723
724
        $parentId = 0;
725
        foreach ($primaryKeys as $id) {
726
            $resource = $repo->find($id);
727
            $resourceNode = $resource->getResourceNode();
728
729
            if (null === $resourceNode) {
730
                continue;
731
            }
732
733
            $this->denyAccessUnlessGranted(
734
                ResourceNodeVoter::DELETE,
735
                $resourceNode,
736
                $this->trans('Unauthorised access to resource')
737
            );
738
739
            $parentId = $resourceNode->getParent()->getId();
740
            $em->remove($resource);
741
        }
742
743
        $this->addFlash('success', $this->trans('Deleted'));
744
        $em->flush();
745
746
        $routeParams = $this->getResourceParams($request);
747
        $routeParams['id'] = $parentId;
748
749
        return $this->redirectToRoute('chamilo_core_resource_list', $routeParams);
750
    }
751
752
    /**
753
     * Shows the associated resource file.
754
     *
755
     * @Route("/{tool}/{type}/{id}/view", methods={"GET"}, name="chamilo_core_resource_view")
756
     */
757
    public function viewAction(Request $request, Glide $glide): Response
758
    {
759
        $id = $request->get('id');
760
        $filter = $request->get('filter');
761
        $mode = $request->get('mode');
762
        $em = $this->getDoctrine();
763
        $resourceNode = $em->getRepository('ChamiloCoreBundle:Resource\ResourceNode')->find($id);
764
765
        if ($resourceNode === null) {
766
            throw new FileNotFoundException('Resource not found');
767
        }
768
769
        return $this->showFile($request, $resourceNode, $mode, $glide, $filter);
770
    }
771
772
    /**
773
     * Gets a document when calling route resources_document_get_file.
774
1     *
775
     * @deprecated
776
     *
777
     * @throws \League\Flysystem\FileNotFoundException
778
     */
779
    public function getDocumentAction(Request $request, Glide $glide): Response
780
    {
781
        /*$file = $request->get('file');
782
        $mode = $request->get('mode');
783
784
        // see list of filters in config/services.yaml
785
        $filter = $request->get('filter');
786
        $mode = !empty($mode) ? $mode : 'show';
787
788
        $repository = $this->getRepository('document', 'files');
789
        $nodeRepository = $repository->getResourceNodeRepository();
790
791
        $title = basename($file);
792
        // @todo improve criteria to avoid giving the wrong file.
793
        $criteria = ['slug' => $title];
794
795
        $resourceNode = $nodeRepository->findOneBy($criteria);
796
797
        if (null === $resourceNode) {
798
            throw new NotFoundHttpException();
799
        }
800
801
        return $this->showFile($request, $resourceNode, $mode, $glide,$filter);*/
802
    }
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...
803
804
    /**
805
     * @Route("/{tool}/{type}/{id}/download", methods={"GET"}, name="chamilo_core_resource_download")
806
     */
807
    public function downloadAction(Request $request)
808
    {
809
        $resourceNodeId = (int) $request->get('id');
810
        $courseNode = $this->getCourse()->getResourceNode();
811
812
        $repo = $this->getRepositoryFromRequest($request);
813
814
        if (empty($resourceNodeId)) {
815
            $resourceNode = $courseNode;
816
        } else {
817
            $resourceNode = $repo->getResourceNodeRepository()->find($resourceNodeId);
818
        }
819
820
        $type = $repo->getResourceType();
821
822
        if (null === $resourceNode) {
823
            throw new NotFoundHttpException();
824
        }
825
826
        $this->denyAccessUnlessGranted(
827
            ResourceNodeVoter::VIEW,
828
            $resourceNode,
829
            $this->trans('Unauthorised access to resource')
830
        );
831
832
        // If resource node has a file just download it. Don't download the children.
833
        if ($resourceNode->hasResourceFile()) {
834
            // Redirect to download single file.
835
            return $this->showFile($request, $resourceNode, 'download');
836
        }
837
838
        $zipName = $resourceNode->getSlug().'.zip';
839
        $rootNodePath = $resourceNode->getPathForDisplay();
840
841
        $resourceNodeRepo = $repo->getResourceNodeRepository();
842
843
        $criteria = Criteria::create()
844
            ->where(Criteria::expr()->neq('resourceFile', null)) // must have a file
845
           // ->andWhere(Criteria::expr()->eq('resourceType', $type))
846
        ;
847
848
        /** @var ArrayCollection|ResourceNode[] $children */
849
        /** @var QueryBuilder $children */
850
        $qb = $resourceNodeRepo->getChildrenQueryBuilder($resourceNode);
851
        $qb->addCriteria($criteria);
852
        $children = $qb->getQuery()->getResult();
853
854
        $response = new StreamedResponse(function () use ($rootNodePath, $zipName, $children, $repo) {
855
            // Define suitable options for ZipStream Archive.
856
            $options = new Archive();
857
            $options->setContentType('application/octet-stream');
858
            //initialise zipstream with output zip filename and options.
859
            $zip = new ZipStream($zipName, $options);
860
861
            /** @var ResourceNode $node */
862
            foreach ($children as $node) {
863
                $resourceFile = $node->getResourceFile();
864
                $systemName = $resourceFile->getFile()->getPathname();
865
                $stream = $repo->getResourceNodeFileStream($node);
866
                //error_log($node->getPathForDisplay());
867
                $fileToDisplay = str_replace($rootNodePath, '', $node->getPathForDisplay());
868
                $zip->addFileFromStream($fileToDisplay, $stream);
869
            }
870
            $zip->finish();
871
        });
872
873
        $disposition = $response->headers->makeDisposition(
874
            ResponseHeaderBag::DISPOSITION_ATTACHMENT,
875
            Transliterator::transliterate($zipName)
876
        );
877
        $response->headers->set('Content-Disposition', $disposition);
878
        $response->headers->set('Content-Type', 'application/octet-stream');
879
880
        return $response;
881
    }
882
883
    /**
884
     * Upload form.
885
     *
886
     * @Route("/{tool}/{type}/{id}/upload", name="chamilo_core_resource_upload", methods={"GET", "POST"},
887
     *                                      options={"expose"=true})
888
     */
889
    public function uploadAction(Request $request, $tool, $type, $id): Response
890
    {
891
        $repository = $this->getRepositoryFromRequest($request);
892
        $resourceNode = $repository->getResourceNodeRepository()->find($id);
893
894
        $this->denyAccessUnlessGranted(
895
            ResourceNodeVoter::EDIT,
896
            $resourceNode,
897
            $this->trans('Unauthorised access to resource')
898
        );
899
900
        $this->setBreadCrumb($request);
901
902
        $routeParams = $this->getResourceParams($request);
903
        $routeParams['tool'] = $tool;
904
        $routeParams['type'] = $type;
905
        $routeParams['id'] = $id;
906
907
        return $this->render(
908
            '@ChamiloTheme/Resource/upload.html.twig',
909
            $routeParams
910
        );
911
    }
912
913
    public function setBreadCrumb(Request $request)
914
    {
915
        $tool = $request->get('tool');
916
        $type = $request->get('type');
917
        $resourceNodeId = $request->get('id');
918
919
        $routeParams = $this->getResourceParams($request);
920
921
        if (!empty($resourceNodeId)) {
922
            $breadcrumb = $this->getBreadCrumb();
923
            $toolParams = $routeParams;
924
            $toolParams['id'] = null;
925
926
            // Root tool link
927
            $breadcrumb->addChild(
928
                $this->trans($tool),
929
                [
930
                    'uri' => $this->generateUrl(
931
                        'chamilo_core_resource_index',
932
                        $toolParams
933
                    ),
934
                ]
935
            );
936
937
            $repo = $this->getRepositoryFromRequest($request);
938
939
            /** @var AbstractResource $parent */
940
            $originalResource = $repo->findOneBy(['resourceNode' => $resourceNodeId]);
941
            if ($originalResource === null) {
942
                return;
943
            }
944
            $parent = $originalParent = $originalResource->getResourceNode();
945
946
            $parentList = [];
947
            while ($parent !== null) {
948
                if ($type !== $parent->getResourceType()->getName()) {
949
                    break;
950
                }
951
                $parent = $parent->getParent();
952
                if ($parent) {
953
                    $resource = $repo->findOneBy(['resourceNode' => $parent->getId()]);
954
                    if ($resource) {
955
                        $parentList[] = $resource;
956
                    }
957
                }
958
            }
959
960
            $parentList = array_reverse($parentList);
961
            /** @var AbstractResource $item */
962
            foreach ($parentList as $item) {
963
                $params = $routeParams;
964
                $params['id'] = $item->getResourceNode()->getId();
965
                $breadcrumb->addChild(
966
                    $item->getResourceName(),
967
                    [
968
                        'uri' => $this->generateUrl(
969
                            'chamilo_core_resource_list',
970
                            $params
971
                        ),
972
                    ]
973
                );
974
            }
975
976
            $params = $routeParams;
977
            $params['id'] = $originalParent->getId();
978
979
            $breadcrumb->addChild(
980
                $originalResource->getResourceName(),
0 ignored issues
show
Bug introduced by
The method getResourceName() does not exist on Chamilo\CoreBundle\Entit...source\AbstractResource. Did you maybe mean getResourceNode()? ( Ignorable by Annotation )

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

980
                $originalResource->/** @scrutinizer ignore-call */ 
981
                                   getResourceName(),

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
981
                [
982
                    'uri' => $this->generateUrl(
983
                        'chamilo_core_resource_list',
984
                        $params
985
                    ),
986
                ]
987
            );
988
        }
989
    }
990
991
    private function getParentResourceNode(Request $request): ResourceNode
992
    {
993
        $parentNodeId = $request->get('id');
994
995
        $parentResourceNode = null;
996
997
        if (empty($parentNodeId)) {
998
            if ($this->hasCourse()) {
999
                $parentResourceNode = $this->getCourse()->getResourceNode();
1000
            } else {
1001
                if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
1002
                    /** @var User $user */
1003
                    $parentResourceNode = $this->getUser()->getResourceNode();
1004
                }
1005
            }
1006
        } else {
1007
            $repo = $this->getDoctrine()->getRepository('ChamiloCoreBundle:Resource\ResourceNode');
1008
            $parentResourceNode = $repo->find($parentNodeId);
1009
        }
1010
1011
        if (null === $parentResourceNode) {
1012
            throw new AccessDeniedException();
1013
        }
1014
1015
        return $parentResourceNode;
1016
    }
1017
1018
    /**
1019
     * @param string $mode
1020
     * @param string $filter
1021
     *
1022
     * @return mixed|StreamedResponse
1023
     */
1024
    private function showFile(Request $request, ResourceNode $resourceNode, $mode = 'show', Glide $glide = null, $filter = '')
1025
    {
1026
        $this->denyAccessUnlessGranted(
1027
            ResourceNodeVoter::VIEW,
1028
            $resourceNode,
1029
            $this->trans('Unauthorised access to resource')
1030
        );
1031
1032
        $repo = $this->getRepositoryFromRequest($request);
1033
        $resourceFile = $resourceNode->getResourceFile();
1034
1035
        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...
1036
            throw new NotFoundHttpException($this->trans('File not found for resource'));
1037
        }
1038
1039
        //$fileName = $resourceFile->getOriginalName();
1040
        $fileName = $resourceNode->getSlug();
1041
        $filePath = $resourceFile->getFile()->getPathname();
1042
        $mimeType = $resourceFile->getMimeType();
1043
1044
        switch ($mode) {
1045
            case 'download':
1046
                $forceDownload = true;
1047
                break;
1048
            case 'show':
1049
            default:
1050
                $forceDownload = false;
1051
                // If it's an image then send it to Glide.
1052
                if (strpos($mimeType, 'image') !== false) {
1053
                    $server = $glide->getServer();
0 ignored issues
show
Bug introduced by
The method getServer() does not exist on null. ( Ignorable by Annotation )

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

1053
                    /** @scrutinizer ignore-call */ 
1054
                    $server = $glide->getServer();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
1054
                    $params = $request->query->all();
1055
1056
                    // The filter overwrites the params from get
1057
                    if (!empty($filter)) {
1058
                        $params = $glide->getFilters()[$filter] ?? [];
1059
                    }
1060
1061
                    // The image was cropped manually by the user, so we force to render this version,
1062
                    // no matter other crop parameters.
1063
                    $crop = $resourceFile->getCrop();
1064
                    if (!empty($crop)) {
1065
                        $params['crop'] = $crop;
1066
                    }
1067
1068
                    return $server->getImageResponse($filePath, $params);
1069
                }
1070
                break;
1071
        }
1072
1073
        $stream = $repo->getResourceNodeFileStream($resourceNode);
1074
1075
        //$stream = $this->fs->readStream($resourceNode);
1076
        $response = new StreamedResponse(function () use ($stream): void {
1077
            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

1077
            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

1077
            stream_copy_to_stream(/** @scrutinizer ignore-type */ $stream, fopen('php://output', 'wb'));
Loading history...
1078
        });
1079
        $disposition = $response->headers->makeDisposition(
1080
            $forceDownload ? ResponseHeaderBag::DISPOSITION_ATTACHMENT : ResponseHeaderBag::DISPOSITION_INLINE,
1081
            $fileName
1082
            //Transliterator::transliterate($fileName)
1083
        );
1084
        $response->headers->set('Content-Disposition', $disposition);
1085
        $response->headers->set('Content-Type', $mimeType ?: 'application/octet-stream');
1086
1087
        return $response;
1088
    }
1089
1090
    /**
1091
     * @param string $fileType
1092
     *
1093
     * @return RedirectResponse|Response
1094
     */
1095
    private function createResource(Request $request, $fileType = 'file')
1096
    {
1097
        $resourceNodeParentId = $request->get('id');
1098
1099
        $repository = $this->getRepositoryFromRequest($request);
1100
1101
        // Default parent node is course.
1102
        $parentNode = $this->getParentResourceNode($request);
1103
        //var_dump($parentNode->getPath());
1104
1105
        $this->denyAccessUnlessGranted(
1106
            ResourceNodeVoter::CREATE,
1107
            $parentNode,
1108
            $this->trans('Unauthorised access to resource')
1109
        );
1110
1111
        $form = $repository->getForm($this->container->get('form.factory'), null);
1112
1113
        if ($fileType === 'file') {
1114
            $resourceParams = $this->getResourceParams($request);
1115
            $form->add(
1116
                'content',
1117
                CKEditorType::class,
1118
                [
1119
                    'mapped' => false,
1120
                    'config' => [
1121
                        'filebrowserImageBrowseRoute' => 'resources_filemanager',
1122
                        'filebrowserImageBrowseRouteParameters' => $resourceParams,
1123
                        'fullPage' => true,
1124
                    ],
1125
                ]
1126
            );
1127
        }
1128
1129
        $form->handleRequest($request);
1130
        if ($form->isSubmitted() && $form->isValid()) {
1131
            $em = $this->getDoctrine()->getManager();
1132
1133
            $course = $this->getCourse();
1134
            $session = $this->getSession();
1135
1136
            /** @var AbstractResource $newResource */
1137
            $newResource = $repository->saveResource($form, $course, $session, $fileType);
1138
1139
            $file = null;
1140
            if ($fileType === 'file') {
1141
                $content = $form->get('content')->getViewData();
1142
                $newResource->setTitle($newResource->getTitle().'.html');
0 ignored issues
show
Bug introduced by
The method getTitle() does not exist on Chamilo\CoreBundle\Entit...source\AbstractResource. It seems like you code against a sub-type of Chamilo\CoreBundle\Entit...source\AbstractResource such as Chamilo\CoreBundle\Entity\Course or Chamilo\CourseBundle\Entity\CLink or Chamilo\CourseBundle\Entity\CAnnouncement or Chamilo\CourseBundle\Entity\CQuiz or Chamilo\CourseBundle\Entity\CDocument or Chamilo\CourseBundle\Entity\CQuizQuestionCategory. ( Ignorable by Annotation )

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

1142
                $newResource->setTitle($newResource->/** @scrutinizer ignore-call */ getTitle().'.html');
Loading history...
Bug introduced by
The method setTitle() does not exist on Chamilo\CoreBundle\Entit...source\AbstractResource. It seems like you code against a sub-type of Chamilo\CoreBundle\Entit...source\AbstractResource such as Chamilo\CoreBundle\Entity\Course or Chamilo\CourseBundle\Entity\CLink or Chamilo\CourseBundle\Entity\CAnnouncement or Chamilo\CourseBundle\Entity\CQuiz or Chamilo\CourseBundle\Entity\CDocument or Chamilo\CourseBundle\Entity\CQuizQuestionCategory. ( Ignorable by Annotation )

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

1142
                $newResource->/** @scrutinizer ignore-call */ 
1143
                              setTitle($newResource->getTitle().'.html');
Loading history...
1143
                $fileName = $newResource->getTitle();
1144
1145
                $handle = tmpfile();
1146
                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

1146
                fwrite(/** @scrutinizer ignore-type */ $handle, $content);
Loading history...
1147
                $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

1147
                $meta = stream_get_meta_data(/** @scrutinizer ignore-type */ $handle);
Loading history...
1148
                $file = new UploadedFile($meta['uri'], $fileName, 'text/html', null, true);
1149
                $em->persist($newResource);
1150
            }
1151
1152
            $resourceNode = $repository->createNodeForResource($newResource, $this->getUser(), $parentNode, $file);
1153
            $em->persist($resourceNode);
1154
1155
            $repository->addResourceNodeToCourse(
1156
                $resourceNode,
1157
                ResourceLink::VISIBILITY_PUBLISHED,
1158
                $course,
1159
                $session,
1160
                null
1161
            );
1162
1163
            $em->flush();
1164
1165
            // Loops all sharing options
1166
            /*foreach ($shareList as $share) {
1167
                $idList = [];
1168
                if (isset($share['search'])) {
1169
                    $idList = explode(',', $share['search']);
1170
                }
1171
1172
                $resourceRight = null;
1173
                if (isset($share['mask'])) {
1174
                    $resourceRight = new ResourceRight();
1175
                    $resourceRight
1176
                        ->setMask($share['mask'])
1177
                        ->setRole($share['role'])
1178
                    ;
1179
                }
1180
1181
                // Build links
1182
                switch ($share['sharing']) {
1183
                    case 'everyone':
1184
                        $repository->addResourceToEveryone(
1185
                            $resourceNode,
1186
                            $resourceRight
1187
                        );
1188
                        break;
1189
                    case 'course':
1190
                        $repository->addResourceToCourse(
1191
                            $resourceNode,
1192
                            $course,
1193
                            $resourceRight
1194
                        );
1195
                        break;
1196
                    case 'session':
1197
                        $repository->addResourceToSession(
1198
                            $resourceNode,
1199
                            $course,
1200
                            $session,
1201
                            $resourceRight
1202
                        );
1203
                        break;
1204
                    case 'user':
1205
                        // Only for me
1206
                        if (isset($share['only_me'])) {
1207
                            $repository->addResourceOnlyToMe($resourceNode);
1208
                        } else {
1209
                            // To other users
1210
                            $repository->addResourceToUserList($resourceNode, $idList);
1211
                        }
1212
                        break;
1213
                    case 'group':
1214
                        // @todo
1215
                        break;
1216
                }*/
1217
            //}
1218
            $em->flush();
1219
            $this->addFlash('success', $this->trans('Saved'));
1220
1221
            $params = $this->getResourceParams($request);
1222
            $params['id'] = $resourceNodeParentId;
1223
1224
            return $this->redirectToRoute(
1225
                'chamilo_core_resource_list',
1226
                $params
1227
            );
1228
        }
1229
1230
        switch ($fileType) {
1231
            case 'folder':
1232
                $template = '@ChamiloTheme/Resource/new_folder.html.twig';
1233
                break;
1234
            case 'file':
1235
                $template = '@ChamiloTheme/Resource/new.html.twig';
1236
                break;
1237
        }
1238
1239
        return $this->render(
1240
            $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...
1241
            [
1242
                'form' => $form->createView(),
1243
                'parent' => $resourceNodeParentId,
1244
                'file_type' => $fileType,
1245
            ]
1246
        );
1247
    }
1248
}
1249