Issues (3627)

bundles/AssetBundle/Controller/AssetController.php (1 issue)

1
<?php
2
3
/*
4
 * @copyright   2014 Mautic Contributors. All rights reserved
5
 * @author      Mautic
6
 *
7
 * @link        http://mautic.org
8
 *
9
 * @license     GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
10
 */
11
12
namespace Mautic\AssetBundle\Controller;
13
14
use Mautic\CoreBundle\Controller\FormController;
15
use Mautic\CoreBundle\Form\Type\DateRangeType;
16
use Mautic\CoreBundle\Helper\FileHelper;
17
use Symfony\Component\HttpFoundation\JsonResponse;
18
use Symfony\Component\HttpFoundation\Response;
19
20
class AssetController extends FormController
0 ignored issues
show
Deprecated Code introduced by
The class Mautic\CoreBundle\Controller\FormController has been deprecated: 2.3 - to be removed in 3.0; use AbstractFormController instead ( Ignorable by Annotation )

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

20
class AssetController extends /** @scrutinizer ignore-deprecated */ FormController
Loading history...
21
{
22
    /**
23
     * @param int $page
24
     *
25
     * @return JsonResponse|\Symfony\Component\HttpFoundation\Response
26
     */
27
    public function indexAction($page = 1)
28
    {
29
        $model = $this->getModel('asset');
30
31
        //set some permissions
32
        $permissions = $this->get('mautic.security')->isGranted([
33
            'asset:assets:viewown',
34
            'asset:assets:viewother',
35
            'asset:assets:create',
36
            'asset:assets:editown',
37
            'asset:assets:editother',
38
            'asset:assets:deleteown',
39
            'asset:assets:deleteother',
40
            'asset:assets:publishown',
41
            'asset:assets:publishother',
42
        ], 'RETURN_ARRAY');
43
44
        if (!$permissions['asset:assets:viewown'] && !$permissions['asset:assets:viewother']) {
45
            return $this->accessDenied();
46
        }
47
48
        if ('POST' == $this->request->getMethod()) {
49
            $this->setListFilters();
50
        }
51
52
        //set limits
53
        $limit = $this->get('session')->get('mautic.asset.limit', $this->get('mautic.helper.core_parameters')->get('default_assetlimit'));
54
        $start = (1 === $page) ? 0 : (($page - 1) * $limit);
55
        if ($start < 0) {
56
            $start = 0;
57
        }
58
59
        $search = $this->request->get('search', $this->get('session')->get('mautic.asset.filter', ''));
60
        $this->get('session')->set('mautic.asset.filter', $search);
61
62
        $filter = ['string' => $search, 'force' => []];
63
64
        if (!$permissions['asset:assets:viewother']) {
65
            $filter['force'][] =
66
                ['column' => 'a.createdBy', 'expr' => 'eq', 'value' => $this->user->getId()];
67
        }
68
69
        $orderBy    = $this->get('session')->get('mautic.asset.orderby', 'a.title');
70
        $orderByDir = $this->get('session')->get('mautic.asset.orderbydir', 'DESC');
71
72
        $assets = $model->getEntities(
73
            [
74
                'start'      => $start,
75
                'limit'      => $limit,
76
                'filter'     => $filter,
77
                'orderBy'    => $orderBy,
78
                'orderByDir' => $orderByDir,
79
            ]
80
        );
81
82
        $count = count($assets);
83
        if ($count && $count < ($start + 1)) {
84
            //the number of entities are now less then the current asset so redirect to the last asset
85
            if (1 === $count) {
86
                $lastPage = 1;
87
            } else {
88
                $lastPage = (ceil($count / $limit)) ?: 1;
89
            }
90
            $this->get('session')->set('mautic.asset.asset', $lastPage);
91
            $returnUrl = $this->generateUrl('mautic_asset_index', ['page' => $lastPage]);
92
93
            return $this->postActionRedirect([
94
                'returnUrl'       => $returnUrl,
95
                'viewParameters'  => ['asset' => $lastPage],
96
                'contentTemplate' => 'MauticAssetBundle:Asset:index',
97
                'passthroughVars' => [
98
                    'activeLink'    => '#mautic_asset_index',
99
                    'mauticContent' => 'asset',
100
                ],
101
            ]);
102
        }
103
104
        //set what asset currently on so that we can return here after form submission/cancellation
105
        $this->get('session')->set('mautic.asset.page', $page);
106
107
        $tmpl = $this->request->isXmlHttpRequest() ? $this->request->get('tmpl', 'index') : 'index';
108
109
        //retrieve a list of categories
110
        $categories = $this->getModel('asset')->getLookupResults('category', '', 0);
111
112
        return $this->delegateView([
113
            'viewParameters' => [
114
                'searchValue' => $search,
115
                'items'       => $assets,
116
                'categories'  => $categories,
117
                'limit'       => $limit,
118
                'permissions' => $permissions,
119
                'model'       => $model,
120
                'tmpl'        => $tmpl,
121
                'page'        => $page,
122
                'security'    => $this->get('mautic.security'),
123
            ],
124
            'contentTemplate' => 'MauticAssetBundle:Asset:list.html.php',
125
            'passthroughVars' => [
126
                'activeLink'    => '#mautic_asset_index',
127
                'mauticContent' => 'asset',
128
                'route'         => $this->generateUrl('mautic_asset_index', ['page' => $page]),
129
            ],
130
        ]);
131
    }
132
133
    /**
134
     * Loads a specific form into the detailed panel.
135
     *
136
     * @param int $objectId
137
     *
138
     * @return JsonResponse|\Symfony\Component\HttpFoundation\Response
139
     */
140
    public function viewAction($objectId)
141
    {
142
        $model       = $this->getModel('asset');
143
        $security    = $this->get('mautic.security');
144
        $activeAsset = $model->getEntity($objectId);
145
146
        //set the asset we came from
147
        $page = $this->get('session')->get('mautic.asset.page', 1);
148
149
        $tmpl = $this->request->isXmlHttpRequest() ? $this->request->get('tmpl', 'details') : 'details';
150
151
        // Init the date range filter form
152
        $dateRangeValues = $this->request->get('daterange', []);
153
        $action          = $this->generateUrl('mautic_asset_action', ['objectAction' => 'view', 'objectId' => $objectId]);
154
        $dateRangeForm   = $this->get('form.factory')->create(DateRangeType::class, $dateRangeValues, ['action' => $action]);
155
156
        if (null === $activeAsset) {
157
            //set the return URL
158
            $returnUrl = $this->generateUrl('mautic_asset_index', ['page' => $page]);
159
160
            return $this->postActionRedirect([
161
                'returnUrl'       => $returnUrl,
162
                'viewParameters'  => ['page' => $page],
163
                'contentTemplate' => 'MauticAssetBundle:Asset:index',
164
                'passthroughVars' => [
165
                    'activeLink'    => '#mautic_asset_index',
166
                    'mauticContent' => 'asset',
167
                ],
168
                'flashes' => [
169
                    [
170
                        'type'    => 'error',
171
                        'msg'     => 'mautic.asset.asset.error.notfound',
172
                        'msgVars' => ['%id%' => $objectId],
173
                    ],
174
                ],
175
            ]);
176
        } elseif (!$this->get('mautic.security')->hasEntityAccess('asset:assets:viewown', 'asset:assets:viewother', $activeAsset->getCreatedBy())) {
177
            return $this->accessDenied();
178
        }
179
180
        // Audit Log
181
        $logs = $this->getModel('core.auditlog')->getLogForObject('asset', $activeAsset->getId(), $activeAsset->getDateAdded());
182
183
        return $this->delegateView([
184
            'returnUrl'      => $action,
185
            'viewParameters' => [
186
                'activeAsset' => $activeAsset,
187
                'tmpl'        => $tmpl,
188
                'permissions' => $security->isGranted([
189
                    'asset:assets:viewown',
190
                    'asset:assets:viewother',
191
                    'asset:assets:create',
192
                    'asset:assets:editown',
193
                    'asset:assets:editother',
194
                    'asset:assets:deleteown',
195
                    'asset:assets:deleteother',
196
                    'asset:assets:publishown',
197
                    'asset:assets:publishother',
198
                ], 'RETURN_ARRAY'),
199
                'stats' => [
200
                    'downloads' => [
201
                        'total'     => $activeAsset->getDownloadCount(),
202
                        'unique'    => $activeAsset->getUniqueDownloadCount(),
203
                        'timeStats' => $model->getDownloadsLineChartData(
204
                            null,
205
                            new \DateTime($dateRangeForm->get('date_from')->getData()),
206
                            new \DateTime($dateRangeForm->get('date_to')->getData()),
207
                            null,
208
                            ['asset_id' => $activeAsset->getId()]
209
                        ),
210
                    ],
211
                ],
212
                'security'         => $security,
213
                'assetDownloadUrl' => $model->generateUrl($activeAsset, true),
214
                'logs'             => $logs,
215
                'dateRangeForm'    => $dateRangeForm->createView(),
216
            ],
217
            'contentTemplate' => 'MauticAssetBundle:Asset:'.$tmpl.'.html.php',
218
            'passthroughVars' => [
219
                'activeLink'    => '#mautic_asset_index',
220
                'mauticContent' => 'asset',
221
            ],
222
        ]);
223
    }
224
225
    /**
226
     * Show a preview of the file.
227
     *
228
     * @param $objectId
229
     *
230
     * @return JsonResponse|\Symfony\Component\HttpFoundation\Response
231
     */
232
    public function previewAction($objectId)
233
    {
234
        /** @var \Mautic\AssetBundle\Model\AssetModel $model */
235
        $model       = $this->getModel('asset');
236
        $activeAsset = $model->getEntity($objectId);
237
238
        if (null === $activeAsset || !$this->get('mautic.security')->hasEntityAccess('asset:assets:viewown', 'asset:assets:viewother', $activeAsset->getCreatedBy())) {
239
            return $this->modalAccessDenied();
240
        }
241
242
        $download = $this->request->query->get('download', 0);
243
        $stream   = $this->request->query->get('stream', 0);
244
245
        if ('1' === $download || '1' === $stream) {
246
            try {
247
                //set the uploadDir
248
                $activeAsset->setUploadDir($this->get('mautic.helper.core_parameters')->get('upload_dir'));
249
                $contents = $activeAsset->getFileContents();
250
            } catch (\Exception $e) {
251
                return $this->notFound();
252
            }
253
254
            $response = new Response();
255
            $response->headers->set('Content-Type', $activeAsset->getFileMimeType());
256
            if ('1' === $download) {
257
                $response->headers->set('Content-Disposition', 'attachment;filename="'.$activeAsset->getOriginalFileName());
258
            }
259
            $response->setContent($contents);
260
261
            return $response;
262
        }
263
264
        return $this->delegateView([
265
            'viewParameters' => [
266
                'activeAsset'      => $activeAsset,
267
                'assetDownloadUrl' => $model->generateUrl($activeAsset),
268
            ],
269
            'contentTemplate' => 'MauticAssetBundle:Asset:preview.html.php',
270
            'passthroughVars' => [
271
                'route' => false,
272
            ],
273
        ]);
274
    }
275
276
    /**
277
     * Generates new form and processes post data.
278
     *
279
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
280
     */
281
    public function newAction($entity = null)
282
    {
283
        /** @var \Mautic\AssetBundle\Model\AssetModel $model */
284
        $model = $this->getModel('asset');
285
286
        /** @var \Mautic\AssetBundle\Entity\Asset $entity */
287
        if (null == $entity) {
288
            $entity = $model->getEntity();
289
        }
290
291
        $entity->setMaxSize(FileHelper::convertMegabytesToBytes($this->get('mautic.helper.core_parameters')->get('max_size')));
292
293
        $method  = $this->request->getMethod();
294
        $session = $this->get('session');
295
296
        if (!$this->get('mautic.security')->isGranted('asset:assets:create')) {
297
            return $this->accessDenied();
298
        }
299
300
        $maxSize    = $model->getMaxUploadSize();
301
        $extensions = '.'.implode(', .', $this->get('mautic.helper.core_parameters')->get('allowed_extensions'));
302
303
        $maxSizeError = $this->get('translator')->trans('mautic.asset.asset.error.file.size', [
304
            '%fileSize%' => '{{filesize}}',
305
            '%maxSize%'  => '{{maxFilesize}}',
306
        ], 'validators');
307
308
        $extensionError = $this->get('translator')->trans('mautic.asset.asset.error.file.extension.js', [
309
            '%extensions%' => $extensions,
310
        ], 'validators');
311
312
        // Create temporary asset ID
313
        $asset  = $this->request->request->get('asset', []);
314
        $tempId = 'POST' === $method ? ($asset['tempId'] ?? '') : uniqid('tmp_');
315
        $entity->setTempId($tempId);
316
317
        // Set the page we came from
318
        $page   = $session->get('mautic.asset.page', 1);
319
        $action = $this->generateUrl('mautic_asset_action', ['objectAction' => 'new']);
320
321
        // Get upload folder
322
        $uploaderHelper = $this->container->get('oneup_uploader.templating.uploader_helper');
323
        $uploadEndpoint = $uploaderHelper->endpoint('asset');
324
325
        //create the form
326
        $form = $model->createForm($entity, $this->get('form.factory'), $action);
327
328
        ///Check for a submitted form and process it
329
        if ('POST' == $method) {
330
            $valid = false;
331
            if (!$cancelled = $this->isFormCancelled($form)) {
332
                if ($valid = $this->isFormValid($form)) {
333
                    $entity->setUploadDir($this->get('mautic.helper.core_parameters')->get('upload_dir'));
334
                    $entity->preUpload();
335
                    $entity->upload();
336
337
                    //form is valid so process the data
338
                    $model->saveEntity($entity);
339
340
                    //remove the asset from request
341
                    $this->request->files->remove('asset');
342
343
                    $this->addFlash('mautic.core.notice.created', [
344
                        '%name%'      => $entity->getTitle(),
345
                        '%menu_link%' => 'mautic_asset_index',
346
                        '%url%'       => $this->generateUrl('mautic_asset_action', [
347
                            'objectAction' => 'edit',
348
                            'objectId'     => $entity->getId(),
349
                        ]),
350
                    ]);
351
352
                    if (!$form->get('buttons')->get('save')->isClicked()) {
353
                        //return edit view so that all the session stuff is loaded
354
                        return $this->editAction($entity->getId(), true);
355
                    }
356
357
                    $viewParameters = [
358
                        'objectAction' => 'view',
359
                        'objectId'     => $entity->getId(),
360
                    ];
361
                    $returnUrl = $this->generateUrl('mautic_asset_action', $viewParameters);
362
                    $template  = 'MauticAssetBundle:Asset:view';
363
                }
364
            } else {
365
                $viewParameters = ['page' => $page];
366
                $returnUrl      = $this->generateUrl('mautic_asset_index', $viewParameters);
367
                $template       = 'MauticAssetBundle:Asset:index';
368
            }
369
370
            if ($cancelled || ($valid && $form->get('buttons')->get('save')->isClicked())) {
371
                return $this->postActionRedirect([
372
                    'returnUrl'       => $returnUrl,
373
                    'viewParameters'  => $viewParameters,
374
                    'contentTemplate' => $template,
375
                    'passthroughVars' => [
376
                        'activeLink'    => 'mautic_asset_index',
377
                        'mauticContent' => 'asset',
378
                    ],
379
                ]);
380
            }
381
        }
382
383
        // Check for integrations to cloud providers
384
        /** @var \Mautic\PluginBundle\Helper\IntegrationHelper $integrationHelper */
385
        $integrationHelper = $this->factory->getHelper('integration');
386
387
        $integrations = $integrationHelper->getIntegrationObjects(null, ['cloud_storage']);
388
389
        return $this->delegateView([
390
            'viewParameters' => [
391
                'form'             => $form->createView(),
392
                'activeAsset'      => $entity,
393
                'assetDownloadUrl' => $model->generateUrl($entity),
394
                'integrations'     => $integrations,
395
                'startOnLocal'     => $entity->isLocal(),
396
                'uploadEndpoint'   => $uploadEndpoint,
397
                'maxSize'          => $maxSize,
398
                'maxSizeError'     => $maxSizeError,
399
                'extensions'       => $extensions,
400
                'extensionError'   => $extensionError,
401
            ],
402
            'contentTemplate' => 'MauticAssetBundle:Asset:form.html.php',
403
            'passthroughVars' => [
404
                'activeLink'    => '#mautic_asset_index',
405
                'mauticContent' => 'asset',
406
                'route'         => $this->generateUrl('mautic_asset_action', [
407
                    'objectAction' => 'new',
408
                ]),
409
            ],
410
        ]);
411
    }
412
413
    /**
414
     * Generates edit form and processes post data.
415
     *
416
     * @param int  $objectId
417
     * @param bool $ignorePost
418
     *
419
     * @return JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
420
     */
421
    public function editAction($objectId, $ignorePost = false)
422
    {
423
        /** @var \Mautic\AssetBundle\Model\AssetModel $model */
424
        $model  = $this->getModel('asset');
425
        $entity = $model->getEntity($objectId);
426
427
        $entity->setMaxSize(FileHelper::convertMegabytesToBytes($this->get('mautic.helper.core_parameters')->get('max_size')));
428
429
        $session    = $this->get('session');
430
        $page       = $session->get('mautic.asset.page', 1);
431
        $method     = $this->request->getMethod();
432
        $maxSize    = $model->getMaxUploadSize();
433
        $extensions = '.'.implode(', .', $this->get('mautic.helper.core_parameters')->get('allowed_extensions'));
434
435
        $maxSizeError = $this->get('translator')->trans('mautic.asset.asset.error.file.size', [
436
            '%fileSize%' => '{{filesize}}',
437
            '%maxSize%'  => '{{maxFilesize}}',
438
        ], 'validators');
439
440
        $extensionError = $this->get('translator')->trans('mautic.asset.asset.error.file.extension.js', [
441
            '%extensions%' => $extensions,
442
        ], 'validators');
443
444
        //set the return URL
445
        $returnUrl = $this->generateUrl('mautic_asset_index', ['page' => $page]);
446
447
        // Get upload folder
448
        $uploaderHelper = $this->container->get('oneup_uploader.templating.uploader_helper');
449
        $uploadEndpoint = $uploaderHelper->endpoint('asset');
450
451
        $postActionVars = [
452
            'returnUrl'       => $returnUrl,
453
            'viewParameters'  => ['page' => $page],
454
            'contentTemplate' => 'MauticAssetBundle:Asset:index',
455
            'passthroughVars' => [
456
                'activeLink'    => 'mautic_asset_index',
457
                'mauticContent' => 'asset',
458
            ],
459
        ];
460
461
        //not found
462
        if (null === $entity) {
463
            return $this->postActionRedirect(
464
                array_merge($postActionVars, [
465
                    'flashes' => [
466
                        [
467
                            'type'    => 'error',
468
                            'msg'     => 'mautic.asset.asset.error.notfound',
469
                            'msgVars' => ['%id%' => $objectId],
470
                        ],
471
                    ],
472
                ])
473
            );
474
        } elseif (!$this->get('mautic.security')->hasEntityAccess(
475
            'asset:assets:viewown', 'asset:assets:viewother', $entity->getCreatedBy()
476
        )
477
        ) {
478
            return $this->accessDenied();
479
        } elseif ($model->isLocked($entity)) {
480
            //deny access if the entity is locked
481
            return $this->isLocked($postActionVars, $entity, 'asset.asset');
482
        }
483
484
        // Create temporary asset ID
485
        $asset  = $this->request->request->get('asset', []);
486
        $tempId = 'POST' === $method ? ($asset['tempId'] ?? '') : uniqid('tmp_');
487
        $entity->setTempId($tempId);
488
489
        //Create the form
490
        $action = $this->generateUrl('mautic_asset_action', ['objectAction' => 'edit', 'objectId' => $objectId]);
491
        $form   = $model->createForm($entity, $this->get('form.factory'), $action);
492
493
        ///Check for a submitted form and process it
494
        if (!$ignorePost && 'POST' == $method) {
495
            $valid = false;
496
            if (!$cancelled = $this->isFormCancelled($form)) {
497
                if ($valid = $this->isFormValid($form)) {
498
                    $entity->setUploadDir($this->get('mautic.helper.core_parameters')->get('upload_dir'));
499
                    $entity->preUpload();
500
                    $entity->upload();
501
502
                    //form is valid so process the data
503
                    $model->saveEntity($entity, $form->get('buttons')->get('save')->isClicked());
504
505
                    //remove the asset from request
506
                    $this->request->files->remove('asset');
507
508
                    $this->addFlash('mautic.core.notice.updated', [
509
                        '%name%'      => $entity->getTitle(),
510
                        '%menu_link%' => 'mautic_asset_index',
511
                        '%url%'       => $this->generateUrl('mautic_asset_action', [
512
                            'objectAction' => 'edit',
513
                            'objectId'     => $entity->getId(),
514
                        ]),
515
                    ]);
516
517
                    $returnUrl = $this->generateUrl('mautic_asset_action', [
518
                        'objectAction' => 'view',
519
                        'objectId'     => $entity->getId(),
520
                    ]);
521
                    $viewParams = ['objectId' => $entity->getId()];
522
                    $template   = 'MauticAssetBundle:Asset:view';
523
                }
524
            } else {
525
                //clear any modified content
526
                $session->remove('mautic.asestbuilder.'.$objectId.'.content');
527
                //unlock the entity
528
                $model->unlockEntity($entity);
529
530
                $returnUrl  = $this->generateUrl('mautic_asset_index', ['page' => $page]);
531
                $viewParams = ['page' => $page];
532
                $template   = 'MauticAssetBundle:Asset:index';
533
            }
534
535
            if ($cancelled || ($valid && $form->get('buttons')->get('save')->isClicked())) {
536
                return $this->postActionRedirect(
537
                    array_merge($postActionVars, [
538
                        'returnUrl'       => $returnUrl,
539
                        'viewParameters'  => $viewParams,
540
                        'contentTemplate' => $template,
541
                    ])
542
                );
543
            }
544
        } else {
545
            //lock the entity
546
            $model->lockEntity($entity);
547
        }
548
549
        // Check for integrations to cloud providers
550
        /** @var \Mautic\PluginBundle\Helper\IntegrationHelper $integrationHelper */
551
        $integrationHelper = $this->factory->getHelper('integration');
552
553
        $integrations = $integrationHelper->getIntegrationObjects(null, ['cloud_storage']);
554
555
        return $this->delegateView([
556
            'viewParameters' => [
557
                'form'             => $form->createView(),
558
                'activeAsset'      => $entity,
559
                'assetDownloadUrl' => $model->generateUrl($entity),
560
                'integrations'     => $integrations,
561
                'startOnLocal'     => $entity->isLocal(),
562
                'uploadEndpoint'   => $uploadEndpoint,
563
                'maxSize'          => $maxSize,
564
                'maxSizeError'     => $maxSizeError,
565
                'extensions'       => $extensions,
566
                'extensionError'   => $extensionError,
567
            ],
568
            'contentTemplate' => 'MauticAssetBundle:Asset:form.html.php',
569
            'passthroughVars' => [
570
                'activeLink'    => '#mautic_asset_index',
571
                'mauticContent' => 'asset',
572
                'route'         => $this->generateUrl('mautic_asset_action', [
573
                    'objectAction' => 'edit',
574
                    'objectId'     => $entity->getId(),
575
                ]),
576
            ],
577
        ]);
578
    }
579
580
    /**
581
     * Clone an entity.
582
     *
583
     * @param int $objectId
584
     *
585
     * @return JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse|Response
586
     */
587
    public function cloneAction($objectId)
588
    {
589
        /** @var \Mautic\AssetBundle\Model\AssetModel $model */
590
        $model  = $this->getModel('asset');
591
        $entity = $model->getEntity($objectId);
592
593
        if (null != $entity) {
594
            if (!$this->get('mautic.security')->isGranted('asset:assets:create') ||
595
                !$this->get('mautic.security')->hasEntityAccess(
596
                    'asset:assets:viewown', 'asset:assets:viewother', $entity->getCreatedBy()
597
                )
598
            ) {
599
                return $this->accessDenied();
600
            }
601
602
            $clone = clone $entity;
603
            $clone->setDownloadCount(0);
604
            $clone->setUniqueDownloadCount(0);
605
            $clone->setRevision(0);
606
            $clone->setIsPublished(false);
607
        }
608
609
        return $this->newAction($clone);
610
    }
611
612
    /**
613
     * Deletes the entity.
614
     *
615
     * @param int $objectId
616
     *
617
     * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse
618
     */
619
    public function deleteAction($objectId)
620
    {
621
        $page      = $this->get('session')->get('mautic.asset.page', 1);
622
        $returnUrl = $this->generateUrl('mautic_asset_index', ['page' => $page]);
623
        $flashes   = [];
624
625
        $postActionVars = [
626
            'returnUrl'       => $returnUrl,
627
            'viewParameters'  => ['page' => $page],
628
            'contentTemplate' => 'MauticAssetBundle:Asset:index',
629
            'passthroughVars' => [
630
                'activeLink'    => 'mautic_asset_index',
631
                'mauticContent' => 'asset',
632
            ],
633
        ];
634
635
        if ('POST' == $this->request->getMethod()) {
636
            /** @var \Mautic\AssetBundle\Model\AssetModel $model */
637
            $model  = $this->getModel('asset');
638
            $entity = $model->getEntity($objectId);
639
640
            if (null === $entity) {
641
                $flashes[] = [
642
                    'type'    => 'error',
643
                    'msg'     => 'mautic.asset.asset.error.notfound',
644
                    'msgVars' => ['%id%' => $objectId],
645
                ];
646
            } elseif (!$this->get('mautic.security')->hasEntityAccess(
647
                'asset:assets:deleteown',
648
                'asset:assets:deleteother',
649
                $entity->getCreatedBy()
650
            )
651
            ) {
652
                return $this->accessDenied();
653
            } elseif ($model->isLocked($entity)) {
654
                return $this->isLocked($postActionVars, $entity, 'asset.asset');
655
            }
656
657
            $entity->removeUpload();
658
            $model->deleteEntity($entity);
659
660
            $flashes[] = [
661
                'type'    => 'notice',
662
                'msg'     => 'mautic.core.notice.deleted',
663
                'msgVars' => [
664
                    '%name%' => $entity->getTitle(),
665
                    '%id%'   => $objectId,
666
                ],
667
            ];
668
        } //else don't do anything
669
670
        return $this->postActionRedirect(
671
            array_merge($postActionVars, [
672
                'flashes' => $flashes,
673
            ])
674
        );
675
    }
676
677
    /**
678
     * Deletes a group of entities.
679
     *
680
     * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse
681
     */
682
    public function batchDeleteAction()
683
    {
684
        $page      = $this->get('session')->get('mautic.asset.page', 1);
685
        $returnUrl = $this->generateUrl('mautic_asset_index', ['page' => $page]);
686
        $flashes   = [];
687
688
        $postActionVars = [
689
            'returnUrl'       => $returnUrl,
690
            'viewParameters'  => ['page' => $page],
691
            'contentTemplate' => 'MauticAssetBundle:Asset:index',
692
            'passthroughVars' => [
693
                'activeLink'    => 'mautic_asset_index',
694
                'mauticContent' => 'asset',
695
            ],
696
        ];
697
698
        if ('POST' == $this->request->getMethod()) {
699
            /** @var \Mautic\AssetBundle\Model\AssetModel $model */
700
            $model     = $this->getModel('asset');
701
            $ids       = json_decode($this->request->query->get('ids', '{}'));
702
            $deleteIds = [];
703
704
            // Loop over the IDs to perform access checks pre-delete
705
            foreach ($ids as $objectId) {
706
                $entity = $model->getEntity($objectId);
707
708
                if (null === $entity) {
709
                    $flashes[] = [
710
                        'type'    => 'error',
711
                        'msg'     => 'mautic.asset.asset.error.notfound',
712
                        'msgVars' => ['%id%' => $objectId],
713
                    ];
714
                } elseif (!$this->get('mautic.security')->hasEntityAccess(
715
                    'asset:assets:deleteown', 'asset:assets:deleteother', $entity->getCreatedBy()
716
                )
717
                ) {
718
                    $flashes[] = $this->accessDenied(true);
719
                } elseif ($model->isLocked($entity)) {
720
                    $flashes[] = $this->isLocked($postActionVars, $entity, 'asset', true);
721
                } else {
722
                    $deleteIds[] = $objectId;
723
                }
724
            }
725
726
            // Delete everything we are able to
727
            if (!empty($deleteIds)) {
728
                $entities = $model->deleteEntities($deleteIds);
729
730
                $flashes[] = [
731
                    'type'    => 'notice',
732
                    'msg'     => 'mautic.asset.asset.notice.batch_deleted',
733
                    'msgVars' => [
734
                        '%count%' => count($entities),
735
                    ],
736
                ];
737
            }
738
        } //else don't do anything
739
740
        return $this->postActionRedirect(
741
            array_merge($postActionVars, [
742
                'flashes' => $flashes,
743
            ])
744
        );
745
    }
746
747
    /**
748
     * Renders the container for the remote file browser.
749
     *
750
     * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse
751
     */
752
    public function remoteAction()
753
    {
754
        // Check for integrations to cloud providers
755
        /** @var \Mautic\PluginBundle\Helper\IntegrationHelper $integrationHelper */
756
        $integrationHelper = $this->factory->getHelper('integration');
757
758
        $integrations = $integrationHelper->getIntegrationObjects(null, ['cloud_storage']);
759
760
        $tmpl = $this->request->isXmlHttpRequest() ? $this->request->get('tmpl', 'index') : 'index';
761
762
        return $this->delegateView([
763
            'viewParameters' => [
764
                'integrations' => $integrations,
765
                'tmpl'         => $tmpl,
766
            ],
767
            'contentTemplate' => 'MauticAssetBundle:Remote:browse.html.php',
768
            'passthroughVars' => [
769
                'activeLink'    => '#mautic_asset_index',
770
                'mauticContent' => 'asset',
771
                'route'         => $this->generateUrl('mautic_asset_index', ['page' => $this->get('session')->get('mautic.asset.page', 1)]),
772
            ],
773
        ]);
774
    }
775
}
776