Get file history form

@param HTTPRequest $request
@return Form|HTTPResponse
762121
public function fileHistoryForm($request = null)
    {
        // Get ID either from posted back value, or url parameter
        if (!$request) {
            $this->jsonError(400);
            return null;
        }
        $id = $request->param('ID');
        if (!$id) {
            $this->jsonError(400);
            return null;
        }
        $versionID = $request->param('VersionID');
        if (!$versionID) {
            $this->jsonError(400);
            return null;
        }
        $form = $this->getFileHistoryForm([
            'RecordID' => $id,
            'RecordVersion' => $versionID,
        ]);
        return $form;
    }
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');
    }
96452
public function getFileAction(Request $request)
    {
        $customerClient = $this->getFactory()->createCustomerClient();
        $customerTransfer = $customerClient->getCustomer();

        if (!$customerTransfer) {
            return $this->redirectResponseInternal(PayoneControllerProvider::ROUTE_LOGIN);
        }

        $getFileTransfer = new PayoneGetFileTransfer();
        $getFileTransfer->setReference($request->query->get('id'));
        $getFileTransfer->setCustomerId($customerTransfer->getIdCustomer());

        $response = $this->getClient()->getFile($getFileTransfer);

        if ($response->getStatus() === 'ERROR') {
            return $this->viewResponse(['errormessage' => $response->getCustomerErrorMessage()]);
        }

        $callback = function () use ($response) {
            echo base64_decode($response->getRawResponse());
        };

        return $this->streamedResponse($callback, 200, ["Content-type" => "application/pdf"]);
    }
70050
public function index(HTTPRequest $request = null)
    {
        $gallery = $this->Gallery();
        if ($this->Content && $gallery) {
            $hasLocation = stristr($this->Content, '$Gallery');
            if ($hasLocation) {
                /** @see Requirements_Backend::escapeReplacement */
                $galleryEscapedForRegex = addcslashes($gallery->forTemplate(), '\\$');
                $content = preg_replace(
                    '/(<p[^>]*>)?\\$Gallery(<\\/p>)?/i',
                    $galleryEscapedForRegex,
                    $this->Content
                );
                return [
                    'Content' => DBField::create_field('HTMLText', $content),
                    'Gallery' => ''
                ];
            }
        }

        return [
            'Content' => DBField::create_field('HTMLText', $this->Content),
            'Gallery' => $this->Gallery()
        ];
    }
780822
public function updateHistory(ServerRequestInterface $request): ResponseInterface
    {
        $modules = $this->module_service->findByInterface(ModuleHistoricEventsInterface::class, true);

        $this->updateStatus($modules, $request);

        return redirect(route('history'));
    }
1329277
public function getIsFrontend(HTTPRequest $request)
    {
        $adminPaths = static::config()->get('admin_url_paths');
        $adminPaths[] = AdminRootController::config()->get('url_base') . '/';
        $currentPath = rtrim($request->getURL(), '/') . '/';

        foreach ($adminPaths as $adminPath) {
            if (substr($currentPath, 0, strlen($adminPath)) === $adminPath) {
                return false;
            }
        }

        // If using the CMS preview, do not treat the site as frontend
        if ($request->getVar('CMSPreview')) {
            return false;
        }

        return true;
    }
1160955
public function makeRequest(Google_HttpRequest $request) {
    // First, check to see if we have a valid cached version.
    $cached = $this->getCachedRequest($request);
    if ($cached !== false) {
      if (!$this->checkMustRevaliadateCachedRequest($cached, $request)) {
        return $cached;
      }
    }

    $default_options = stream_context_get_options(stream_context_get_default());

    $requestHttpContext = array_key_exists('http', $default_options) ?
        $default_options['http'] : array();
    if (array_key_exists($request->getRequestMethod(),
          self::$ENTITY_HTTP_METHODS)) {
      $request = $this->processEntityRequest($request);
    }

    if ($request->getPostBody()) {
      $requestHttpContext["content"] = $request->getPostBody();
    }

    $requestHeaders = $request->getRequestHeaders();
    if ($requestHeaders && is_array($requestHeaders)) {
      $headers = "";
      foreach($requestHeaders as $k => $v) {
        $headers .= "$k: $v\n";
      }
      $requestHttpContext["header"] = $headers;
    }

    $requestHttpContext["method"] = $request->getRequestMethod();
    $requestHttpContext["user_agent"] = $request->getUserAgent();

    $requestSslContext = array_key_exists('ssl', $default_options) ?
        $default_options['ssl'] : array();

    if (!array_key_exists("cafile", $requestSslContext)) {
      $requestSslContext["cafile"] = dirname(__FILE__) . '/cacerts.pem';
    }

    $options = array("http" => array_merge(self::$DEFAULT_HTTP_CONTEXT,
                                                 $requestHttpContext),
                     "ssl" => array_merge(self::$DEFAULT_SSL_CONTEXT,
                                          $requestSslContext));

    $context = stream_context_create($options);

    $response_data = file_get_contents($request->getUrl(),
                                       false,
                                       $context);

    if (false === $response_data) {
      throw new Google_IOException("HTTP Error: Unable to connect");
    }

    $respHttpCode = $this->getHttpResponseCode($http_response_header);
    $responseHeaders = $this->getHttpResponseHeaders($http_response_header);

    if ($respHttpCode == 304 && $cached) {
      // If the server responded NOT_MODIFIED, return the cached request.
      $this->updateCachedRequest($cached, $responseHeaders);
      return $cached;
    }

    $request->setResponseHttpCode($respHttpCode);
    $request->setResponseHeaders($responseHeaders);
    $request->setResponseBody($response_data);
    // Store the request in cache (the function checks to see if the request
    // can actually be cached)
    $this->setCachedRequest($request);
    return $request;
  }
1012060
protected function getRequestOrigin(HTTPRequest $request)
    {
        // Prefer Origin header
        $origin = $request->getHeader('Origin');
        if ($origin) {
            return $origin;
        }

        // Check referer
        $referer = $request->getHeader('Referer');
        if ($referer) {
            // Extract protocol, hostname, and port
            $refererParts = parse_url($referer);
            if (!$refererParts) {
                return null;
            }
            // Rebuild
            $origin = $refererParts['scheme'] . '://' . $refererParts['host'];
            if (isset($refererParts['port'])) {
                $origin .= ':' . $refererParts['port'];
            }
            return $origin;
        }

        return null;
    }
964456
public function cgetAction(Request $request)
    {
        // required parameter
        $locale = $this->getRequestParameter($request, 'locale', true);
        $entityClass = $this->getRequestParameter($request, 'entityClass', true);
        $entityId = $this->getRequestParameter($request, 'entityId', true);

        // optional parameter
        $history = $this->getBooleanRequestParameter($request, 'history', false, false);

        $routes = $this->findRoutes($history, $entityClass, $entityId, $locale);

        return $this->handleView($this->view(new CollectionRepresentation($routes, 'routes')));
    }
999889
public function preview(SS_HTTPRequest $request)
    {
        $file = File::get()
            ->byID($request->param('FileID'));
        if (!$file) {
            return "file not found";
        }
        //TODO: validate file?
        $mapper = new CSVFieldMapper($file->getFullPath());
        $mapper->setMappableCols($this->getMappableColumns());
        //load previously stored values
        if ($cachedmapping = $this->getCachedMapping()) {
            $mapper->loadDataFrom($cachedmapping);
        }

        $form = $this->MapperForm();
        $form->Fields()->unshift(
            new LiteralField('mapperfield', $mapper->forTemplate())
        );
        $form->Fields()->push(new HiddenField("BackURL", "BackURL", $this->getBackURL($request)));
        $form->setFormAction($this->Link('import').'/'.$file->ID);
        $content = ArrayData::create(array(
            'File' => $file,
            'MapperForm'=> $form
        ))->renderWith('GridFieldImporter_preview');
        $controller = $this->getToplevelController();

        return $controller->customise(array(
            'Content' => $content
        ));
    }
905333
public function view($request)
    {
        if (!$this->currentRecord) {
            return $this->httpError(404, "{$this->recordType} not found");
        }
        if (!$this->currentRecord->canView()) {
            return $this->httpError(403, "You do not have permission to view this {$this->recordType}");
        }
        $form = $this->Form();
        $form->setActions(new FieldList());
        $form->makeReadonly();
        return $this->customise(array('Form' => $form));
    }
1014289
protected function requestFromRequest(Request $request, $changeHistory = true)
    {
        return $this->request($request->getMethod(), $request->getUri(), $request->getParameters(), $request->getFiles(), $request->getServer(), $request->getContent(), $changeHistory);
    }
907329
protected static function currentRequest(HTTPRequest $request = null)
    {
        // Ensure we only use a registered HTTPRequest and don't
        // incidentally construct a singleton
        if (!$request && Injector::inst()->has(HTTPRequest::class)) {
            $request = Injector::inst()->get(HTTPRequest::class);
        }
        return $request;
    }
653289
public function detailAction(Request $request)
    {
        $id = $request->get('id');

        $volume = $this->get('phlexible_media_manager.volume_manager')->getByFileId($id);
        $userManager = $this->get('phlexible_user.user_manager');

        $detail = [];
        foreach ($volume->findFileVersions($id) as $fileVersion) {
            $createUser = $userManager->find($fileVersion->getCreateUserId());

            $detail[] = [
                'id' => $fileVersion->getFile()->getId(),
                'folder_id' => $fileVersion->getFile()->getFolderId(),
                'name' => $fileVersion->getName(),
                'size' => $fileVersion->getSize(),
                'version' => $fileVersion->getVersion(),
                'document_type_key' => strtolower($fileVersion->getMediaType()),
                'asset_type' => strtolower($fileVersion->getMediaCategory()),
                'create_user_id' => $fileVersion->getCreateUserId(),
                'create_user' => $createUser ? $createUser->getUsername() : 'Unknown',
                'create_time' => $fileVersion->getCreatedAt()->format('Y-m-d H:i:s'),
            ];
        }

        return new JsonResponse(
            [
                'detail' => $detail,
            ]
        );
    }
920957
public function upload(HTTPRequest $request)
    {
        $assetAdmin = AssetAdmin::singleton();
        $uploadResponse = $assetAdmin->apiCreateFile($request);
        
        if ($uploadResponse->getStatusCode() == 200)
        {
            $responseData = Convert::json2array($uploadResponse->getBody());
            $responseData = array_shift($responseData);

            $record = $this->createDataObject($responseData['id']);

            $bulkToolsResponse = new HTTPBulkToolsResponse(false, $this->gridField);
            $bulkToolsResponse->addSuccessRecord($record);
            
            $responseData['bulkTools'] = json_decode($bulkToolsResponse->getBody());
            $uploadResponse->setBody(json_encode(array($responseData)));
        }

        return $uploadResponse;
    }
126301
public function readCampaign(HTTPRequest $request)
    {
        $response = new HTTPResponse();
        $accepts = $request->getAcceptMimetypes();

        //accept 'text/json' for legacy reasons
        if (in_array('application/json', $accepts) || in_array('text/json', $accepts)) {
            $response->addHeader('Content-Type', 'application/json');
            if (!$request->param('Name')) {
                return (new HTTPResponse(null, 400));
            }

            /** @var ChangeSet $changeSet */
            $changeSet = ChangeSet::get()->byID($request->param('ID'));
            if (!$changeSet) {
                return (new HTTPResponse(null, 404));
            }

            if (!$changeSet->canView()) {
                return (new HTTPResponse(null, 403));
            }

            $body = json_encode($this->getChangeSetResource($changeSet, true));
            return (new HTTPResponse($body, 200))
                ->addHeader('Content-Type', 'application/json');
        } else {
            return $this->index($request);
        }
    }
1323453
public function fetchArchiveAction(Request $request)
    {
        $url = $request->request->get('url');

        $file = file_get_contents($url);
        $tmp = @tempnam('claro', '_zip');
        file_put_contents($tmp, $file);
        $file = new File($tmp);
        $object = $this->fileUtils->createFile($file);
        $archive = $this->serializer->serialize($object);
        $zip = new \ZipArchive();
        $zip->open($this->fileUtils->getPath($object));
        $json = $zip->getFromName('workspace.json');
        $zip->close();

        $data = json_decode($json, true);
        $data['archive'] = $archive;

        return new JsonResponse($data);
    }