@param Request $request
@param int     $folderId

@Route("bulkuploadsubmit/{folderId}", requirements={"folderId" = "\d+"}, name="KunstmaanMediaBundle_media_bulk_upload_submit")

@return JsonResponse
345038
public function bulkUploadSubmitAction(Request $request, $folderId)
    {
        // Settings
        if (\ini_get('upload_tmp_dir')) {
            $tempDir = \ini_get('upload_tmp_dir');
        } else {
            $tempDir = \sys_get_temp_dir();
        }
        $targetDir = \rtrim($tempDir, '/').DIRECTORY_SEPARATOR.'plupload';
        $cleanupTargetDir = true; // Remove old files
        $maxFileAge = 5 * 60 * 60; // Temp file age in seconds

        // Create target dir
        if (!\file_exists($targetDir)) {
            @\mkdir($targetDir);
        }

        // Get a file name
        if ($request->request->has('name')) {
            $fileName = $request->request->get('name');
        } elseif (0 !== $request->files->count()) {
            $fileName = $request->files->get('file')['name'];
        } else {
            $fileName = \uniqid('file_', false);
        }
        $filePath = $targetDir.DIRECTORY_SEPARATOR.$fileName;

        $chunk = 0;
        $chunks = 0;
        // Chunking might be enabled
        if ($request->request->has('chunk')) {
            $chunk = $request->request->getInt('chunk');
        }
        if ($request->request->has('chunks')) {
            $chunks = $request->request->getInt('chunks');
        }

        // Remove old temp files
        if ($cleanupTargetDir) {
            if (!\is_dir($targetDir) || !$dir = \opendir($targetDir)) {
                return $this->returnJsonError('100', 'Failed to open temp directory.');
            }

            while (($file = \readdir($dir)) !== false) {
                $tmpFilePath = $targetDir.DIRECTORY_SEPARATOR.$file;

                // If temp file is current file proceed to the next
                if ($tmpFilePath === "{$filePath}.part") {
                    continue;
                }

                // Remove temp file if it is older than the max age and is not the current file
                if (\preg_match('/\.part$/', $file) && (\filemtime($tmpFilePath) < \time() - $maxFileAge)) {
                    $success = @\unlink($tmpFilePath);
                    if ($success !== true) {
                        return $this->returnJsonError('106', 'Could not remove temp file: '.$filePath);
                    }
                }
            }
            \closedir($dir);
        }

        // Open temp file
        if (!$out = @\fopen("{$filePath}.part", $chunks ? 'ab' : 'wb')) {
            return $this->returnJsonError('102', 'Failed to open output stream.');
        }

        if (0 !== $request->files->count()) {
            $_file = $request->files->get('file');
            if ($_file->getError() > 0 || !\is_uploaded_file($_file->getRealPath())) {
                return $this->returnJsonError('103', 'Failed to move uploaded file.');
            }

            // Read binary input stream and append it to temp file
            if (!$input = @\fopen($_file->getRealPath(), 'rb')) {
                return $this->returnJsonError('101', 'Failed to open input stream.');
            }
        } else {
            if (!$input = @\fopen('php://input', 'rb')) {
                return $this->returnJsonError('101', 'Failed to open input stream.');
            }
        }

        while ($buff = \fread($input, 4096)) {
            \fwrite($out, $buff);
        }

        @\fclose($out);
        @\fclose($input);

        // Check if file has been uploaded
        if (!$chunks || $chunk === $chunks - 1) {
            // Strip the temp .part suffix off
            \rename("{$filePath}.part", $filePath);
        }

        $em = $this->getDoctrine()->getManager();
        /* @var Folder $folder */
        $folder = $em->getRepository('KunstmaanMediaBundle:Folder')->getFolder($folderId);
        $file = new File($filePath);

        try {
            /* @var Media $media */
            $media = $this->get('kunstmaan_media.media_manager')->getHandler($file)->createNew($file);
            $media->setFolder($folder);
            $em->getRepository(Media::class)->save($media);
        } catch (Exception $e) {
            return $this->returnJsonError('104', 'Failed performing save on media-manager');
        }

        $success = \unlink($filePath);
        if ($success !== true) {
            return $this->returnJsonError('105', 'Could not remove temp file: '.$filePath);
        }

        // Send headers making sure that the file is not cached (as it happens for example on iOS devices)
        $response = new JsonResponse(
            [
                'jsonrpc' => '2.0',
                'result' => '',
                'id' => 'id',
            ], JsonResponse::HTTP_OK, [
                'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT',
                'Last-Modified' => \gmdate('D, d M Y H:i:s').' GMT',
                'Cache-Control' => 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0',
                'Pragma' => 'no-cache',
            ]
        );

        return $response;
    }
437925
public function deleteAction(Request $request, $folderId)
    {
        /** @var EntityManager $em */
        $em = $this->getDoctrine()->getManager();

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

        if (is_null($parentFolder)) {
            $this->addFlash(
                FlashTypes::ERROR,
                $this->get('translator')->trans('media.folder.delete.failure.text', array(
                    '%folder%' => $folderName,
                ))
            );
        } else {
            $em->getRepository('KunstmaanMediaBundle:Folder')->delete($folder);
            $this->addFlash(
                FlashTypes::SUCCESS,
                $this->get('translator')->trans('media.folder.delete.success.text', array(
                    '%folder%' => $folderName,
                ))
            );
            $folderId = $parentFolder->getId();
        }
        if (strpos($request->server->get('HTTP_REFERER', ''), 'chooser')) {
            $redirect = 'KunstmaanMediaBundle_chooser_show_folder';
        } else {
            $redirect = 'KunstmaanMediaBundle_folder_show';
        }

        $type = $this->get('request_stack')->getCurrentRequest()->get('type');

        return new RedirectResponse(
            $this->generateUrl($redirect,
                array(
                    'folderId' => $folderId,
                    'type' => $type,
                )
            )
        );
    }
1113110
public function renameAction(Request $request)
    {
        $volumeId = $request->get('site_id');
        $folderId = $request->get('folder_id');
        $folderName = $request->get('folder_name');

        $volume = $this->getVolume($volumeId);
        $folder = $volume->findFolder($folderId);

        $volume->renameFolder($folder, $folderName, $this->getUser()->getId());

        return new ResultResponse(true, 'Folder renamed.', [
            'folder_name' => $folderName,
        ]);
    }
118446
@RequestMapping(value = "branches/{branchId}/update/bulk", method = RequestMethod.GET)
    public Form bulkUpdate(@SuppressWarnings("UnusedParameters") @PathVariable ID branchId) {
        return Form.create()
                .with(
                        Replacements.of("replacements")
                                .label("Replacements")
                )
                ;
    }
204859
public function copyAction(Request $request)
    {
        $folderId = $request->get('folderID');
        $fileIDs = json_decode($request->get('fileIDs'));

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

        foreach ($fileIDs as $fileID) {
            $file = $volume->findFile($fileID);
            $volume->copyFile($file, $folder, $this->getUser()->getId());
        }

        return new ResultResponse(true, 'File(s) copied.');
    }
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);
    }
124740
public function deleteAction($folderId)
    {
        $folder = $this->get('open_orchestra_media.repository.media_folder')->find($folderId);
        if ($folder) {
            $this->denyAccessUnlessGranted(ContributionActionInterface::DELETE, $folder);
            $folderManager = $this->get('open_orchestra_media_admin.manager.media_folder');

            if (!$this->get('open_orchestra_backoffice.business_rules_manager')->isGranted(BusinessActionInterface::DELETE, $folder)) {
                throw new FolderNotDeletableException();
            }
            $folderManager->deleteFolder($folder);

            $event = $this->get("open_orchestra_media_admin.event.folder_event");
            $event->setFolder($folder);
            $this->dispatchEvent(FolderEvents::FOLDER_DELETE, $event);
            $this->get('object_manager')->flush();
        }

        return array();
    }
692006
protected function move_file_from_root_to_folder(\repository_googledocs\rest $client, $fileid, $folderid) {
        // Set the parent.
        $params = [
            'fileid' => $fileid, 'addParents' => $folderid, 'removeParents' => 'root'
        ];
        $response = $client->call('update', $params, ' ');
        if (empty($response->id)) {
            $details = 'Cannot move the file to a folder: ' . $fileid;
            throw new repository_exception('errorwhilecommunicatingwith', 'repository', '', $details);
        }
        return 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);
    }
693501
public function subCreateAction(Request $request, $folderId)
    {
        $em = $this->getDoctrine()->getManager();

        /* @var Folder $parent */
        $parent = $em->getRepository('VictoireMediaBundle:Folder')->getFolder($folderId);
        $folder = new Folder();
        $folder->setParent($parent);
        $form = $this->createForm(FolderType::class, $folder, ['folder' => $folder]);
        if ('POST' == $request->getMethod()) {
            $form->handleRequest($request);
            if ($form->isValid()) {
                $em->getRepository('VictoireMediaBundle:Folder')->save($folder);

                $this->congrat('Folder \''.$folder->getName().'\' has been created!');

                return new Response('<script>window.location="'.$this->generateUrl('VictoireMediaBundle_folder_show', ['folderId' => $folder->getId()]).'"</script>');
            }
        }

        $galleries = $em->getRepository('VictoireMediaBundle:Folder')->getAllFolders();

        return $this->render('VictoireMediaBundle:Folder:addsub-modal.html.twig', [
            'subform'   => $form->createView(),
            'galleries' => $galleries,
            'folder'    => $folder,
            'parent'    => $parent,
        ]);
    }
195997
public function handleFolderContents(SS_HTTPRequest $request)
    {
        if (!$request->param('FolderID')) {
            $folder = Injector::inst()->get('Folder');
            $folder->Filename = ASSETS_DIR;
        } else {
            $folder = Folder::get()->byID($request->param('FolderID'));
        }

        if (!$folder) {
            return $this->httpError(404, 'That folder does not exist');
        }

        $cursor = (int)$request->getVar('cursor');
        $result = array(
            'folder' => $this->createFolderJson($folder),
            'breadcrumbs' => $this->createBreadcrumbJson($folder),
            'children' => array()
        );

        $files = File::get()
            ->filter(array(
                'ParentID' => $folder->ID
            ))
            ->sort($this->getSortClause($request->getVar('sort')));

        $totalFiles = (int)$files->count();
        $files = $files->limit($this->config()->folder_items_limit, $cursor);

        foreach ($files as $file) {
            if (!$file->canView()) {
                continue;
            }

            $result['children'][] = ($file instanceof Folder) ?
                $this->createFolderJson($file) :
                $this->createFileJson($file, $folder);
        }

        $cursor += $files->count();
        $result['cursor'] = $cursor;
        $result['has_more'] = ($cursor < $totalFiles);
        $result['total_items'] = $totalFiles;

        $response = new SS_HTTPResponse(
            Convert::array2json($result), 200
        );

        return $response->addHeader('Content-Type', 'application/json');
    }
704107
public function create(Request $request)
    {
        try {
            $parentId = $request->input('parentId');
            $contentTypeId = $request->input('contentTypeId');
            $content = $this->content->createStub($parentId, $contentTypeId);

            if ($request->input('folder') == true) {
                $content->fillDefaults()->fill([
                    'name'           => $request->input('name'),
                    'is_sluggable'   => false,
                    'is_folder'      => true,
                    'is_publishable' => false,
                ])->save();

                if ($parentId) {
                    return redirect()->route('soda.content.show', $parentId)->with('success', trans('soda::messages.created', ['object' => trans('soda::terminology.content')]));
                }

                return redirect()->route('soda.content.index')->with('success', trans('soda::messages.created', ['object' => trans('soda::terminology.content')]));
            }
        } catch (Exception $e) {
            return $this->handleException($e, trans('soda::errors.create', ['object' => trans('soda::terminology.content')]));
        }

        if ($parentId) {
            $contentFolder = $this->content->findById($parentId);
            $this->buildBreadcrumbTree($contentFolder, $contentFolder->real_depth > 0);
        }

        if ($content->type) {
            app('soda.interface')->setHeading('New '.$content->type->name);
        } else {
            app('soda.interface')->setHeading('New '.ucfirst(trans('soda::terminology.content')));
        }

        return view($content->edit_action, compact('content'));
    }
631567
public function upload($id, Request $request)
    {
        $entity = $this->getQuery()->where('id', $id)->first();

        if (!$entity) {
            return $this->response([], Response::HTTP_NOT_FOUND);
        }

        $manager = $this->getManager();

        if ($request->file('file') === null) {
            return $this->error(['errors' => ['message' => 'Missing file']]);
        }

        $result = $manager->uploadFile(
            $entity,
            $request->file('file')
        );

        if (!$result->ok()) {
            return $this->error(['errors' => $result->getSimpleErrors()]);
        }

        return $this->success(['data' => $this->getManager()->getSerializer()->serialize($result->getResource())->toArray()], 201);
    }
82862
public function indexAction(Request $request, $menuid)
    {
        $menuRepo = $this->getDoctrine()->getManager()->getRepository(
            $this->container->getParameter('kunstmaan_menu.entity.menu.class')
        );

        /** @var BaseMenu $menu */
        $menu = $menuRepo->find($menuid);
        if ($menu->getLocale() != $request->getLocale()) {
            /** @var BaseMenu $translatedMenu */
            $translatedMenu = $menuRepo->findOneBy(['locale' => $request->getLocale(), 'name' => $menu->getName()]);
            $menuid = $translatedMenu->getId();
        }

        $configurator = $this->getAdminListConfigurator($request, $menuid);
        $itemRoute = function (EntityInterface $item) use ($menuid) {
            return array(
                'path' => 'kunstmaanmenubundle_admin_menuitem_move_up',
                'params' => array(
                    'menuid' => $menuid,
                    'item' => $item->getId(),
                ),
            );
        };
        $configurator->addItemAction(new SimpleItemAction($itemRoute, 'arrow-up', 'kuma_admin_list.action.move_up'));

        $itemRoute = function (EntityInterface $item) use ($menuid) {
            return array(
                'path' => 'kunstmaanmenubundle_admin_menuitem_move_down',
                'params' => array(
                    'menuid' => $menuid,
                    'item' => $item->getId(),
                ),
            );
        };
        $configurator->addItemAction(new SimpleItemAction($itemRoute, 'arrow-down', 'kuma_admin_list.action.move_down'));

        return parent::doIndexAction($configurator, $request);
    }
1316785
public function listsetsAction(Request $request)
    {
        $folderId = $request->get('folder_id');

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

        $folder = $volumeManager->getByFolderId($folderId)->findFolder($folderId);
        $metaSets = $folderMetaSetResolver->resolve($folder);

        $sets = [];
        foreach ($metaSets as $metaSet) {
            $sets[] = [
                'id' => $metaSet->getId(),
                'name' => $metaSet->getName(),
            ];
        }

        return new JsonResponse(['sets' => $sets]);
    }
76369
private function createAndRedirect(Request $request, $folderId, $type, $redirectUrl)
    {
        $em = $this->getDoctrine()->getManager();

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

        /* @var MediaManager $mediaManager */
        $mediaManager = $this->get('victoire_media.media_manager');
        $handler = $mediaManager->getHandlerForType($type);
        $media = new Media();
        $helper = $handler->getFormHelper($media);

        $options = array_merge([
            'action' => $this->generateUrl('VictoireMediaBundle_media_create', ['folderId' => $folderId, 'type' => $type]),
        ], $handler->getFormTypeOptions());
        $form = $this->createForm($handler->getFormType(), $helper, $options);

        if ($request->isMethod('POST')) {
            $form->handleRequest($request);
            if ($form->isValid()) {
                $media = $helper->getMedia();
                $media->setFolder($folder);
                $em->getRepository('VictoireMediaBundle:Media')->save($media);

                $this->congrat('Media \''.$media->getName().'\' has been created!');

                return new RedirectResponse($this->generateUrl($redirectUrl, ['folderId' => $folder->getId()]));
            }
        }

        return [
            'type'   => $type,
            'form'   => $form->createView(),
            'folder' => $folder,
        ];
    }
641259
public static function view_folder($folderid) {
        global $DB, $CFG;
        require_once($CFG->dirroot . "/mod/folder/lib.php");

        $params = self::validate_parameters(self::view_folder_parameters(),
                                            array(
                                                'folderid' => $folderid
                                            ));
        $warnings = array();

        // Request and permission validation.
        $folder = $DB->get_record('folder', array('id' => $params['folderid']), '*', MUST_EXIST);
        list($course, $cm) = get_course_and_cm_from_instance($folder, 'folder');

        $context = context_module::instance($cm->id);
        self::validate_context($context);

        require_capability('mod/folder:view', $context);

        // Call the page/lib API.
        folder_view($folder, $course, $cm, $context);

        $result = array();
        $result['status'] = true;
        $result['warnings'] = $warnings;
        return $result;
    }