@param  MediaFolder $mediaFolder
@param  Request     $request
@return Response

@Rest\ParamConverter(name="mediaFolder", class="BackBee\NestedNode\MediaFolder")
@Rest\Security("is_fully_authenticated() & has_role('ROLE_API_USER')")
512287
public function patchAction(MediaFolder $mediaFolder, Request $request)
    {
        if (!$this->isGranted('EDIT', $mediaFolder)) {
            throw new AccessDeniedHttpException(sprintf('You are not authorized to edit %s MediaFolder.', $mediaFolder->getTitle()));
        }

        $operations = $request->request->all();
        try {
            (new OperationSyntaxValidator())->validate($operations);
        } catch (InvalidOperationSyntaxException $e) {
            throw new BadRequestHttpException('operation invalid syntax: ' . $e->getMessage());
        }

        $this->patchSiblingAndParentOperation($mediaFolder, $operations);
        $entityPatcher = new EntityPatcher(new RightManager($this->getSerializer()->getMetadataFactory()));
        try {
            $entityPatcher->patch($mediaFolder, $operations);
        } catch (UnauthorizedPatchOperationException $e) {
            throw new BadRequestHttpException('Invalid patch operation: '.$e->getMessage());
        }

        $this->getEntityManager()->flush();
        return $this->createJsonResponse(null, 204);
    }
1288201
public function chooserIndexAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $session = $request->getSession();
        $folderId = false;

        $type = $request->get('type', 'all');
        $cKEditorFuncNum = $request->get('CKEditorFuncNum');
        $linkChooser = $request->get('linkChooser');

        // Go to the last visited folder
        if ($session->get('last-media-folder')) {
            try {
                $em->getRepository('KunstmaanMediaBundle:Folder')->getFolder($session->get('last-media-folder'));
                $folderId = $session->get('last-media-folder');
            } catch (EntityNotFoundException $e) {
                $folderId = false;
            }
        }

        if (!$folderId) {
            // Redirect to the first top folder
            /* @var Folder $firstFolder */
            $firstFolder = $em->getRepository('KunstmaanMediaBundle:Folder')->getFirstTopFolder();
            $folderId = $firstFolder->getId();
        }

        $params = array(
            'folderId' => $folderId,
            'type' => $type,
            'CKEditorFuncNum' => $cKEditorFuncNum,
            'linkChooser' => $linkChooser,
        );

        return $this->redirect($this->generateUrl('KunstmaanMediaBundle_chooser_show_folder', $params));
    }
745253
public function store(MediaImageRequest $request, $id)
    {
        if ($this->auth->user()->hasRole('admin')) {
            $user = $this->user->find($id);
        } else {
            $user = $this->auth->user();
        }

        $user->clearMediaCollection('profile');
        $savedImage = $user->addMedia($request->files->get('image'))->toMediaLibrary('profile');

        return $this->response->item($savedImage, new ProfilePictureTransformer());
    }
518921
public function showMediaAction(Request $request, Media $media, $filter = null)
    {
        $response = new Response();
        $lastModified = new \DateTime('now');

        //Checking if it is an image or not
        $src = $this->get('alpixel_media.manager')->getAbsolutePath($media);
        $isImage = @getimagesize($src);

        try {
            if ($isImage) {
                $response->headers->set('Content-disposition', 'inline;filename='.$media->getName());
                if (!empty($filter) && $isImage) {
                    $src = $this->get('alpixel_media.manager')->getAbsolutePath($media, $filter);
                    $dataManager = $this->get('liip_imagine.data.manager'); // the data manager service
                    $filterManager = $this->get('liip_imagine.filter.manager'); // the filter manager service
                    $uploadDir = $this->get('alpixel_media.manager')->getUploadDir($filter);

                    if (!is_file($src)) {
                        $fs = new Filesystem();
                        if (!$fs->exists($uploadDir.$media->getFolder())) {
                            $fs->mkdir($uploadDir.$media->getFolder());
                        }

                        $path = 'upload/'.$media->getUri();

                        // find the image and determine its type
                        $image = $dataManager->find($filter, $path);

                        // run the filter
                        $responseData = $filterManager->applyFilter($image, $filter);
                        $data = $responseData->getContent();
                        file_put_contents($uploadDir.$media->getUri(), $data);
                    } else {
                        $data = file_get_contents($src);
                        $lastModified->setTimestamp(filemtime($src));
                    }
                } else {
                    $src = $this->get('alpixel_media.manager')->getAbsolutePath($media);
                    $lastModified->setTimestamp(filemtime($src));
                    $data = file_get_contents($src);
                }
            } else {
                $lastModified->setTimestamp(filemtime($src));
                $data = file_get_contents($src);
                $response->headers->set('Content-disposition', 'attachment;filename='.basename($media->getUri()));
            }

            if ($data === false) {
                throw $this->createNotFoundException();
            }
        } catch (\Exception $e) {
            throw $this->createNotFoundException($e->getMessage());
        }

        $response->setLastModified($lastModified);
        $response->setPublic();
        $response->headers->set('Content-Type', $media->getMime());

        if ($response->isNotModified($request)) {
            return $response;
        }

        $response->setContent($data);

        return $response;
    }
1129133
public function deleteMedia(Request $request)
    {
        // if single file/folder '?s=name'
        if ($request->has('s')) {
            if (is_dir(storage_path('app') . DIRECTORY_SEPARATOR . $request->input('s'))) {
                return $this->deleteDirectory($request);
            } else {
                return $this->deleteFile($request);
            }
        }

        // if multiple files
        if ($request->has('files')) {
            Storage::delete($request->input('files'));
        }

        // if multiple directories
        if ($request->has('directories')) {
            if (is_array($request->input('directories'))) {
                foreach ($request->input('directories') as $directory) {
                    Storage::deleteDirectory($directory);
                }
            } else {
                Storage::deleteDirectory($request->input('directories'));
            }
        }

        if ($request->wantsJson()) {
            return $this->notifySuccess('File/Folder deleted successfully!');
        }

        flash()->success('File/Folder deleted successfully!');

        return redirect()->back();
    }
518538
public function deleteAction(Request $request, $mediaId)
    {
        $em = $this->getDoctrine()->getManager();

        /* @var Media $media */
        $media = $em->getRepository('KunstmaanMediaBundle:Media')->getMedia($mediaId);
        $medianame = $media->getName();
        $folder = $media->getFolder();

        $em->getRepository('KunstmaanMediaBundle:Media')->delete($media);

        $this->addFlash(
            FlashTypes::SUCCESS,
            $this->get('translator')->trans(
                'kuma_admin.media.flash.deleted_success.%medianame%',
                [
                    '%medianame%' => $medianame,
                ]
            )
        );

        // If the redirect url is passed via the url we use it
        $redirectUrl = $request->query->get('redirectUrl');
        if (empty($redirectUrl) || (\strpos($redirectUrl, $request->getSchemeAndHttpHost()) !== 0 && \strpos($redirectUrl, '/') !== 0)) {
            $redirectUrl = $this->generateUrl(
                'KunstmaanMediaBundle_folder_show',
                ['folderId' => $folder->getId()]
            );
        }

        return new RedirectResponse($redirectUrl);
    }
174147
public function isDeletable(MediaFolderInterface $folder)
    {
        return $this->mediaRepository->countByFolderId($folder->getId()) == 0
            && $this->folderRepository->countChildren($folder->getId(), $folder->getSiteId()) == 0;
    }
1363304
public function createFolder(UploadNewFolderRequest $request)
    {
        $new_folder = $request->get('new_folder');
        $folder = $request->get('folder').'/'.$new_folder;

        try {
            $result = $this->mediaManager->createDirectory($folder);

            if ($result !== true) {
                $error = $this->mediaManager->errors() ?: trans('media-manager::messages.create_error', ['entity' => 'directory']);

                return $this->errorResponse($error);
            }

            return ['success' => trans('media-manager::messages.create_success', ['entity' => 'folder'])];
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }
509499
public function searchMediaAction(Request $request)
    {
        $response = $this->getFilter($request);
        if ($response['success'] === false) {
            return $response['value'];
        }
        $filter = $response['crypted'];

        $mm = $this->getMediaManager();

        $q = ($request->query->has('q')) ? $request->query->get('q') : null;
        $type = ($request->query->has('type')) ? $request->query->get('type') : null;

        $medias = $mm->search($filter, $q, $type);

        return $this->createResponse($medias);
    }
1166804
public function putAction($id, Request $request)
    {
        $mediaTitle = $request->get('title', 'Untitled media');
        $mediaFolderUid = $request->get('media_folder', null);
        $media = $this->getMediaRepository()->find($id);
        $currentMediaFoldierUid = $media->getMediaFolder()->getUid();

        if (null === $media) {
            throw new BadRequestHttpException(sprintf('Cannot find media with id `%s`.', $id));
        }

        $media->setTitle($mediaTitle);

        if ((null !== $mediaFolderUid) && ($mediaFolderUid !== $currentMediaFoldierUid)) {
            $mediaFolder = $this->getMediaFolderRepository()->find($mediaFolderUid);
            if (null !== $mediaFolder) {
                $media->setMediaFolder($mediaFolder);
            }
        }

        $this->autoCommitContent($media->getContent());
        $this->getEntityManager()->persist($media);
        $this->getEntityManager()->flush();

        return $this->createJsonResponse(null, 204);
    }
430022
protected function handleWriteMedium(Request $request, MediaInterface $media, MediaProviderInterface $provider)
    {
        $form = $this->formFactory->createNamed(null, 'sonata_media_api_form_media', $media, [
            'provider_name' => $provider->getName(),
            'csrf_protection' => false,
        ]);

        $form->handleRequest($request);

        if ($form->isValid()) {
            $media = $form->getData();
            $this->mediaManager->save($media);

            $context = new Context();
            $context->setGroups(['sonata_api_read']);
            $context->enableMaxDepth();

            $view = FOSRestView::create($media);
            $view->setContext($context);

            return $view;
        }

        return $form;
    }
80857
public function postCreate(MediaCreateRequest $request)
    {
        $media = Media::create($request->all());

        return redirect($this->admin->currentUrl('view/'.$media->id))->with('notifications_below_header', [['type' => 'success', 'icon' => 'check-circle', 'title' => 'Success!', 'message' => 'Your Media was successfully added.', 'dismissable' => false]]);
    }
995258
public function saveAction(Request $request)
    {
        $repository = $this->get('phlexible_media_template.template_manager');

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

        unset($params['template_key'],
        $params['module'],
        $params['controller'],
        $params['action']);

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

        $params = $this->fixParams($params);

        foreach ($params as $key => $value) {
            $template->setParameter($key, $value);
        }

        $repository->updateTemplate($template);

        return new ResultResponse(true, 'Media template "'.$template->getKey().'" saved.');
    }
1318672
public function moveMedia(Request $request)
    {
        @trigger_error(sprintf('The "%s" controller action is deprecated in KunstmaanMediaBundle 5.1 and will be removed in KunstmaanMediaBundle 6.0.', __METHOD__), E_USER_DEPRECATED);

        $mediaId = $request->request->get('mediaId');
        $folderId = $request->request->get('folderId');

        if (empty($mediaId) || empty($folderId)) {
            return new JsonResponse(['error' => ['title' => 'Missing media id or folder id']], 400);
        }

        $em = $this->getDoctrine()->getManager();
        $mediaRepo = $em->getRepository('KunstmaanMediaBundle:Media');

        $media = $mediaRepo->getMedia($mediaId);
        $folder = $em->getRepository('KunstmaanMediaBundle:Folder')->getFolder($folderId);

        $media->setFolder($folder);
        $mediaRepo->save($media);

        return new JsonResponse();
    }
920485
public function addMediaFile(ServerRequestInterface $request, Tree $tree): ResponseInterface
    {
        $xref  = $request->get('xref', '');
        $media = Media::getInstance($xref, $tree);

        try {
            Auth::checkMediaAccess($media);
        } catch (Exception $ex) {
            return response(view('modals/error', [
                'title' => I18N::translate('Add a media file'),
                'error' => $ex->getMessage(),
            ]));
        }

        return response(view('modals/add-media-file', [
            'max_upload_size' => $this->maxUploadFilesize(),
            'media'           => $media,
            'media_types'     => $this->mediaTypes(),
            'unused_files'    => $this->unusedFiles($tree),
        ]));
    }
795820
public function savesetsAction(Request $request)
    {
        $folderId = $request->get('folder_id');
        $joinedIds = $request->get('ids');
        if ($joinedIds) {
            $ids = explode(',', $joinedIds);
        } else {
            $ids = [];
        }

        $volumeManager = $this->get('phlexible_media_manager.volume_manager');

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

        $attributes = $folder->getAttributes();
        $attributes->set('metasets', $ids);
        $volume->setFolderAttributes($folder, $attributes, $this->getUser()->getId());

        return new ResultResponse(true, 'Set added.');
    }
564871
public function metaAction(Request $request)
    {
        $fileId = $request->get('file_id');

        $file = $this->get('phlexible_media_manager.volume_manager')->getByFileId($fileId)->findFile($fileId);

        $fileMetaSetResolver = $this->get('phlexible_media_manager.file_meta_set_resolver');
        $fileMetaDataManager = $this->get('phlexible_media_manager.file_meta_data_manager');
        $optionResolver = $this->get('phlexible_meta_set.option_resolver');

        $meta = [];

        foreach ($fileMetaSetResolver->resolve($file) as $metaSet) {
            $metaData = $fileMetaDataManager->findByMetaSetAndFile($metaSet, $file);

            $fieldDatas = [];

            foreach ($metaSet->getFields() as $field) {
                $options = $optionResolver->resolve($field);

                $fieldData = [
                    'key' => $field->getName(),
                    'type' => $field->getType(),
                    'options' => $options,
                    'readonly' => $field->isReadonly(),
                    'required' => $field->isRequired(),
                    'synchronized' => $field->isSynchronized(),
                ];

                if ($metaData) {
                    foreach ($metaData->getLanguages() as $language) {
                        $fieldData["value_$language"] = $metaData->get($field->getName(), $language);
                    }
                }

                $fieldDatas[] = $fieldData;
            }

            $meta[] = [
                'set_id' => $metaSet->getId(),
                'title' => $metaSet->getName(),
                'fields' => $fieldDatas,
            ];
        }

        return new JsonResponse(['meta' => $meta]);
    }