Get file edit form

@param HTTPRequest $request
@return Form|HTTPResponse
189481
public function fileEditForm($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;
        }
        return $this->getFileEditForm($id);
    }
501658
public function indexAction(Request $request)
    {
        $fileEntity = new UploadFile();

        $form = $this->createForm(UploadFileType::class, $fileEntity, [
            'method' => 'POST',
        ]);

        $form->handleRequest($request);

        if ($form->isValid()) {
            /* @noinspection PhpUndefinedMethodInspection */
            if (!$fileEntity->getFile()->getError()) {
                $fileEntity->move($this->getParameter('kernel.root_dir') . '/../' . $this->getParameter('compo_import.upload_dir'));

                $this->getDoctrine()->getManager()->persist($fileEntity);
                $this->getDoctrine()->getManager()->flush();

                $this->runCommand($fileEntity);

                $this->getDoctrine()->getManager()->persist($fileEntity);
                $this->getDoctrine()->getManager()->flush();

                return $this->redirect($this->admin->generateUrl('upload', [
                    'import_id' => $fileEntity->getId(),
                ]));
            }

            /* @noinspection PhpUndefinedMethodInspection */
            $form->get('file')->addError(new FormError($fileEntity->getFile()->getErrorMessage()));
        }

        /** @var AbstractAdmin $admin */
        $admin = $this->get('sonata.admin.pool')->getInstance($this->admin->getCode());

        $builder = $admin->getExportFields();

        return $this->renderWithExtraParams('@CompoImport/Default/index.html.twig', [
            'form' => $form->createView(),
            'base_template' => $this->getBaseTemplate(),
            'builder' => $builder,
            'action' => 'import',
            'letters' => $this->getLetterArray(),
        ]);
    }
922451
public function edit(Request $request)
    {
        return view('gzero-core::account.edit', [
            'isUserEmailSet' => strpos($request->user()->email, '@'),
            'timezones'      => $this->timezones->getAvailableTimezones()
        ]);
    }
925991
public function apiHistory(HTTPRequest $request)
    {
        // CSRF check not required as the GET request has no side effects.
        $fileId = $request->getVar('fileId');

        if (!$fileId || !is_numeric($fileId)) {
            $this->jsonError(400);
            return null;
        }

        $class = File::class;
        $file = DataObject::get($class)->byID($fileId);

        if (!$file) {
            $this->jsonError(404);
            return null;
        }

        if (!$file->canView()) {
            $this->jsonError(403);
            return null;
        }

        $versions = Versioned::get_all_versions($class, $fileId)
            ->limit($this->config()->max_history_entries)
            ->sort('Version', 'DESC');

        $output = array();
        $next = array();
        $prev = null;

        // swap the order so we can get the version number to compare against.
        // i.e version 3 needs to know version 2 is the previous version
        $copy = $versions->map('Version', 'Version')->toArray();
        foreach (array_reverse($copy) as $k => $v) {
            if ($prev) {
                $next[$v] = $prev;
            }

            $prev = $v;
        }

        $_cachedMembers = array();

        /** @var File|AssetAdminFile $version */
        foreach ($versions as $version) {
            $author = null;

            if ($version->AuthorID) {
                if (!isset($_cachedMembers[$version->AuthorID])) {
                    $_cachedMembers[$version->AuthorID] = DataObject::get(Member::class)
                        ->byID($version->AuthorID);
                }

                $author = $_cachedMembers[$version->AuthorID];
            }

            if ($version->canView()) {
                if (isset($next[$version->Version])) {
                    $summary = $version->humanizedChanges(
                        $version->Version,
                        $next[$version->Version]
                    );

                    // if no summary returned by humanizedChanges, i.e we cannot work out what changed, just show a
                    // generic message
                    if (!$summary) {
                        $summary = _t(__CLASS__.'.SAVEDFILE', "Saved file");
                    }
                } else {
                    $summary = _t(__CLASS__.'.UPLOADEDFILE', "Uploaded file");
                }

                $output[] = array(
                    'versionid' => (int) $version->Version,
                    'date_ago' => $version->dbObject('LastEdited')->Ago(),
                    'date_formatted' => $version->dbObject('LastEdited')->Nice(),
                    'status' => ($version->WasPublished) ? _t(__CLASS__.'.PUBLISHED', 'Published') : '',
                    'author' => ($author)
                        ? $author->Name
                        : _t(__CLASS__.'.UNKNOWN', "Unknown"),
                    'summary' => ($summary)
                        ? $summary
                        : _t(__CLASS__.'.NOSUMMARY', "No summary available")
                );
            }
        }

        $response = new HTTPResponse(json_encode($output));
        return $response->addHeader('Content-Type', 'application/json');
    }
1103657
public function edit(ServerRequestInterface $request): ResponseInterface
    {
        $user_id = (int) $request->getQueryParams()['user_id'];
        $user    = $this->user_service->find($user_id);

        if ($user === null) {
            throw new NotFoundHttpException(I18N::translate('%1$s does not exist.', 'user_id:' . $user_id));
        }

        return $this->viewResponse('admin/users-edit', [
            'contact_methods' => FunctionsEdit::optionsContactMethods(),
            'default_locale'  => WT_LOCALE,
            'locales'         => I18N::installedLocales(),
            'roles'           => $this->roles(),
            'trees'           => Tree::getAll(),
            'theme_options'   => $this->themeOptions(),
            'title'           => I18N::translate('Edit the user'),
            'user'            => $user,
        ]);
    }
336337
public function edit($request) {
		//get attendee from registration
		$attendee = $this->registration->Attendees()
			->byID($request->param('ID'));
		if(!$attendee) {
			return $this->httpError(404, "Attendee not found");
		}
		$form = $this->AttendeeForm();
		//add tickets dropdown, if there is no selected ticket
		$ticket = $attendee->Ticket();
		if(!$ticket->exists()){
			$form->setAllowedTickets(
				$this->registration->Event()->getAvailableTickets()
			);
		}
		if (!$form->hasSessionData()) {
			$form->loadDataFrom($attendee);
		}
		//add tickets dropdown, if there is no selected ticket
		$form->getValidator()->addRequiredField("ID");
		$this->extend("onEdit", $form, $attendee, $this->registration);
		return array(
			'Title' => $attendee->Ticket()->Title,
			'Form' => $form
		);
	}
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);
        }
    }
783356
public function edit(Request $request)
    {
        return Admin::content(function (Content $content) use ($request) {
            $connection = $request->get('conn', 'default');

            $manager = $this->manager();

            $variables = [
                'conn'        => $connection,
                'info'        => $manager->getInformation(),
                'connections' => $manager->getConnections(),
                'data'        => $manager->fetch($request->get('key')),
            ];

            if (empty($variables['data'])) {
                $view = 'laravel-admin-redis-manager::edit.nil';
            } else {
                $view = 'laravel-admin-redis-manager::edit.'.$variables['data']['type'];
            }

            $content->header('Redis manager');
            $content->description('Connections');
            $content->breadcrumb(
                ['text' => 'Redis manager', 'url' => route('redis-index', ['conn' => $connection])],
                ['text' => 'Edit']
            );
            $content->body(view($view, $variables));
        });
    }
1119097
public function apiCreateFile(HTTPRequest $request)
    {
        $data = $request->postVars();

        // When creating new files, rename on conflict
        $upload = $this->getUpload();
        $upload->setReplaceFile(false);

        // CSRF check
        $token = SecurityToken::inst();
        if (empty($data[$token->getName()]) || !$token->check($data[$token->getName()])) {
            $this->jsonError(400);
            return null;
        }

        // Check parent record
        /** @var Folder $parentRecord */
        $parentRecord = null;
        if (!empty($data['ParentID']) && is_numeric($data['ParentID'])) {
            $parentRecord = Folder::get()->byID($data['ParentID']);
        }
        $data['Parent'] = $parentRecord;

        $tmpFile = $request->postVar('Upload');
        if (!$upload->validate($tmpFile)) {
            $errors = $upload->getErrors();
            $message = array_shift($errors);
            $this->jsonError(400, $message);
            return null;
        }

        // TODO Allow batch uploads
        $fileClass = File::get_class_for_file_extension(File::get_file_extension($tmpFile['name']));
        /** @var File $file */
        $file = Injector::inst()->create($fileClass);

        // check canCreate permissions
        if (!$file->canCreate(null, $data)) {
            $this->jsonError(
                403,
                _t(__CLASS__.'.CreatePermissionDenied', 'You do not have permission to add files')
            );
            return null;
        }

        $uploadResult = $upload->loadIntoFile($tmpFile, $file, $parentRecord ? $parentRecord->getFilename() : '/');
        if (!$uploadResult) {
            $this->jsonError(
                400,
                _t(__CLASS__.'.LoadIntoFileFailed', 'Failed to load file')
            );
            return null;
        }

        $file->ParentID = $parentRecord ? $parentRecord->ID : 0;
        $file->write();

        $result = [
            $this->getObjectFromData($file, false)
        ];

        return (new HTTPResponse(json_encode($result)))
            ->addHeader('Content-Type', 'application/json');
    }
116041
public function upload(HTTPRequest $request)
    {
        if ($this->isDisabled() || $this->isReadonly()) {
            return $this->httpError(403);
        }

        // CSRF check
        $token = $this->getForm()->getSecurityToken();
        if (!$token->checkRequest($request)) {
            return $this->httpError(400);
        }

        $tmpFile = $request->postVar('Upload');
        /** @var File $file */
        $file = $this->saveTemporaryFile($tmpFile, $error);

        // Prepare result
        if ($error) {
            $result = [
                'message' => [
                    'type' => 'error',
                    'value' => $error,
                ]
            ];
            $this->getUpload()->clearErrors();
            return (new HTTPResponse(json_encode($result), 400))
                ->addHeader('Content-Type', 'application/json');
        }

        // We need an ID for getObjectFromData
        if (!$file->isInDB()) {
            $file->write();
        }

        // Return success response
        $result = [
            AssetAdmin::singleton()->getObjectFromData($file)
        ];

        // Don't discard pre-generated client side canvas thumbnail
        if ($result[0]['category'] === 'image') {
            unset($result[0]['thumbnail']);
        }
        $this->getUpload()->clearErrors();
        return (new HTTPResponse(json_encode($result)))
            ->addHeader('Content-Type', 'application/json');
    }
1026061
public function upload(SS_HTTPRequest $request)
    {
        if ($this->isDisabled() || $this->isReadonly() || !$this->canUpload()) {
            return $this->httpError(403);
        }

        // Protect against CSRF on destructive action
        $token = $this->getForm()->getSecurityToken();
        if (!$token->checkRequest($request)) {
            return $this->httpError(400);
        }
        
        // Get form details (name of the relation)
        $name = $this->getName();
        $postVars = $request->postVar($name);
        $uploadedFiles = $this->extractUploadedFileData($postVars);
        $return = array();
        
        //
        // append all multiparts to one file here before proceeding
        //
        if ($request->getHeader('X-File-Name')) {
            // if chunked, get name from header
            //return Debug::dump($request->getHeader('X-File-Name'));
            $originalFileName = $request->getHeader('X-File-Name');
            $totalSize = $request->getHeader('X-File-Size');
            $uploadedChunkPath = $uploadedFiles[0]['tmp_name'];
            // We (mis)use the security ID as a way of 'unique-ifying' the temporary upload paths
            // so that we don't just depend on the original filename for this (or a scenario might
            // be possible to overwrite files based on an identical original name)
            // Added benefit it that the security ID will be different between form loads, which
            // makes the risk of appending to the same file over and over, a bit smaller
            $securityID = ($request->postVar('SecurityID')? $request->postVar('SecurityID'): 'none');
            // hash to prevent directory traversal etc posibilities based on original file name
            $temphash = sha1($securityID.$originalFileName);
            // eg /tmp/123somelonghash456 instead of $originalFileName.'.part'
            $tmpFilePath = dirname($uploadedChunkPath).DIRECTORY_SEPARATOR.$temphash;
            $append = file_exists($tmpFilePath);
            
            // If it is the first chunk we have to create the file, othewise we append...
            // Note file_put_contents with FILE_APPEND produces overlapping chunks for some reason...
            $out_fp = fopen($tmpFilePath, $append ? "ab" : "wb"); //append or write mode
            $in_fp = fopen($uploadedChunkPath, "rb");
            while ($buff = fread($in_fp, 4096)) {
                fwrite($out_fp, $buff);
            }
            fclose($out_fp);
            fclose($in_fp);
            
            // test if we're done with all chunks yet...
//			$done = (filesize($tmpFilePath)==$totalSize ? true : false);
            if (filesize($tmpFilePath) == $totalSize) {
                // move file to last uploaded chunks tmp_filename 
                // & set size etc for regular upload handling as if uploaded normally
                rename($tmpFilePath, $uploadedChunkPath);
                $uploadedFiles[0]['name'] = $originalFileName;
            } else {
                // not done yet, return for now...
                $return = array('ok' => '('.$uploadedChunkPath.' - '
                    .$tmpFilePath.': '.filesize($tmpFilePath).'/'.$totalSize.')');
                // Format response with json
                $response = new SS_HTTPResponse(Convert::raw2json(array($return)));
                $response->addHeader('Content-Type', 'text/plain');
                return $response;
            }
        }
        
        // Multipart done (or small enough to have been done in one chunk)...
        // Save the temporary file into a File object
        $firstFile = reset($uploadedFiles);
        $file = $this->saveTemporaryFile($firstFile, $error);

        if (empty($file)) {
            array_push($return, array('error' => $error));
        } else {
            array_push($return, $this->encodeFileAttributes($file));
        }
        $this->upload->clearErrors();
        
        // Format response with json
        $response = new SS_HTTPResponse(Convert::raw2json($return));
        $response->addHeader('Content-Type', 'text/plain');
        return $response;
    }
815428
public function editAction(Request $request)
    {
        $entityManager = $this->getDoctrine()->getManager();
        /** @var GlobalConfigRepository $globalConfigRepository */
        $globalConfigRepository = $entityManager->getRepository(GlobalConfig::class);
        $globalConfig = $globalConfigRepository->findLast() ?: new GlobalConfig();
        $form = $this->createForm(GlobalConfigType::class, $globalConfig, []);
        $initialLogo = $globalConfig->getLogo();
        $form->handleRequest($request);

        $success = true;
        if ($form->isSubmitted()) {
            if (true === $success = $form->isValid()) {
                //cloning the entity will give it a new id in order to invalidate browser cache (in meta.html.twig)
                $entityManager->clear(GlobalConfig::class);
                $entityManager->persist($globalConfig);
                $entityManager->flush();
                if ($initialLogo !== $globalConfig->getLogo() && $globalConfig->getLogo() !== null) {
                    $this->container->get(FaviconGenerator::class)->generate(
                        $globalConfig,
                        $this->getParameter('kernel.project_dir').'/faviconConfig.json'
                    );
                }
                $this->congrat('victoire.config.global.edit.success');

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

        return new JsonResponse([
            'html' => $this->renderView('VictoireConfigBundle:global:edit.html.twig', [
                'form' => $form->createView(),
            ]),
            'success' => $success,
        ]);
    }
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;
    }
1341518
public function getResponse(HttpRequest $request)
    {
        $uri = $request->getUrl();

        $headers = $request->getHeaders();
        $flatHeaders = [];

        foreach ($headers as $key => $value) {
            $flatHeaders[] = $key . ": " . $value;
        }

        $flatHeaders[] = 'Connection: Keep-Alive';
        $flatHeaders[] = 'Expect:';
        $flatHeaders[] = 'Accept-Language: en-GB';
        $flatHeaders[] = 'Cache-Control: no-cache';
        $flatHeaders[] = 'User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)';

        $curl = curl_init($uri);

        curl_setopt($curl, CURLOPT_HEADER, false);

        $payload = $request->getPayload();

        switch ($request->getMethod()) {
            case "head":
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "HEAD");
                break;
            case "delete":
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
                break;
            case "post":
                curl_setopt($curl, CURLOPT_POST, true);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
                break;
            case "put":
                curl_setopt($curl, CURLOPT_POST, true);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);

                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
                break;
        }

        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $flatHeaders);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec($curl);

        $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        curl_close($curl);

        $httpResponse = new HttpResponse();
        $httpResponse->setResponseBody($response);
        $httpResponse->setResponseCode($responseCode);

        return $httpResponse;
    }
578836
public function editAction()
    {
        if(method_exists($this, 'getEditForm'))
        {
            $form = $this->getEditForm();
        }
        else
        {
            $form = $this->getForm();
        }

        $id = $this->getEvent()
                ->getRouteMatch()
                ->getParam('id', 0);

        $form->add([
            'type'       => 'Zend\Form\Element\Hidden',
            'name'       => 'id',
            'attributes' => [
                'id'    => 'id',
                'value' => $id,
            ],
            'filters'    => [
                [
                    'name' => 'Int',
                ],
            ],
            'validators' => [
                [
                    'name' => 'Digits',
                ],
            ],
        ]);

        $em            = $this->getEntityManager();
        $objRepository = $em->getRepository($this->getEntityClass());
        $entity        = $objRepository->find($id);
        $form->bind($entity);

        $redirectUrl = $this->url()->fromRoute($this->getActionRoute(), [], true);
        $prg         = $this->fileprg($form, $redirectUrl, true);

        if($prg instanceof Response)
        {
            return $prg;
        }
        elseif($prg === false)
        {
            $this->getEventManager()->trigger('getForm', $this, [
                'form'        => $form,
                'entityClass' => $this->getEntityClass(),
                'id'          => $id,
                'entity'      => $entity,
            ]);

            return [
                'entityForm' => $form,
                'entity'     => $entity,
            ];
        }

        $this->getEventManager()->trigger('getForm', $this, [
            'form'        => $form,
            'entityClass' => $this->getEntityClass(),
            'id'          => $id,
            'entity'      => $entity,
        ]);

        $savedEntity = $this->getEntityService()->save($form, $entity);

        if(!$savedEntity)
        {
            return [
                'entityForm' => $form,
                'entity'     => $entity,
            ];
        }

        $this->flashMessenger()->addSuccessMessage($this->getServiceLocator()
                        ->get('translator')
                        ->translate($this->successEditMessage));

        return $this->redirect()->toRoute($this->getActionRoute('list'), [], true);
    }
690540
private function getPostRequestEncoding( Request $request ) {
		if ( $request instanceof MultipartRequest ) {
			return 'multipart';
		}
		foreach ( $request->getParams() as $value ) {
			if ( is_resource( $value ) ) {
				return 'multipart';
			}
		}
		return 'form_params';
	}
623300
public function handleFile(HTTPRequest $request)
    {
        $filename = $this->parseFilename($request);

        // Deny requests to private file
        if (!$this->isValidFilename($filename)) {
            return $this->httpError(400, "Invalid request");
        }

        // Pass through to backend
        return $this->getRouteHandler()->getResponseFor($filename);
    }