@param Request $request
@param int     $folderId

@Route("drop/{folderId}", requirements={"folderId" = "\d+"}, name="KunstmaanMediaBundle_media_drop_upload", methods={"GET", "POST"})

@return JsonResponse
761839
public function dropAction(Request $request, $folderId)
    {
        $em = $this->getDoctrine()->getManager();

        /* @var Folder $folder */
        $folder = $em->getRepository('KunstmaanMediaBundle:Folder')->getFolder($folderId);

        $drop = null;

        if ($request->files->has('files') && $request->files->get('files')['error'] === 0) {
            $drop = $request->files->get('files');
        } else {
            if ($request->files->get('file')) {
                $drop = $request->files->get('file');
            } else {
                $drop = $request->get('text');
            }
        }
        $media = $this->get('kunstmaan_media.media_manager')->createNew($drop);
        if ($media) {
            $media->setFolder($folder);
            $em->getRepository('KunstmaanMediaBundle:Media')->save($media);

            return new JsonResponse(['status' => $this->get('translator')->trans('kuma_admin.media.flash.drop_success')]);
        }

        $request->getSession()->getFlashBag()->add(
            FlashTypes::DANGER,
            $this->get('translator')->trans('kuma_admin.media.flash.drop_unrecognized')
        );

        return new JsonResponse(['status' => $this->get('translator')->trans('kuma_admin.media.flash.drop_unrecognized')]);
    }
342976
public function moveAction(Request $request)
    {
        $volumeId = $request->get('site_id');
        $targetId = $request->get('target_id');
        $sourceId = $request->get('source_id');

        $volume = $this->getVolume($volumeId);
        $folder = $volume->findFolder($sourceId);
        $targetFolder = $volume->findFolder($targetId);

        $volume->moveFolder($folder, $targetFolder, $this->getUser()->getId());

        return new ResultResponse(true);
    }
286289
public function update(Request $request, string $folder = '')
    {
        if (empty($request->name)) {
            return $this->json('Name property is required.', 422);
        }

        $this->manager->resetPath($folder);

        if (!$this->manager->blobExists()) {
            return $this->json('Folder not found.', 404);
        }

        $details = $this->manager->rename($request->name);

        return $this->json($details);
    }
742656
public function sortAction(Request $request)
    {
        $tid = $request->get('tid');
        $mode = $request->get('mode');
        $dir = strtolower($request->get('dir'));
        $sortTids = $request->get('sort_ids');
        $sortTids = json_decode($sortTids, true);

        $treeManager = $this->get('phlexible_tree.tree_manager');
        $nodeSorter = $this->get('phlexible_tree.node_sorter');

        $tree = $treeManager->getByNodeId($tid);
        $node = $tree->get($tid);

        $node->setSortMode($mode);
        $node->setSortDir($dir);

        if ($mode !== TreeInterface::SORT_MODE_FREE) {
            $sortTids = $nodeSorter->sort($node);
        }

        if (count($sortTids)) {
            $tree->reorderChildren($node, $sortTids);
        }

        return new ResultResponse(true, 'Tree sort published.');
    }
1233745
public function bulkUploadAction($folderId)
    {
        $em = $this->getDoctrine()->getManager();

        /* @var Folder $folder */
        $folder = $em->getRepository('KunstmaanMediaBundle:Folder')->getFolder($folderId);

        return ['folder' => $folder];
    }
901130
public function putMediaAction(Request $request, $id)
    {
        $_PUT = json_decode($request->getContent(), true);

        $response = $this->getFilter($request);
        if ($response['success'] === false) {
            return $response['value'];
        }
        $filter = $response['value'];

        $mm = $this->getMediaManager();

        $media = $mm->findOneBy(array(
            'id' => $id,
            'filter' => $filter,
        ));

        if ($media === null) {
            return new Response($this->get('translator')->trans('error.mediaIdNotFound', array('%id%' => $id), 'ApoutchikaMediaBundle'));
        }

        $media->setCryptedFilter($response['crypted']);

        // Rotate
        if (isset($_PUT['rotate']) && in_array($_PUT['rotate'], array(-90, 90))) {
            $rotate = new Rotate($mm, $media);
            $rotate
                ->setAngle($_PUT['rotate'])
                ->apply();

            return $this->createResponse($media);
        }

// Mirror
        if (isset($_PUT['mirror']) && in_array($_PUT['mirror'], array('x', 'y'))) {
            $mirror = new Mirror($mm, $media);
            $mirror
                ->setDirection($_PUT['mirror'])
                ->apply();

            return $this->createResponse($media);
        }

// Crop
        if (
            isset($_PUT['x']) && is_numeric($_PUT['x']) &&
            isset($_PUT['y']) && is_numeric($_PUT['y']) &&
            isset($_PUT['w']) && is_numeric($_PUT['w']) &&
            isset($_PUT['h']) && is_numeric($_PUT['h'])
        ) {
            $crop = new Crop($mm, $media);
            $crop
                ->setSize(
                    $_PUT['x'],
                    $_PUT['y'],
                    $_PUT['w'],
                    $_PUT['h']
                )
                ->apply();

            return $this->createResponse($media);
        }

        if (isset($_PUT['name'])) {
            $media->setName($_PUT['name']);
        }
        if (isset($_PUT['description'])) {
            $media->setDescription($_PUT['description']);
        }
        if (isset($_PUT['alt'])) {
            $media->setAlt($_PUT['alt']);
        }
        if (isset($_PUT['focusLeft'])) {
            $media->setFocusLeft($_PUT['focusLeft']);
        }
        if (isset($_PUT['focusTop'])) {
            $media->setFocusTop($_PUT['focusTop']);
        }

        $mm->save($media);

        return $this->createResponse($media);
    }
909197
public function getCollectionAction(Request $request, $start, $count)
    {
        $mediafolder = null;
        $folderUid = $request->get('mediaFolder_uid', null);

        if (null === $folderUid) {
            $mediafolder = $this->getMediaFolderRepository()->getRoot();
        } else {
            $mediafolder = $this->getMediaFolderRepository()->find($folderUid);
        }

        if (null === $mediafolder) {
            throw new NotFoundHttpException('Cannot find a media folder');
        }

        $paginator = null;

        if ($request->query->has('content_uid')) {
            $paginator = $this->getCollectionByContent($request->query->get('content_uid'), $mediafolder);
        } else {
            $paginator = $this->getClassicCollection($request, $mediafolder, $start, $count);
        }

        $iterator = $paginator->getIterator();
        $results = [];
        while ($iterator->valid()) {

            if($this->isGranted('VIEW', $iterator->current()->getMediaFolder())){

                $results[] = $iterator->current();
            }

            $iterator->next();
        }

        $pager = $request->query->has('usePagination') ? $paginator : null;

        return $this->addRangeToContent(
            $this->createJsonResponse($this->mediaToJson($results)),
            $pager,
            $start,
            count($results)
        );
    }
233900
public function findByFolderId($folderId)
    {
        $qb = $this->createQueryBuilder();

        $qb->field('mediaFolder.id')->equals($folderId);

        return $qb->getQuery()->execute();
    }
270113
public function dropsDownloadAction(Request $request)
    {
        $drops = $this->decodeIdsString($request, Drop::class);
        $dropzone = $drops[0]->getDropzone();
        $this->checkPermission('EDIT', $dropzone->getResourceNode(), [], true);
        $fileName = $dropzone->getResourceNode()->getName();

        $archive = $this->manager->generateArchiveForDrops($drops);

        $response = new StreamedResponse();
        $response->setCallBack(
            function () use ($archive) {
                readfile($archive);
            }
        );
        $response->headers->set('Content-Transfer-Encoding', 'octet-stream');
        $response->headers->set('Content-Type', 'application/force-download');
        $response->headers->set('Content-Disposition', 'attachment; filename='.urlencode($fileName.'.zip'));
        $response->headers->set('Content-Type', 'application/zip; charset=utf-8');
        $response->headers->set('Connection', 'close');

        return $response->send();
    }
195091
public function uploadImageAction(Request $request): Response
    {
        if ($this->isValidCsrfToken($request)) {
            $data = new ImageAssetUploadData(
                $request->files->get(self::FILE_KEY),
                $request->request->get(self::LANGUAGE_CODE_KEY)
            );

            $errors = $this->validator->validate($data);
            if ($errors->count() === 0) {
                try {
                    $file = $data->getFile();

                    $content = $this->imageAssetMapper->createAsset(
                        $file->getClientOriginalName(),
                        new ImageValue([
                            'path' => $file->getRealPath(),
                            'fileSize' => $file->getSize(),
                            'fileName' => $file->getClientOriginalName(),
                            'alternativeText' => null,
                        ]),
                        $data->getLanguageCode()
                    );

                    return new JsonResponse([
                        'destinationContent' => [
                            'id' => $content->contentInfo->id,
                            'name' => $content->getName(),
                            'locationId' => $content->contentInfo->mainLocationId,
                        ],
                        'value' => $this->imageAssetMapper->getAssetValue($content),
                    ]);
                } catch (Exception $e) {
                    return $this->createGenericErrorResponse($e->getMessage());
                }
            } else {
                return $this->createInvalidInputResponse($errors);
            }
        }

        return $this->createInvalidCsrfResponse();
    }
629798
public function moveAction(Request $request)
    {
        if (!$request->isXmlHttpRequest()) {
            throw new NotFoundHttpException();
        }

        $folder = $this->findFolderById($request->attributes->get('id'));

        $result = [];
        $mode = $request->request->get('mode');

        if (!in_array($mode, array('before', 'after', 'over'))) {
            $result = array(
                'error'   => true,
                'message' => 'Unexpected creation mode.',
            );
        } else {
            $reference = $this->findFolderById($request->request->get('reference'));

            if ($mode === 'before') {
                $this->getFolderRepository()->persistAsPrevSiblingOf($folder, $reference);
            } elseif ($mode === 'after') {
                $this->getFolderRepository()->persistAsNextSiblingOf($folder, $reference);
            } elseif ($mode === 'over') {
                $this->getFolderRepository()->persistAsLastChildOf($folder, $reference);
            }
            $this->getEntityManager()->flush();
        }

        $response = new Response(json_encode($result, JSON_FORCE_OBJECT));
        $response->headers->add(array('Content-Type' => 'application/json'));
        return $response;
    }
632456
public function loadAction(Request $request)
    {
        $repository = $this->get('phlexible_media_template.template_manager');

        $templateKey = $request->get('template_key');

        $template = $repository->find($templateKey);
        $parameters = $template->getParameters();

        if (isset($parameters['method'])) {
            $parameters['xmethod'] = $parameters['method'];
            unset($parameters['method']);
        }

        return new JsonResponse(['success' => true, 'data' => $parameters]);
    }
1225871
public function formAction(Request $request, $folderId)
    {
        $folderRepository = $this->get('open_orchestra_media.repository.media_folder');
        $folder = $folderRepository->find($folderId);
        $this->denyAccessUnlessGranted(ContributionActionInterface::EDIT, $folder);
        $form = $this->createForm('oo_folder', $folder, array(
            'action' => $this->generateUrl('open_orchestra_media_admin_folder_form', array('folderId' => $folderId)),
            'enable_delete_button' => $this->get('open_orchestra_backoffice.business_rules_manager')->isGranted(BusinessActionInterface::DELETE, $folder),
            'delete_button' => $this->isGranted(ContributionActionInterface::DELETE, $folder)
        ));
        $form->handleRequest($request);
        if ($this->handleForm($form, $this->get('translator')->trans('open_orchestra_media_admin.form.folder.success'), $folder)) {
            $event = $this->get("open_orchestra_media_admin.event.folder_event");
            $event->setFolder($folder);
            $this->dispatchEvent(FolderEvents::FOLDER_UPDATE, $event);
        }
        return $this->renderAdminForm($form);
    }
648555
public function uploadAction(Request $request)
    {
        $files = $this->uploadFiles($request);
        $data = [];

        foreach ($files as $file) {
            $data[] = $this->serializer->serialize($file);
        }

        return new JsonResponse($data, 200);
    }
581245
public function createDirectory(Request $request)
    {
        $this->authorize(MediasPolicy::PERMISSION_CREATE);

        // TODO: Refactor this with the Laravel 5.5 new Exception Handler & Form Request
        $validator = validator($data = $request->all(), [
            'name'     => ['required', 'string'], // TODO: check if the folder does not exists
            'location' => ['required', 'string'],
        ]);

        if ($validator->fails()) {
            return $this->jsonResponseError([
                'messages' => $validator->messages(),
            ], 422);
        }

        $this->media->makeDirectory(
            $path = trim($data['location'], '/').'/'.Str::slug($data['name'])
        );

        return $this->jsonResponseSuccess(['data' => compact('path')]);
    }
959547
public function filesAction(Request $request)
    {
        $id = $request->query->get('id');
        $em = $this->getDoctrine()->getManager();

        $files = $this->getDoctrine()->getRepository('ClasticMediaBundle:File')
            ->findBy(array(
                'directory' => $em->getReference('ClasticMediaBundle:Directory', $id),
            ));

        $data = array_map(function (File $file) {
            return array(
                'id' => $file->getId(),
                'text' => $file->getName(),
                'path' => '/uploads/documents/'.$file->getPath(),
            );
        }, $files);

        return new JsonResponse($data);
    }
71239
public function listAction(Request $request)
    {
        $folderId = $request->get('folder_id');
        $start = $request->get('start', 0);
        $limit = $request->get('limit', 25);
        $sort = $request->get('sort', 'name');
        $dir = $request->get('dir', 'ASC');
        $showHidden = $request->get('show_hidden', false);
        $filter = $request->get('filter');

        if (!$folderId) {
            throw new \RuntimeException('No folder ID');
        }

        if ($filter) {
            $filter = json_decode($filter, true);
        }

        $data = [];
        $total = 0;

        $volume = $this->getVolumeByFolderId($folderId);
        $securityContext = $this->get('security.context');

        $folder = $volume->findFolder($folderId);

        if ($securityContext->isGranted('ROLE_SUPER_ADMIN') || $securityContext->isGranted('FILE_READ', $folder)) {
            if ($sort === 'create_time') {
                $sort = 'created_at';
            } elseif ($sort === 'document_type_key') {
                $sort = 'mime_type';
            }

            if ($filter) {
                $filter['folder'] = $folder;
                if (!$showHidden) {
                    $filter['hidden'] = false;
                }
                $files = $volume->findFiles($filter, [$this->toCamelCase($sort) => $dir], $limit, $start);
                $total = $volume->countFiles($filter);
            } else {
                $files = $volume->findFilesByFolder($folder, [$this->toCamelCase($sort) => $dir], $limit, $start, $showHidden);
                $total = $volume->countFilesByFolder($folder, $showHidden);
            }

            $data = $this->filesToArray($volume, $files);
        }

        return new JsonResponse(['files' => $data, 'totalCount' => $total]);
    }