Completed
Pull Request — 5.0 (#2103)
by Kevin
10:13
created

MediaBundle/Controller/MediaController.php (3 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace Kunstmaan\MediaBundle\Controller;
4
5
use Exception;
6
use Kunstmaan\AdminBundle\FlashMessages\FlashTypes;
7
use Kunstmaan\MediaBundle\Entity\Folder;
8
use Kunstmaan\MediaBundle\Entity\Media;
9
use Kunstmaan\MediaBundle\Helper\MediaManager;
10
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
11
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
12
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
13
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
14
use Symfony\Component\HttpFoundation\File\File;
15
use Symfony\Component\HttpFoundation\JsonResponse;
16
use Symfony\Component\HttpFoundation\RedirectResponse;
17
use Symfony\Component\HttpFoundation\Request;
18
use Symfony\Component\HttpFoundation\Response;
19
20
/**
21
 * MediaController
22
 */
23
class MediaController extends Controller
24
{
25
26
    /**
27
     * @param Request $request
28
     * @param int     $mediaId
29
     *
30
     * @Route("/{mediaId}", requirements={"mediaId" = "\d+"}, name="KunstmaanMediaBundle_media_show")
31
     *
32
     * @return Response
33
     */
34
    public function showAction(Request $request, $mediaId)
35
    {
36
        $em = $this->getDoctrine()->getManager();
37
38
        /* @var Media $media */
39
        $media  = $em->getRepository('KunstmaanMediaBundle:Media')->getMedia($mediaId);
40
        $folder = $media->getFolder();
41
42
        /* @var MediaManager $mediaManager */
43
        $mediaManager = $this->get('kunstmaan_media.media_manager');
44
        $handler      = $mediaManager->getHandler($media);
45
        $helper       = $handler->getFormHelper($media);
46
47
        $form = $this->createForm($handler->getFormType(), $helper, $handler->getFormTypeOptions());
48
49
        if ($request->isMethod('POST')) {
50
            $form->handleRequest($request);
51
            if ($form->isSubmitted() && $form->isValid()) {
52
                $media = $helper->getMedia();
53
                $em->getRepository('KunstmaanMediaBundle:Media')->save($media);
54
55
                return new RedirectResponse($this->generateUrl(
56
                    'KunstmaanMediaBundle_media_show',
57
                    ['mediaId' => $media->getId()]
58
                ));
59
            }
60
        }
61
        $showTemplate = $mediaManager->getHandler($media)->getShowTemplate($media);
62
63
        return $this->render(
64
            $showTemplate, [
65
                'handler'      => $handler,
66
                'foldermanager' => $this->get('kunstmaan_media.folder_manager'),
67
                'mediamanager' => $this->get('kunstmaan_media.media_manager'),
68
                'editform'     => $form->createView(),
69
                'media'        => $media,
70
                'helper'       => $helper,
71
                'folder'       => $folder
72
            ]
73
        );
74
    }
75
76
    /**
77
     * @param Request $request
78
     * @param int     $mediaId
79
     *
80
     * @Route("/delete/{mediaId}", requirements={"mediaId" = "\d+"}, name="KunstmaanMediaBundle_media_delete")
81
     *
82
     * @return RedirectResponse
83
     */
84
    public function deleteAction(Request $request, $mediaId)
85
    {
86
        $em = $this->getDoctrine()->getManager();
87
88
        /* @var Media $media */
89
        $media     = $em->getRepository('KunstmaanMediaBundle:Media')->getMedia($mediaId);
90
        $medianame = $media->getName();
91
        $folder    = $media->getFolder();
92
93
        $em->getRepository('KunstmaanMediaBundle:Media')->delete($media);
94
95
        $this->addFlash(
96
            FlashTypes::SUCCESS,
97
            $this->get('translator')->trans('kuma_admin.media.flash.deleted_success.%medianame%', [
98
                '%medianame%' => $medianame
99
            ])
100
        );
101
102
        // If the redirect url is passed via the url we use it
103
        $redirectUrl = $request->query->get('redirectUrl');
104
        if (empty($redirectUrl) || (\strpos($redirectUrl, $request->getSchemeAndHttpHost()) !== 0 && \strpos($redirectUrl, '/') !== 0)) {
105
            $redirectUrl = $this->generateUrl(
106
                'KunstmaanMediaBundle_folder_show',
107
                ['folderId' => $folder->getId()]
108
            );
109
        }
110
111
        return new RedirectResponse($redirectUrl);
112
    }
113
114
    /**
115
     * @param int $folderId
116
     *
117
     * @Route("bulkupload/{folderId}", requirements={"folderId" = "\d+"}, name="KunstmaanMediaBundle_media_bulk_upload")
118
     * @Template()
119
     *
120
     * @return array|RedirectResponse
121
     */
122
    public function bulkUploadAction($folderId)
123
    {
124
        $em = $this->getDoctrine()->getManager();
125
126
        /* @var Folder $folder */
127
        $folder = $em->getRepository('KunstmaanMediaBundle:Folder')->getFolder($folderId);
128
129
        return ['folder' => $folder];
130
    }
131
132
    /**
133
     * @param Request $request
134
     * @param int     $folderId
135
     *
136
     * @Route("bulkuploadsubmit/{folderId}", requirements={"folderId" = "\d+"}, name="KunstmaanMediaBundle_media_bulk_upload_submit")
137
     * @Template()
138
     *
139
     * @return JsonResponse
140
     */
141
    public function bulkUploadSubmitAction(Request $request, $folderId)
142
    {
143
        // Settings
144
        if (\ini_get('upload_tmp_dir')) {
145
            $tempDir = \ini_get('upload_tmp_dir');
146
        } else {
147
            $tempDir = \sys_get_temp_dir();
148
        }
149
        $targetDir        = \rtrim($tempDir, '/') . DIRECTORY_SEPARATOR . 'plupload';
150
        $cleanupTargetDir = true; // Remove old files
151
        $maxFileAge       = 5 * 60 * 60; // Temp file age in seconds
152
153
        // Create target dir
154
        if (!\file_exists($targetDir)) {
155
            @\mkdir($targetDir);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
156
        }
157
158
        // Get a file name
159
        if ($request->request->has('name')) {
160
            $fileName = $request->request->get('name');
161
        } elseif (0 !== $request->files->count()) {
162
            $fileName = $request->files->get('file')['name'];
163
        } else {
164
            $fileName = \uniqid('file_', false);
165
        }
166
        $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
167
168
        $chunk = 0;
169
        $chunks = 0;
170
        // Chunking might be enabled
171
        if ($request->request->has('chunk')) {
172
            $chunk = $request->request->getInt('chunk');
173
        }
174
        if ($request->request->has('chunks')) {
175
            $chunks = $request->request->getInt('chunks');
176
        }
177
178
        // Remove old temp files
179
        if ($cleanupTargetDir) {
180
            if (!\is_dir($targetDir) || !$dir = \opendir($targetDir)) {
181
182
                return $this->returnJsonError('100', 'Failed to open temp directory.');
183
            }
184
185
            while (($file = \readdir($dir)) !== false) {
186
                $tmpFilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
187
188
                // If temp file is current file proceed to the next
189
                if ($tmpFilePath === "{$filePath}.part") {
190
191
                    continue;
192
                }
193
194
                // Remove temp file if it is older than the max age and is not the current file
195
                if (\preg_match('/\.part$/', $file) && (\filemtime($tmpFilePath) < \time() - $maxFileAge)) {
196
                    $success = @\unlink($tmpFilePath);
197
                    if ($success !== true) {
198
199
                        return $this->returnJsonError('106', 'Could not remove temp file: '.$filePath);
200
                    }
201
                }
202
            }
203
            \closedir($dir);
204
        }
205
206
        // Open temp file
207
        if (!$out = @\fopen("{$filePath}.part", $chunks ? 'ab' : 'wb')) {
208
209
            return $this->returnJsonError('102', 'Failed to open output stream.');
210
        }
211
212
        if (0 !== $request->files->count()) {
213
214
            $_file = $request->files->get('file');
215
            if ($_file->getError() > 0 || !\is_uploaded_file($_file->getRealPath())) {
216
                return $this->returnJsonError('103', 'Failed to move uploaded file.');
217
            }
218
219
            // Read binary input stream and append it to temp file
220
            if (!$input = @\fopen($_file->getRealPath(), 'rb')) {
221
222
                return $this->returnJsonError('101', 'Failed to open input stream.');
223
            }
224
        } else {
225
            if (!$input = @\fopen('php://input', 'rb')) {
226
227
                return $this->returnJsonError('101', 'Failed to open input stream.');
228
            }
229
        }
230
231
        while ($buff = \fread($input, 4096)) {
232
            \fwrite($out, $buff);
233
        }
234
235
        @\fclose($out);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
236
        @\fclose($input);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
237
238
        // Check if file has been uploaded
239
        if (!$chunks || $chunk === $chunks - 1) {
240
            // Strip the temp .part suffix off
241
            \rename("{$filePath}.part", $filePath);
242
        }
243
244
245
        $em = $this->getDoctrine()->getManager();
246
        /* @var Folder $folder */
247
        $folder = $em->getRepository('KunstmaanMediaBundle:Folder')->getFolder($folderId);
248
        $file   = new File($filePath);
249
250
        try {
251
            /* @var Media $media */
252
            $media = $this->get('kunstmaan_media.media_manager')->getHandler($file)->createNew($file);
253
            $media->setFolder($folder);
254
            $em->getRepository(Media::class)->save($media);
255
        } catch (Exception $e) {
256
            return $this->returnJsonError('104', 'Failed performing save on media-manager');
257
        }
258
259
        $success = \unlink($filePath);
260
        if ($success !== true) {
261
262
            return $this->returnJsonError('105', 'Could not remove temp file: '.$filePath);
263
        }
264
265
266
        // Send headers making sure that the file is not cached (as it happens for example on iOS devices)
267
        $response = new JsonResponse([
268
            'jsonrpc' => '2.0',
269
            'result'  => '',
270
            'id'      => 'id'
271
        ], JsonResponse::HTTP_OK, [
272
            'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT',
273
            'Last-Modified' => \gmdate('D, d M Y H:i:s') . ' GMT',
274
            'Cache-Control' => 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0',
275
            'Pragma' => 'no-cache',
276
        ]);
277
278
        return $response;
279
    }
280
281
    private function returnJsonError($code, $message){
282
283
        return new JsonResponse([
284
            'jsonrpc' => '2.0',
285
            'error ' => [
286
                'code' => $code,
287
                'message' => $message,
288
            ],
289
            'id' => 'id'
290
        ]);
291
    }
292
293
    /**
294
     * @param Request $request
295
     * @param int     $folderId
296
     *
297
     * @Route("drop/{folderId}", requirements={"folderId" = "\d+"}, name="KunstmaanMediaBundle_media_drop_upload")
298
     * @Method({"GET", "POST"})
299
     *
300
     * @return JsonResponse
301
     */
302
    public function dropAction(Request $request, $folderId)
303
    {
304
        $em = $this->getDoctrine()->getManager();
305
306
        /* @var Folder $folder */
307
        $folder = $em->getRepository('KunstmaanMediaBundle:Folder')->getFolder($folderId);
308
309
        $drop = null;
310
311
        if ($request->files->has('files') && $request->files->get('files')['error'] === 0) {
312
            $drop = $request->files->get('files');
313
        } else if ($request->files->get('file')) {
314
            $drop = $request->files->get('file');
315
        } else {
316
            $drop = $request->get('text');
317
        }
318
        $media = $this->get('kunstmaan_media.media_manager')->createNew($drop);
319
        if ($media) {
320
            $media->setFolder($folder);
321
            $em->getRepository('KunstmaanMediaBundle:Media')->save($media);
322
323
            return new JsonResponse(['status' => $this->get('translator')->trans('kuma_admin.media.flash.drop_success')]);
324
        }
325
326
        $request->getSession()->getFlashBag()->add(
327
            FlashTypes::DANGER,
328
            $this->get('translator')->trans('kuma_admin.media.flash.drop_unrecognized')
329
        );
330
331
        return new JsonResponse(['status' => $this->get('translator')->trans('kuma_admin.media.flash.drop_unrecognized')]);
332
    }
333
334
    /**
335
     * @param Request $request
336
     * @param int     $folderId The folder id
337
     * @param string  $type     The type
338
     *
339
     * @Route("create/{folderId}/{type}", requirements={"folderId" = "\d+", "type" = ".+"}, name="KunstmaanMediaBundle_media_create")
340
     * @Method({"GET", "POST"})
341
     * @Template()
342
     *
343
     * @return array|RedirectResponse
344
     */
345
    public function createAction(Request $request, $folderId, $type)
346
    {
347
        return $this->createAndRedirect($request, $folderId, $type, 'KunstmaanMediaBundle_folder_show');
348
    }
349
350
    /**
351
     * @param Request $request
352
     * @param int     $folderId    The folder Id
353
     * @param string  $type        The type
354
     * @param string  $redirectUrl The url where we want to redirect to on success
355
     * @param array   $extraParams The extra parameters that will be passed wen redirecting
356
     *
357
     * @return array|RedirectResponse
358
     */
359
    private function createAndRedirect(Request $request, $folderId, $type, $redirectUrl, $extraParams = [], $isInModal=false)
360
    {
361
        $em = $this->getDoctrine()->getManager();
362
363
        /* @var Folder $folder */
364
        $folder = $em->getRepository('KunstmaanMediaBundle:Folder')->getFolder($folderId);
365
366
        /* @var MediaManager $mediaManager */
367
        $mediaManager = $this->get('kunstmaan_media.media_manager');
368
        $handler      = $mediaManager->getHandlerForType($type);
369
        $media        = new Media();
370
        $helper       = $handler->getFormHelper($media);
371
372
        $form = $this->createForm($handler->getFormType(), $helper, $handler->getFormTypeOptions());
373
374
        if ($request->isMethod('POST')) {
375
            $params = ['folderId' => $folder->getId()];
376
            $params = \array_merge($params, $extraParams);
377
378
            $form->handleRequest($request);
379
380
            if ($form->isSubmitted() && $form->isValid()) {
381
                $media = $helper->getMedia();
382
                $media->setFolder($folder);
383
                $em->getRepository('KunstmaanMediaBundle:Media')->save($media);
384
385
                $this->addFlash(
386
                    FlashTypes::SUCCESS,
387
                    $this->get('translator')->trans('media.flash.created', [
388
                        '%medianame%' => $media->getName()
389
                    ])
390
                );
391
392
                return new RedirectResponse($this->generateUrl($redirectUrl, $params));
393
            }
394
395
            if ($isInModal) {
396
                $this->addFlash(
397
                    FlashTypes::ERROR,
398
                    $this->get('translator')->trans('media.flash.not_created', array(
399
                        '%mediaerrors%' => $form->getErrors(true, true)
400
                    ))
401
                );
402
                return new RedirectResponse($this->generateUrl($redirectUrl, $params));
403
            }
404
        }
405
406
        return [
407
            'type'   => $type,
408
            'form'   => $form->createView(),
409
            'folder' => $folder
410
        ];
411
    }
412
413
    /**
414
     * @param Request $request
415
     * @param int     $folderId The folder id
416
     * @param string  $type     The type
417
     *
418
     * @Route("create/modal/{folderId}/{type}", requirements={"folderId" = "\d+", "type" = ".+"}, name="KunstmaanMediaBundle_media_modal_create")
419
     * @Method({"GET", "POST"})
420
     * @Template()
421
     *
422
     * @return array|RedirectResponse
423
     */
424
    public function createModalAction(Request $request, $folderId, $type)
425
    {
426
        $cKEditorFuncNum = $request->get('CKEditorFuncNum');
427
        $linkChooser     = $request->get('linkChooser');
428
429
        $extraParams = [];
430
        if (!empty($cKEditorFuncNum)) {
431
            $extraParams['CKEditorFuncNum'] = $cKEditorFuncNum;
432
        }
433
        if (!empty($linkChooser)) {
434
            $extraParams['linkChooser'] = $linkChooser;
435
        }
436
437
        return $this->createAndRedirect(
438
            $request,
439
            $folderId,
440
            $type,
441
            'KunstmaanMediaBundle_chooser_show_folder',
442
            $extraParams,
443
            true
444
        );
445
    }
446
447
    /**
448
     * @param Request $request
449
     *
450
     * @Route("move/", name="KunstmaanMediaBundle_media_move")
451
     * @Method({"POST"})
452
     *
453
     * @return string
454
     */
455
    public function moveMedia(Request $request)
456
    {
457
        $mediaId = $request->request->get('mediaId');
458
        $folderId = $request->request->get('folderId');
459
460
        if (empty($mediaId) || empty($folderId)) {
461
            return new JsonResponse(['error' => ['title' => 'Missing media id or folder id']], 400);
462
        }
463
464
        $em = $this->getDoctrine()->getManager();
465
        $mediaRepo = $em->getRepository('KunstmaanMediaBundle:Media');
466
467
        $media = $mediaRepo->getMedia($mediaId);
468
        $folder = $em->getRepository('KunstmaanMediaBundle:Folder')->getFolder($folderId);
469
470
        $media->setFolder($folder);
471
        $mediaRepo->save($media);
472
473
        return new JsonResponse();
474
    }
475
}
476