Gets the contents of a folder, and applies a sort. Splits the response
into folder metadata and folder children

@param  SS_HTTPRequest $request
@return SS_HTTPResponse
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');
    }
207216
public function moveFolderAction(Request $request)
    {
        $facade = $this->get('jms_serializer')->deserialize(
            $request->getContent(),
            'OpenOrchestra\MediaAdminBundle\Facade\FolderFacade',
            $request->get('_format', 'json')
        );
        $folder = $this->get('open_orchestra_media.repository.media_folder')->findOneById($facade->id);
        $this->denyAccessUnlessGranted(ContributionActionInterface::EDIT, $folder);

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

        $this->get('object_manager')->flush();

        return array();
    }
641237
public function index(ServerRequestInterface $request): ResponseInterface
    {
        $files        = $request->getQueryParams()['files'] ?? 'local'; // local|unused|external
        $media_folder = $request->getQueryParams()['media_folder'] ?? '';
        $subfolders   = $request->getQueryParams()['subfolders'] ?? 'include'; // include/exclude

        $media_folders = $this->allMediaFolders();

        // Preserve the pagination/filtering/sorting between requests, so that the
        // browser’s back button works. Pagination is dependent on the currently
        // selected folder.
        $table_id = md5($files . $media_folder . $subfolders);

        $title = I18N::translate('Manage media');

        return $this->viewResponse('admin/media', [
            'data_folder'   => WT_DATA_DIR,
            'files'         => $files,
            'media_folder'  => $media_folder,
            'media_folders' => $media_folders,
            'subfolders'    => $subfolders,
            'table_id'      => $table_id,
            'title'         => $title,
        ]);
    }
71012
public function process(\SS_HTTPRequest $request)
    {
        $results = [];

        foreach ($this->processors as $identifier => $processor) {

            $results[$identifier] = $processor->process($request);

        }

        return $results;
    }
1029146
public function index(SS_HTTPRequest $request)
    {
        $doc = $this->getDocumentFromID($request);

        if (!empty($doc)) {
            $canView = $doc->canView();

            if ($canView) {
                $path = $doc->getFullPath();
                if (is_file($path)) {
                    $fileBin = trim(`whereis file`);
                    if (function_exists('finfo_file')) {
                        // discover the mime type properly
                        $finfo = finfo_open(FILEINFO_MIME_TYPE);
                        $mime = finfo_file($finfo, $path);
                    } elseif (is_executable($fileBin)) {
                        $path = escapeshellarg($path);
                        // try to use the system tool
                        $mime = `$fileBin -i -b $path`;
                        $mime = explode(';', $mime);
                        $mime = trim($mime[0]);
                    } else {
                        // make do with what we have
                        $ext = $doc->getExtension();
                        if ($ext == 'pdf') {
                            $mime = 'application/pdf';
                        } elseif ($ext == 'html' || $ext =='htm') {
                            $mime = 'text/html';
                        } else {
                            $mime = 'application/octet-stream';
                        }
                    }

                    if (self::$testMode) {
                        return $path;
                    }

                    // set fallback if no config nor file-specific value
                    $disposition = 'attachment';

                    // file-specific setting
                    if ($doc->DownloadBehavior == 'open') {
                        $disposition = 'inline';
                    }

                    //if a DMSDocument can be downloaded and all the permissions/privileges has passed,
                    //its ViewCount should be increased by 1 just before the browser sending the file to front.
                    $doc->trackView();

                    return $this->sendFile($path, $mime, $doc->getFilenameWithoutID(), $disposition);
                }
            }
        }
643788
public function listAction(Request $request): Response
    {
        $page = $request->query->get('page') ?? 1;

        $pagerfanta = new Pagerfanta(
            new ArrayAdapter($this->sectionService->loadSections())
        );

        $pagerfanta->setMaxPerPage($this->defaultPaginationLimit);
        $pagerfanta->setCurrentPage(min($page, $pagerfanta->getNbPages()));

        /** @var \eZ\Publish\API\Repository\Values\Content\Section[] $sectionList */
        $sectionList = $pagerfanta->getCurrentPageResults();
        $contentCountBySectionId = [];
        $deletableSections = [];
        $assignableSections = [];

        $deleteSectionsForm = $this->formFactory->deleteSections(
            new SectionsDeleteData($this->getSectionsNumbers($sectionList))
        );

        $assignContentForms = $this->formFactory->assignContentSectionForm(
            new SectionContentAssignData()
        );

        foreach ($sectionList as $section) {
            $contentCountBySectionId[$section->id] = $this->sectionService->countAssignedContents($section);
            $deletableSections[$section->id] = !$this->sectionService->isSectionUsed($section);
            $assignableSections[$section->id] = $this->canUserAssignSectionToSomeContent($section);
        }

        return $this->render('@ezdesign/admin/section/list.html.twig', [
            'can_edit' => $this->isGranted(new Attribute('section', 'edit')),
            'can_assign' => $this->isGranted(new Attribute('section', 'assign')),
            'pager' => $pagerfanta,
            'content_count' => $contentCountBySectionId,
            'deletable' => $deletableSections,
            'assignable' => $assignableSections,
            'form_sections_delete' => $deleteSectionsForm->createView(),
            'form_section_content_assign' => $assignContentForms->createView(),
        ]);
    }
717270
public function renameFolder(Request $request)
    {
        $namespace = $request->request->get('namespace');
        $parent = $request->request->get('parent');
        $oldName = $request->request->get('oldname');
        $newName = $request->request->get('newname');

        try {
            $dir = $this->filesystem()->getDir("$namespace://$parent/$oldName");
            if (!$dir) {
                return $this->json(
                    sprintf("Only directories are allowed to be renamed with this method"),
                    Response::HTTP_BAD_REQUEST
                );
            }
            $this->filesystem()->rename("$namespace://$parent/$oldName", "$parent/$newName");

            return $this->json($newName, Response::HTTP_OK);
        } catch (ExceptionInterface $e) {
            $msg = Trans::__('Unable to rename directory: %DIR%', ['%DIR%' => $oldName]);
            $this->logException($msg, $e);

            if ($e instanceof FileExistsException) {
                $status = Response::HTTP_CONFLICT;
            } elseif ($e instanceof FileNotFoundException) {
                $status = Response::HTTP_NOT_FOUND;
            } else {
                $status = Response::HTTP_INTERNAL_SERVER_ERROR;
            }

            return $this->json($msg, $status);
        }
    }
540401
public function get_items( $request ) {
		$data = array();
		$statuses = get_post_stati( array( 'internal' => false ), 'object' );
		$statuses['trash'] = get_post_status_object( 'trash' );
		foreach ( $statuses as $slug => $obj ) {
			$ret = $this->check_read_permission( $obj );
			if ( ! $ret ) {
				continue;
			}
			$status = $this->prepare_item_for_response( $obj, $request );
			$data[ $obj->name ] = $this->prepare_response_for_collection( $status );
		}
		return rest_ensure_response( $data );
	}
77798
public function propertiesAction(Request $request)
    {
        $folderId = $request->get('folder_id');
        $volumeManager = $this->get('phlexible_media_manager.volume_manager');
        $volume = $volumeManager->getByFolderId($folderId);

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

            $calculator = new SizeCalculator();
            $calculatedSize = $calculator->calculate($volume, $folder);

            $data = [
                'title' => $folder->getName(),
                'type' => 'folder',
                'path' => '/'.$folder->getPath(),
                'size' => $calculatedSize->getSize(),
                'files' => $calculatedSize->getNumFiles(),
                'folders' => $calculatedSize->getNumFolders(),
                'create_time' => $folder->getCreatedAt()->format('U') * 1000,
                'create_user' => $folder->getCreateUserId(),
                'modify_time' => $folder->getModifiedAt()->format('U') * 1000,
                'modify_user' => $folder->getModifyUserId(),
            ];
        } catch (\Exception $e) {
            $data = [];
        }

        return new JsonResponse($data);
    }
887167
public function index(HTTPRequest $request)
    {
        $stage = $request->param('Stage');
        if ($stage && in_array($stage, [Versioned::DRAFT, Versioned::LIVE])) {
            Versioned::set_stage($stage);
        }
        // Check for a possible CORS preflight request and handle if necessary
        // Refer issue 66:  https://github.com/silverstripe/silverstripe-graphql/issues/66
        if ($request->httpMethod() === 'OPTIONS') {
            return $this->handleOptions($request);
        }

        // Main query handling
        try {
            $manager = $this->getManager($request);
            // Parse input
            list($query, $variables) = $this->getRequestQueryVariables($request);

            // Run query
            $result = $manager->query($query, $variables);
        } catch (Exception $exception) {
            $error = ['message' => $exception->getMessage()];

            if (Director::isDev()) {
                $error['code'] = $exception->getCode();
                $error['file'] = $exception->getFile();
                $error['line'] = $exception->getLine();
                $error['trace'] = $exception->getTrace();
            }

            $result = [
                'errors' => [$error]
            ];
        }

        $response = $this->addCorsHeaders($request, new HTTPResponse(json_encode($result)));
        return $response->addHeader('Content-Type', 'application/json');
    }
1298692
public function get_dir(Request $request)
    {

        $root = base_path() . DIRECTORY_SEPARATOR;
        $postDir = rawurldecode(base_path($request->get('dir')));

        if (file_exists($postDir))
        {
            $files = scandir($postDir);
            $returnDir = substr($postDir, strlen($root));
            natcasesort($files);

            if (count($files) > 2)
            { // The 2 accounts for . and ..
                echo "<ul class='jqueryFileTree'>";
                foreach ($files as $file)
                {
                    $htmlRel = htmlentities($returnDir . $file);
                    $htmlName = htmlentities($file);
                    $ext = preg_replace('/^.*\./', '', $file);
                    if (file_exists($postDir . $file) && $file != '.' && $file != '..')
                    {
                        if (is_dir($postDir . $file))
                        {
                            echo "<li class='directory collapsed'><a rel='" . $htmlRel . "/'>" . $htmlName . "</a></li>";
                        }
                        else
                        {
                            echo "<li class='file ext_{$ext}'><a rel='" . $htmlRel . "'>" . $htmlName . "</a></li>";
                        }
                    }
                }
                echo "</ul>";
            }
        }
    }
1006470
protected function getSortOrder(Request $request)
    {
        $sort = array();

        $order = $request->query->get('order', array());

        $columns = $this->getSortColumns($request);

        foreach ($order as $setting) {
            $index = $setting['column'];

            if (array_key_exists($index, $columns)) {
                $column = $columns[$index];

                if (!is_array($column)) {
                    $column = array($column);
                }

                foreach ($column as $c) {
                    $sort[] = array(
                        $c,
                        $setting['dir'],
                    );
                }
            }
        }

        // Default sort order
        if (empty($sort)) {
            $sort = $this->getDefaultSortOrder($request);
        }

        return $sort;
    }
827324
public function listAction(Request $request)
    {
        if (!$request->isXmlHttpRequest()) {
            throw new NotFoundHttpException();
        }

        $root = $this->getFolderRepository()->findRoot();
        if (null !== $id = $request->query->get('folderId')) {
            if (!$this->activateFolderById($id, $root)) {
                $root->setActive(true);
            }
        } else {
            $root->setActive(true);
        }

        $folders = $this->get('jms_serializer')->serialize(
            array($root),
            'json',
            SerializationContext::create()->setGroups(array('Manager'))
        );

        $response = new Response($folders);
        $response->headers->add(array('Content-Type' => 'application/json'));

        return $response;
    }
1003458
public function listAction(Request $request)
    {
        $query = $this->addOrganizationFilter($request->query->all());

        return new JsonResponse($this->finder->search(
            $this->getClass(),
            $query,
            []
        ));
    }
1284210
private function getDumpedIndexResponse(Request $request)
    {
        /** @var Portal $portal */
        $portal = $request->get('_sulu')->getAttribute('portal');
        $localization = $request->get('_sulu')->getAttribute('localization');
        if (!$localization) {
            $localization = $portal->getXDefaultLocalization();
        }

        $path = $this->get('sulu_website.sitemap.xml_dumper')->getIndexDumpPath(
            $request->getScheme(),
            $portal->getWebspace()->getKey(),
            $localization->getLocale(),
            $request->getHttpHost()
        );

        if (!$this->get('filesystem')->exists($path)) {
            return;
        }

        return $this->createBinaryFileResponse($path);
    }
666576
public function cgetAction(Request $request)
    {
        $locale = $this->getRequestParameter($request, 'locale', true);
        $fieldDescriptors = $this->getFieldDescriptors($locale, false);
        $types = array_filter(explode(',', $request->get('types')));
        $listBuilder = $this->getListBuilder($request, $fieldDescriptors, $types);
        $listBuilder->setParameter('locale', $locale);
        $listResponse = $listBuilder->execute();
        $count = $listBuilder->count();

        for ($i = 0, $length = count($listResponse); $i < $length; ++$i) {
            $format = $this->getFormatManager()->getFormats(
                $listResponse[$i]['id'],
                $listResponse[$i]['name'],
                $listResponse[$i]['storageOptions'],
                $listResponse[$i]['version'],
                $listResponse[$i]['subVersion'],
                $listResponse[$i]['mimeType']
            );

            if (0 < count($format)) {
                $listResponse[$i]['thumbnails'] = $format;
            }

            $listResponse[$i]['url'] = $this->getMediaManager()->getUrl(
                $listResponse[$i]['id'],
                $listResponse[$i]['name'],
                $listResponse[$i]['version']
            );
        }

        $ids = $listBuilder->getIds();
        if (null != $ids) {
            $result = [];
            foreach ($listResponse as $item) {
                $result[array_search($item['id'], $ids)] = $item;
            }
            ksort($result);
            $listResponse = array_values($result);
        }

        $list = new ListRepresentation(
            $listResponse,
            self::$entityKey,
            'cget_media',
            $request->query->all(),
            $listBuilder->getCurrentPage(),
            $listBuilder->getLimit(),
            $count
        );

        $view = $this->view($list, 200);

        return $this->handleView($view);
    }
7959
public function deleteAction(Request $request)
    {
        $volumeId = $request->get('site_id');
        $folderId = $request->get('folder_id');

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

        if ($folder->isRoot()) {
            return new ResultResponse(false, "Can't delete the root folder.");
        }

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

        return new ResultResponse(true, 'Folder deleted', ['parent_id' => $folder->getParentId()]);
    }