List browse on the server, so we can insert them in the file input.

@param Request $request
@param string  $namespace
@param string  $path

@return \Bolt\Response\TemplateResponse
486497
public function browse(Request $request, $namespace, $path)
    {
        $directory = $this->filesystem()->getDir("$namespace://$path");
        $listing = new Listing($directory);
        $showHidden = $this->isAllowed('files:hidden');

        try {
            $directories = $listing->getDirectories($showHidden);
            $files = $listing->getFiles($showHidden);
        } catch (IOException $e) {
            $this->logException(Trans::__('page.file-management.message.folder-not-found', ['%s' => $path]), $e);
            $directories = [];
            $files = [];
        }

        $context = [
            'directory'   => $directory,
            'directories' => $directories,
            'files'       => $files,
            'multiselect' => $request->query->getBoolean('multiselect'),
        ];

        return $this->render('@bolt/async/browse.twig', ['context' => $context]);
    }
665684
public function showPage(Request $request, $path = '')
  {
    // Redirect trailing slash
    $uri = $request->getRequestUri();
    // if (preg_match('/(.+)\/$/', $request->getRequestUri()) !== 0)
    if (strlen($uri) > 1 && substr($uri, -1) === '/') {
      return redirect(rtrim($request->path(), '/'), 301);
    }

    // Parse the request path
    $pathInfo = LocaleService::parsePath($path);
    $pagePath = $pathInfo->pagePath;

    // Set the active language
    LocaleService::setLang($pathInfo->lang);

    // 'index' is a reserved name
    if ($pagePath === '/index') {
      error_log("index is a reserved name.");
      abort(404);
    }

    // Get the views' directory
    $viewsPath = base_path() . '/resources/views/';
    if (!is_dir($viewsPath)) {
      error_log("The directory /resources/views/ doesn't exists.");
      throw new PathNotFoundException();
    }

    // Compute the view name to be showed
    $showView = '';
    if ($pagePath === '/') {
      $showView = 'index';
    }
    else {
      $showView = ltrim(str_replace('/', '.', $pagePath), '.');
    }

    // If the view doesn't exists return a 404 Not Found
    if (!view()->exists($showView)) {
      abort(404, "View not found: $showView");
    }

    // Initialize the LocaleLinkService used inside views to set links
    LocaleLinkService::setLang($pathInfo->lang);
    LocaleLinkService::setLangDir($pathInfo->langDir);
    LocaleLinkService::setPagePath($pathInfo->pagePath);

    // Return the requested view
    return view($showView, [
      'benjamin' => 'benjamin::html',
      'activeLang' => LocaleService::getActiveLang(),
    ]);
  }
103165
public function addPath($path, $namespace = null)
    {
        $key = (is_null($namespace)) ? $path : $namespace . '::' . $path;

        $this->fullQualifiedPathNameWithTemplatePath[$key] = new TemplatePath($path, $namespace);
    }
1002019
public function createFolder(Request $request)
    {
        $namespace = $request->request->get('namespace');
        $parentPath = $request->request->get('parent');
        $folderName = $request->request->get('foldername');

        try {
            $dir = $this->filesystem()->getDir("$namespace://$parentPath/$folderName");
            $dir->create();

            return $this->json($dir->getPath(), Response::HTTP_OK);
        } catch (IOException $e) {
            $msg = Trans::__('Unable to create directory: %DIR%', ['%DIR%' => $folderName]);
            $this->logException($msg, $e);

            return $this->json($msg, Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }
407196
public function listAction(Request $request)
    {
        return $this->render('SynapsePageBundle:Admin/Page:list.html.twig', array(
            'pages' => $this->container->get('synapse.page.loader')->retrieveAll(),
            'page_rendering_route' => $this->container->getParameter('synapse.page.rendering_route'),
        ));
    }
264120
public function edit(Request $request, $namespace, $file)
    {
        /** @var File $file */
        $file = $this->filesystem()->getFile("$namespace://$file");

        if (!$file->authorized()) {
            $this->flashes()->error(Trans::__('general.phrase.access-denied-permissions-edit-file', ['%s' => $file->getPath()]));

            return $this->redirectToRoute('dashboard');
        }

        try {
            $contents = $file->read();
        } catch (FileNotFoundException $e) {
            $this->flashes()->error(Trans::__('general.phrase.file-not-exist', ['%s' => $file->getPath()]));

            return $this->redirectToRoute('dashboard');
        } catch (IOException $e) {
            $this->flashes()->error(Trans::__('general.phrase.file-not-readable', ['%s' => $file->getPath()]));

            return $this->redirectToRoute('dashboard');
        }

        $data = compact('contents');
        $options = [
            'write_allowed'        => true,
            'contents_allow_empty' => $file->getExtension() !== 'yml' ?: false,
            'contents_constraints' => $file->getExtension() === 'yml' ? [new Constraints\Yaml()] : [],
        ];
        /** @var Form $form */
        $form = $this->createFormBuilder(FileEditType::class, $data, $options)
            ->getForm()
        ;

        // Handle the POST and check if it's valid.
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid() && $form->get('save')->isClicked()) {
            return $this->handleEdit($form, $file);
        }
        if ($form->isSubmitted() && !$form->isValid()) {
            return $this->json([
                'ok'  => false,
                'msg' => Trans::__('page.file-management.message.save-failed-invalid-form', ['%s' => $file->getPath()]),
            ]);
        }

        $context = [
            'form'              => $form->createView(),
            'file'              => $file,
            'write_allowed'     => true,
            'related'           => $this->getRelatedFiles($file),
            'datechanged'       => $file->getCarbon()->toIso8601String(),
            'codeMirrorPlugins' => $this->getCodeMirrorPlugins($file),
        ];

        return $this->render('@bolt/editfile/editfile.twig', $context);
    }
829701
public function listAction(Request $request, $parent, $class = ResourceNode::class)
    {
        $options = $request->query->all();

        if ($parent) {
            // grab directory content
            $parentNode = $this->om
                ->getRepository(ResourceNode::class)
                ->findOneBy(['uuid' => $parent]);

            $options['hiddenFilters']['parent'] = $parentNode ? $parentNode->getId() : null;

            if ($parentNode) {
                $permissions = $this->rightsManager->getCurrentPermissionArray($parentNode);

                if (!isset($permissions['administrate']) || !$permissions['administrate']) {
                    $options['hiddenFilters']['published'] = true;
                    $options['hiddenFilters']['hidden'] = false;
                }
            }
        } else {
            $options['hiddenFilters']['parent'] = null;
        }
        $options['hiddenFilters']['active'] = true;
        $options['hiddenFilters']['resourceTypeEnabled'] = true;

        //fix the very large list at the root
        //todo: when impersonating is fixed for easy testing, do that kind of stuff everywhere (not only at the root level)
        //directly in the finder
        //it currently work (altough we can see stuff we shouldnt do through the api)

        $roles = array_map(
            function ($role) { return $role->getRole(); },
            $this->container->get('security.token_storage')->getToken()->getRoles()
        );

        if (!in_array('ROLE_ADMIN', $roles) || null === $options['hiddenFilters']['parent']) {
            $options['hiddenFilters']['roles'] = $roles;
        }

        return new JsonResponse(
            $this->finder->search(ResourceNode::class, $options)
        );
    }
366750
public static function addPath ($path, $namespace = \Twig_Loader_Filesystem::MAIN_NAMESPACE)
    {
        $twigLoader = self::getTwigLoader();
        /* @var $twigLoader \Twig_Loader_Filesystem */
        $twigLoader->addPath($path, $namespace);
    }
410136
protected function loadBackendRoutesFrom($path, $namespace = null)
    {
        if (AreasManager::manager()->isFrontendArea()) {
            return;
        }

        if (!$this->isPathIncluded($path)) {
            $foundation = $this->app->make('antares.app');
            $namespace  = $namespace ?: $this->namespace;
            $foundation->namespaced($namespace, $this->getRouteLoader($path));
        }
    }
415956
private function handleUploadFiles(Request $request, $namespace, $files = null)
    {
        $filesToProcess = $this->getFilesToProcess($request, $namespace, $files);

        /** @var \Sirius\Upload\Result\Collection $result */
        $result = $this->app['upload']->process($filesToProcess);

        if ($result->isValid()) {
            if (!$this->app['config']->get('general/upload/autoconfirm')) {
                // Remove the .lock file attached to the file
                $result->confirm();
            }

            $successfulFiles = [];
            foreach ($result as $resultFile) {
                $successfulFiles[] = $this->filesystem()->toJs($namespace . '://' . $resultFile->name);
            }

            return $successfulFiles;
        }

        // The file that was saved during process() has a .lock file attached
        // and can now be cleared, in the case where form processing fails
        try {
            $result->clear();
        } catch (\Exception $e) {
            // It's an error state anyway
        }

        $errorFiles = [];
        foreach ($result as $resultFile) {
            $errors = $resultFile->getMessages();
            $errorFiles[] = [
                    'name'  => $resultFile->original_name,
                    'error' => (string) $errors[0],
                ];
        }

        return $errorFiles;
    }
419093
public function cgetAction(Request $request)
    {
        $webspaceKey = $request->get('webspace');

        /** @var WebspaceManagerInterface $webspaceManager */
        $webspaceManager = $this->get('sulu_core.webspace.webspace_manager');

        $webspace = $webspaceManager->findWebspaceByKey($webspaceKey);

        if ($webspace) {
            $localizations = new CollectionRepresentation($webspace->getAllLocalizations(), 'localizations');
            $view = $this->view($localizations, 200);
        } else {
            $error = new RestException(sprintf('No webspace found for key \'%s\'', $webspaceKey));
            $view = $this->view($error->toArray(), 400);
        }

        return $this->handleView($view);
    }
659244
public function indexAction(Request $request)
    {

        /** @var \Networking\InitCmsBundle\Lib\PhpCacheInterface $phpCache */
        $phpCache = $this->get('networking_init_cms.lib.php_cache');

        /** @var PageSnapshotInterface $page */
        $page = $request->get('_content');

        $template = $request->get('_template');
        if ($template instanceof \Sensio\Bundle\FrameworkExtraBundle\Configuration\Template) {
            $template = $template->getTemplate();
        }
        $user = $this->getUser();

        if ($phpCache->isCacheable($request, $user) && $page instanceof PageSnapshotInterface) {
            if (!$this->isSnapshotActive($page)) {
                throw new NotFoundHttpException();
            }

            if ($this->getSnapshotVisibility($page) != PageInterface::VISIBILITY_PUBLIC) {
                if (false === $this->get('security.authorization_checker')->isGranted('ROLE_USER')) {
                    throw new AccessDeniedException();
                }
            }

            $updatedAt = $phpCache->get(sprintf('page_%s_created_at', $page->getId()));
            $cacheKey = $request->getLocale().$request->getPathInfo();

            if ($updatedAt != $page->getSnapshotDate()) {
                $phpCache->delete($cacheKey);
            }

            $response = $phpCache->get($request->getLocale().$request->getPathInfo());

            if (!$response || !$response instanceof Response) {
                $params = $this->getPageParameters($request);

                if ($params instanceof RedirectResponse) {
                    return $params;
                }
                $html = $this->renderView(
                    $template,
                    $params
                );
                $response = new Response($html);

                $phpCache->set($cacheKey, $response);
                $phpCache->set(sprintf('page_%s_created_at', $page->getId()), $page->getSnapshotDate());
            } else {
                $phpCache->touch($cacheKey);
                $phpCache->touch(sprintf('page_%s_created_at', $page->getId()));
            }
        } else {
            $params = $this->getPageParameters($request);

            if ($params instanceof RedirectResponse) {
                return $params;
            }
            $html = $this->renderView(
                $template,
                $params
            );
            $response = new Response($html);
        }

        if ($this->getPageHelper()->isAllowLocaleCookie() && !$this->getPageHelper()->isSingleLanguage()) {
            $response->headers->setCookie(new Cookie('_locale', $request->getLocale()));
        }

        return $response;
    }
108655
public function cgetAction($webspace, Request $request)
    {
        // TODO pagination

        $result = $this->get('sulu_custom_urls.manager')->findList($webspace);

        $list = new RouteAwareRepresentation(
            new CollectionRepresentation($result, self::$relationName),
            'cget_webspace_custom-urls',
            array_merge($request->request->all(), ['webspace' => $webspace])
        );

        return $this->handleView($this->view($list));
    }
1147256
private function doRequest($path, $headers = [])
    {
        if (!$this->isAvailable()) {
            throw new NotAvailableException('Service not available.');
        }

        if ($this->loadBalance !== null) {
            $uri = $this->loadBalance->getUri($this->serviceName);
            $this->zendClient->setUri($uri);
        }
        if ($this->appendPath && strlen($path) > 0 && $this->zendClient->getUri()->getPath() != '/') {
            $path = $this->zendClient->getUri()->getPath() . $path;
        }
        $this->zendClient->getUri()->setPath($path);

        $this->zendClient->getRequest()->getHeaders()->addHeaders($headers);

        if (!$this->zendClient->getRequest()->getHeaders()->has('X-Request-Id')) {
            $this->addRequestId();
        }

        $this->addRequestName($this->serviceName);

        $this->getEventManager()->trigger('request.pre', $this);

        $this->responseTime = 0;

        try {
            $requestTime = microtime(true);

            $zendHttpResponse = $this->zendClient->send();

            $this->responseTime = (float) sprintf('%.2f', (microtime(true) - $requestTime) * 1000);

            $this->addRequestTime($this->responseTime);

            $response = new Response($this->zendClient, $zendHttpResponse, $this->depth);
            $this->reportSuccess();
        } catch (RuntimeException $ex) {
            $this->reportFailure();
            $this->getEventManager()->trigger('request.fail', $this, $ex);
            throw new RuntimeException($ex->getMessage(), $ex->getCode(), $ex);
        } catch (\Exception $ex) {
            $this->reportFailure();
            $this->getEventManager()->trigger('request.fail', $this, $ex);
            throw new RuntimeException($ex->getMessage(), 500, $ex);
        }

        $this->getEventManager()->trigger('request.post', $this);

        $content = $response->getContent();

        return $content;
    }
669615
private function listCommands(array &$list, $path, $namespace)
    {
        $classes = [];
        list_classes($classes, $path, $namespace);
        foreach ($classes as $class) {
            /** @var CommandContract $command */
            $command = new $class;
            $name = $command->name();
            $description = trim($command->description() ?: '');
            $list[$name] = compact('class', 'name', 'description');
        }
    }
870180
public function registerNamespace($namespace, $path)
    {
        $namespace = trim($namespace, '\\');
        $this->_namespaces[$namespace] = (array) $path;

        krsort($this->_namespaces, SORT_STRING);

        return $this;
    }
897616
protected function loadConfigurationFiles($path, $namespace)
	{
		foreach ($this->getConfigurationFiles($path) as $key => $file)
		{
			$configs = require $file;
			$this->setConfigsInNamespace($configs, $key, $namespace);
		}
	}