Duplicate a file on the server.

@param Request $request

@return \Symfony\Component\HttpFoundation\JsonResponse
160498
public function duplicateFile(Request $request)
    {
        $namespace = $request->request->get('namespace');
        $filename = $request->request->get('filename');

        $filesystem = $this->filesystem()->getFilesystem($namespace);

        // If the filename doesn't have an extension $extensionPos will be equal to its length, so that $fileBase will
        // contain the entire filename. This also accounts for dotfiles.
        $extensionPos = strrpos($filename, '.') ?: strlen($filename);

        $fileBase = substr($filename, 0, $extensionPos) . '_copy';
        $fileExtension = substr($filename, $extensionPos);

        $n = 0;

        // Increase $n until filename_copy$n.ext doesn't exist
        do {
            ++$n;
            $destination = $fileBase . $n . $fileExtension;
        } while ($filesystem->has($destination));

        try {
            $filesystem->copy($filename, $destination);

            return $this->json($destination, Response::HTTP_OK);
        } catch (IOException $e) {
            $msg = Trans::__('Unable to duplicate file: %FILE%', ['%FILE%' => $filename]);

            $this->logException($msg, $e);

            return $this->json($msg, Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }
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);
    }
1173439
public function uploadAction(Request $request)
    {
        $manager = $this->getDoctrine()->getManager();

        $file = $request->files->get('file');

        $new = new File();
        $new->setFile($file);
        $new->setMimeType($file->getMimeType());
        $new->setName($file->getClientOriginalName());
        $new->setSize($file->getClientSize());
        $new->setOwned(false);

        $manager->persist($new);
        $manager->flush();

        return new Response($new->getId(), 200);
    }
1113908
public function reorderAction(Request $request)
    {
        $folders = array();
        $nodeIds = $request->get('nodes');

        $em = $this->getDoctrine()->getManager();
        $repository = $em->getRepository('KunstmaanMediaBundle:Folder');

        foreach ($nodeIds as $id) {
            /* @var Folder $folder */
            $folder = $repository->find($id);
            $folders[] = $folder;
        }

        foreach ($folders as $id => $folder) {
            $repository->moveDown($folder, true);
        }

        $em->flush();

        return new JsonResponse(
            array(
                'Success' => 'The node-translations for have got new weight values',
            )
        );
    }
226442
protected function duplicateRequest(\Exception $exception, Request $request)
    {
        $attributes = [
            'exception' => $exception = FlattenException::create($exception),
            '_controller' => $this->controller ?: function () use ($exception) {
                $handler = new ExceptionHandler($this->debug, $this->charset, $this->fileLinkFormat);

                return new Response($handler->getHtml($exception), $exception->getStatusCode(), $exception->getHeaders());
            },
            'logger' => $this->logger instanceof DebugLoggerInterface ? $this->logger : null,
        ];
        $request = $request->duplicate(null, null, $attributes);
        $request->setMethod('GET');

        return $request;
    }
1047349
public function upload(Request $request)
    {
        $json = [];
        foreach ($request->file('file') as $file) {
            $this->storage->putFile($request->get('directory'), $file);
        }

        $json['success'] = trans('admin::image.success.upload');

        return response()
            ->json($json);
    }
918973
public function mediaAction(Request $request)
    {
        $query = $request->get('query');

        // TODO: meta search

        $results = [];
        foreach ($this->get('phlexible_media_manager.volume_manager')->all() as $volume) {
            $files = $volume->search($query);

            foreach ($files as $file) {
                /* @var $file ExtendedFileInterface */

                $results[] = [
                    'id' => $file->getId(),
                    'version' => $file->getVersion(),
                    'name' => $file->getName(),
                    'folder_id' => $file->getFolderId(),
                ];
            }
        }

        return new JsonResponse(['results' => $results]);
    }
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();
    }
411012
public function listFilesAction(Request $request)
    {
        if (!$request->get('paths')) {
            throw $this->createNotFoundException();
        }
        $files = $this->get('vince_type.manager.redactor')->listFiles($request->get('paths'));

        return new Response(json_encode($files, JSON_UNESCAPED_SLASHES), 200, array(
                'Content-Type' => 'application/json',
            )
        );
    }
185143
public function upload(Request $request)
    {
        try {
            $path = $request->file->store($request->upload_path, $this->filesystem);
            $success = true;
            $message = 'Successfully uploaded new file!';
        } catch (Exception $e) {
            $success = false;
            $message = $e->getMessage();
        }

        $realPath = Storage::disk($this->filesystem)->getDriver()->getAdapter()->getPathPrefix().$path;
        Image::make($realPath)->orientate()->save();

        $path = preg_replace('/^public\//', '', $path);

        return response()->json(compact('success', 'message', 'path'));
    }
1292116
public function cacheAction(Request $request)
    {
        $fileId = $request->get('file_id');

        $volumeManager = $this->get('phlexible_media_manager.volume_manager');
        $cacheManager = $this->get('phlexible_media_cache.cache_manager');
        $templateManager = $this->get('phlexible_media_template.template_manager');

        $volume = $volumeManager->getByFileId($fileId);
        $file = $volume->findFile($fileId);
        $cacheItems = $cacheManager->findBy(['file_id' => $fileId]);

        $cache = [];
        foreach ($cacheItems as $cacheItem) {
            $template = $templateManager->find($cacheItem->getTemplateKey());
            $storageKey = $template->getStorage();
            $storage = $this->get('mediacache.storage.'.strtolower($storageKey));

            $urls = $storage->getCacheUrls($file, $cacheItem, $this->_request->getBaseUrl());

            $cache[] = [
                'key' => $cacheItem->getTemplateKey(),
                'value' => $urls['media'],
            ];
        }

        return new JsonResponse(['cache' => $cache]);
    }
602993
public function duplicateAction(Request $request)
    {
        $this->denyAccessUnlessGranted(ContributionActionInterface::CREATE, GroupInterface::ENTITY_TYPE);

        $format = $request->get('_format', 'json');
        $facade = $this->get('jms_serializer')->deserialize(
            $request->getContent(),
            $this->getParameter('open_orchestra_group.facade.group.class'),
            $format
        );

        $group = $this->get('open_orchestra_api.transformer_manager')->reverseTransform('group', $facade);

        $newGroup = clone $group;

        $currentSiteId = $this->get('open_orchestra_backoffice.context_backoffice_manager')->getSiteId();
        $currentSite = $this->get('open_orchestra_model.repository.site')->findOneBySiteId($currentSiteId);

        $newGroup->setWorkflowProfileCollections($group->getWorkflowProfileCollections());
        if ($newGroup->getSite()->getId() === $currentSite->getId()) {
            $newGroup->setPerimeters($group->getPerimeters());
        }
        $newGroup->setSite($currentSite);

        $objectManager = $this->get('object_manager');
        $objectManager->persist($newGroup);
        $objectManager->flush();

        return array();
    }
585902
public function put(Request $request)
    {
        $user = $this->getUser();

        $userValidationCopy = clone $user;

        // Validate the modified fields
        $content = $this->getContentAsArray($request);

        $errors = $this->userValidator->validate($content, $user);

        if (count($errors) > 0) {
            return $this->createConstraintViolationResponse($errors);
        }

        $userValidationCopy->exchangeArray($content ?: [])->getArrayCopy();

        try {
            $user = $this->userService->update($user, $this->getContentAsArray($request));
        } catch (OutOfBoundsException $e) {
            return $this->createEmailNotUniqueResponse();
        }

        return $this->userArrayWithoutPassword($user);
    }
952498
public function updateImage(Request $request)
    {
        $fileName = $request->query->get('file');
        $type = $request->query->get('type');
        $value = $request->query->get('value');
      
        /** @var Image $entity */
        $qb = $this->getDoctrine()->getManager()->getRepository('CoreBundle:Image')
                ->createQueryBuilder('i');
        $image = $qb->where($qb->expr()->like('i.path', ':path'))
            ->setParameter('path','%'.$fileName.'%')
            ->getQuery()
            ->getOneOrNullResult();

//        $image = $this->getDoctrine()->getManager()->getRepository('CoreBundle:Image')->findOneBy(array('path' => $fileName));
       
        if (!$image) {
            throw new NotFoundHttpException('Unable to find Image entity.');
        }
        

        if($type == 'title') $image->setTitle($value);
        if($type == 'alt') $image->setAlt($value);
        
        $this->getDoctrine()->getManager()->flush();
            

        return new JsonResponse(array('success' => true));
    }
845166
public function newAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $template = new Template();
        $form = $this->container->get('form.factory')->create(TemplateType::class, $template);

        $form->handleRequest($request);
        if ($form->isValid()) {
            $em->persist($template);
            $em->flush();

            return new JsonResponse([
                'success' => true,
                'url'     => $this->generateUrl('victoire_template_show', ['id' => $template->getId()]),
            ]);
        }

        return new JsonResponse(
            [
                'success' => true,
                'html'    => $this->container->get('templating')->render(
                    'VictoireTemplateBundle:Template:new.html.twig',
                    ['form' => $form->createView()]
                ),
            ]
        );
    }
30501
public function imageUploadAction(Request $request)
    {
        $image = new ImageField();
        /* @var $form Form */
        $form = $this->createForm(new UploadImage(), $image);
        $form->handleRequest($request);

        if (!$form->isValid()) {
            $errors = $form->getErrors();

            return new JsonResponse(['error' => $this->get('translator')->trans($errors[0]->getMessage())], 404);
        }

        // try upload file
        try {
            $this->get('anime_db.downloader')->imageField($image);

            return new JsonResponse([
                'path' => $image->getFilename(),
                'image' => $image->getWebPath(),
            ]);
        } catch (\InvalidArgumentException $e) {
            return new JsonResponse(['error' => $this->get('translator')->trans($e->getMessage())], 404);
        }
    }
505038
public function invalidateCacheAction(Request $request)
    {
        $this->get('lexik_translation.translator')->removeLocalesCacheFiles($this->getManagedLocales());

        $message = $this->get('translator')->trans('translations.cache_removed', array(), 'LexikTranslationBundle');

        if ($request->isXmlHttpRequest()) {
            $this->checkCsrf();

            return new JsonResponse(array('message' => $message));
        }

        $this->get('session')->getFlashBag()->add('success', $message);

        return $this->redirect($this->generateUrl('lexik_translation_grid'));
    }