Construct the upload form.

@param SS_HTTPRequest $request
@return Form
333550
public function getUploadSnapshotForm(SS_HTTPRequest $request) {
		// Performs canView permission check by limiting visible projects
		$project = $this->getCurrentProject();
		if(!$project) {
			return new SS_HTTPResponse("Project '" . Convert::raw2xml($request->latestParam('Project')) . "' not found.", 404);
		}

		if(!$project->canUploadArchive()) {
			return new SS_HTTPResponse("Not allowed to upload", 401);
		}

		// Framing an environment as a "group of people with download access"
		// makes more sense to the user here, while still allowing us to enforce
		// environment specific restrictions on downloading the file later on.
		$envs = $project->DNEnvironmentList()->filterByCallback(function($item) {return $item->canUploadArchive();});
		$envsMap = array();
		foreach($envs as $env) {
			$envsMap[$env->ID] = $env->Name;
		}

		$maxSize = min(File::ini2bytes(ini_get('upload_max_filesize')), File::ini2bytes(ini_get('post_max_size')));
		$fileField = DataArchiveFileField::create('ArchiveFile', 'File');
		$fileField->getValidator()->setAllowedExtensions(array('sspak'));
		$fileField->getValidator()->setAllowedMaxFileSize(array('*' => $maxSize));

		$form = new Form(
			$this,
			'UploadSnapshotForm',
			new FieldList(
				$fileField,
				DropdownField::create('Mode', 'What does this file contain?', DNDataArchive::get_mode_map()),
				DropdownField::create('EnvironmentID', 'Initial ownership of the file', $envsMap)
			),
			new FieldList(
				$action = new FormAction('doUploadSnapshot', "Upload File")
			),
			new RequiredFields('ArchiveFile')
		);
		$action->addExtraClass('btn');
		$form->disableSecurityToken();
		$form->addExtraClass('fields-wide');
		// Tweak the action so it plays well with our fake URL structure.
		$form->setFormAction($project->Link().'/UploadSnapshotForm');

		return $form;
	}
131318
public function upload(SS_HTTPRequest $request)
    {
        if ($recordId = $request->postVar('ID')) {
            $this->setRecord(DMSDocumentSet::get()->byId($recordId));
        }

        if ($this->isDisabled() || $this->isReadonly()) {
            return $this->httpError(403);
        }

        // Protect against CSRF on destructive action
        $token = $this->getForm()->getSecurityToken();
        if (!$token->checkRequest($request)) {
            return $this->httpError(400);
        }

        $name = $this->getName();
        $tmpfile = $request->postVar($name);
        $record = $this->getRecord();

        // Check if the file has been uploaded into the temporary storage.
        if (!$tmpfile) {
            $return = array('error' => _t('UploadField.FIELDNOTSET', 'File information not found'));
        } else {
            $return = array(
                'name' => $tmpfile['name'],
                'size' => $tmpfile['size'],
                'type' => $tmpfile['type'],
                'error' => $tmpfile['error']
            );
        }

        // Check for constraints on the record to which the file will be attached.
        if (!$return['error'] && $this->relationAutoSetting && $record && $record->exists()) {
            $tooManyFiles = false;
            // Some relationships allow many files to be attached.
            if ($this->getConfig('allowedMaxFileNumber') && ($record->hasMany($name) || $record->manyMany($name))) {
                if (!$record->isInDB()) {
                    $record->write();
                }
                $tooManyFiles = $record->{$name}()->count() >= $this->getConfig('allowedMaxFileNumber');
            // has_one only allows one file at any given time.
            } elseif ($record->hasOne($name)) {
                $tooManyFiles = $record->{$name}() && $record->{$name}()->exists();
            }

            // Report the constraint violation.
            if ($tooManyFiles) {
                if (!$this->getConfig('allowedMaxFileNumber')) {
                    $this->setConfig('allowedMaxFileNumber', 1);
                }
                $return['error'] = _t(
                    'UploadField.MAXNUMBEROFFILES',
                    'Max number of {count} file(s) exceeded.',
                    array('count' => $this->getConfig('allowedMaxFileNumber'))
                );
            }
        }

        // Process the uploaded file
        if (!$return['error']) {
            $fileObject = null;

            if ($this->relationAutoSetting) {
                // Search for relations that can hold the uploaded files.
                if ($relationClass = $this->getRelationAutosetClass()) {
                    // Create new object explicitly. Otherwise rely on Upload::load to choose the class.
                    $fileObject = SS_Object::create($relationClass);
                }
            }

            // Get the uploaded file into a new file object.
            try {
                $this->upload->loadIntoFile($tmpfile, $fileObject, $this->getFolderName());
            } catch (Exception $e) {
                // we shouldn't get an error here, but just in case
                $return['error'] = $e->getMessage();
            }

            if (!$return['error']) {
                if ($this->upload->isError()) {
                    $return['error'] = implode(' ' . PHP_EOL, $this->upload->getErrors());
                } else {
                    $file = $this->upload->getFile();

                    // CUSTOM Attach the file to the related record.
                    $document = $this->attachFile($file);

                    // Collect all output data.
                    $return = array_merge($return, array(
                        'id' => $document->ID,
                        'name' => $document->getTitle(),
                        'thumbnail_url' => $document->Icon($document->getExtension()),
                        'edit_url' => $this->getItemHandler($document->ID)->EditLink(),
                        'size' => $document->getFileSizeFormatted(),
                        'buttons' => (string) $document->renderWith($this->getTemplateFileButtons()),
                        'showeditform' => true
                    ));

                    // CUSTOM END
                }
            }
        }
        $response = new SS_HTTPResponse(Convert::raw2json(array($return)));
        $response->addHeader('Content-Type', 'text/plain');
        return $response;
    }
884798
public function delete(SS_HTTPRequest $request)
    {
        // Check form field state
        if ($this->parent->isDisabled() || $this->parent->isReadonly()) {
            return $this->httpError(403);
        }

        // Protect against CSRF on destructive action
        $token = $this->parent->getForm()->getSecurityToken();
        if (!$token->checkRequest($request)) {
            return $this->httpError(400);
        }

        // Check item permissions
        $item = $this->getItem();
        if (!$item) {
            return $this->httpError(404);
        }

        $memberID = Member::currentUserID();

        $res = false;
        try {
            // Owner can always delete
            if ($memberID && $item->OwnerID == $memberID) {
                $res = true;
            } else {
                $res = $item->canDelete();
            }
        } catch (Exception $ex) {

        }

        if (!$res) {
            return $this->httpError(403);
        }

        // Delete the file from the filesystem. The file will be removed
        // from the relation on save
        // @todo Investigate if references to deleted files (if unsaved) is dangerous
        $item->delete();

        if (Controller::has_curr()) {
            return Controller::curr()->redirectBack();
        }
        return $this;
    }
612633
protected function createEntityForm(Request $request = NULL)
    {
        $form = $this->createForm($this->type, $this->entity);

        return $request ? $form->handleRequest($request) : $form;
    }
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;
    }
535323
public function uploadAction(Request $request)
    {
        $form = $this->createForm(new FileImportType());
        $data = $form->handleRequest($request)->getData();
        $session = $this->getSession();

        try {
            $counters = $this->getSessionImporter()->handleUploadedFile($data['file']);
            if ($counters['new'] == 0 && $counters['updated'] == 0) {
                $session->getFlashBag()->set('warning', 'File import success, but not more modification found');
            } else {
                $session->getFlashBag()->set('info', "File import success, {$counters['new']} new and {$counters['updated']} update");
            }
        } catch (ImportException $e) {
            $session->getFlashBag()->set('error', 'Error while trying to import: '.$e->getMessage());
        }

        return $this->redirect($this->generateUrl('liip_translation_import'));
    }
185143
public function upload(Request $request)
    {
        try {
            $path = $request->file->store($request->upload_path, $this->filesystem);
            $success = true;
            $message = 'Successfully uploaded new file!';
        } catch (Exception $e) {
            $success = false;
            $message = $e->getMessage();
        }

        $realPath = Storage::disk($this->filesystem)->getDriver()->getAdapter()->getPathPrefix().$path;
        Image::make($realPath)->orientate()->save();

        $path = preg_replace('/^public\//', '', $path);

        return response()->json(compact('success', 'message', 'path'));
    }
1058293
public function uploadAction(Request $request)
    {
        $media = $this->get('opifer.media.media_manager')->createMedia();
        $em = $this->getDoctrine()->getManager();

        foreach ($request->files->all() as $files) {
            if ((!is_array($files)) && (!$files instanceof \Traversable)) {
                $files = [$files];
            }

            foreach ($files as $file) {
                $media = clone $media;
                $media->setFile($file);

                if (strpos($file->getClientMimeType(), 'image') !== false) {
                    $media->setProvider('image');
                } else {
                    $media->setProvider('file');
                }

                $em->persist($media);
            }
        }
        $em->flush();

        $media = $this->get('jms_serializer')->serialize($media, 'json');

        return new Response($media, 200, ['Content-Type' => 'application/json']);
    }
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');
    }
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');
    }
721541
public function createAction(Request $request)
    {
        $form = $this->buildForm();

        if ($request->isMethod('POST') && $this->submitForm($form, $request)->isValid()) {
            try {
                $this->getDomainManager()->create($form->getData());
            } catch (DomainException $e) {
                $this->processException($e);
            }
        }

        return $this->processAction('create', $form, Response::HTTP_CREATED);
    }
308933
public function handleCreateFolder(SS_HTTPRequest $request)
    {

        if (!Injector::inst()->get('Folder')->canCreate()) {
            return $this->httpError(403);
        }

        $parentID = (int)$request->postVar('parentID');

        /** @var Folder $parentRecord */
        $parentRecord = Folder::get()->byID($parentID);

        $name = $request->postVar('title') ? $request->postVar('title') : _t('AssetAdmin.NEWFOLDER', "NewFolder");
        if ($parentRecord && $parentRecord->ID) {
            $filename = Controller::join_links($parentRecord->FullPath, $name);
        } else {
            $filename = Controller::join_links(ASSETS_PATH, $name);
        }

        /** @var Folder $record */
        $record = Folder::create(array(
            'ParentID' => $parentID,
            'Name' => basename($filename),
            'Title' => basename($filename),
            'Filename' => $filename
        ));

        // Ensure uniqueness
        $i = 2;
        if (substr($record->Filename, -1) == "/") {
            $baseFilename = substr($record->Filename, 0, -1);
        } else {
            $baseFilename = $record->Filename;
        }
        $baseFilename .= "-";
        while (file_exists($record->FullPath)) {
            $record->Filename = $baseFilename . $i . '/';
            $i++;
        }

        $record->Name = $record->Title = basename($record->Filename);

        mkdir($record->FullPath);
        @chmod($record->FullPath, (int)Config::inst()->get('Filesystem', 'file_create_mask'));

        $record->write();

        $response = new SS_HTTPResponse(
            Convert::array2json($this->createFolderJson($record)), 200
        );

        return $response->addHeader('Content-Type', 'application/json');
    }
1319050
public function createAction(Request $request)
    {
        $contentTypeEntityClass = $this->configurationManager->getEntityClass('content_type');
        $contentType = new $contentTypeEntityClass;

        $form = $this->createForm(ContentTypeFormType::class, $contentType, [
            'action' => $this->generateUrl('sherlockode_acb_content_type_create'),
            'contentType' => $contentType,
        ]);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->om->persist($contentType);
            $this->om->flush();

            return $this->redirectToRoute('sherlockode_acb_content_type_edit', ['id' => $contentType->getId()]);
        }

        return $this->render('@SherlockodeAdvancedContent/ContentType/create_content_type.html.twig', [
            'form' => $form->createView(),
            'data' => $contentType,
        ]);
    }
588227
public function index(SS_HTTPRequest $request)
    {
        $this->customise(
            array(
            'Title'     => _t('Users.Register', 'Register'),
            'MetaTitle' => _t('Users.Register', 'Register'),
            'Form'      => $this->RegisterForm(),
            )
        );

        $this->extend("updateIndexAction");

        return $this->renderWith(
            array(
            "Users_Register",
            "Users",
            "Page"
            )
        );
    }
1047349
public function upload(Request $request)
    {
        $json = [];
        foreach ($request->file('file') as $file) {
            $this->storage->putFile($request->get('directory'), $file);
        }

        $json['success'] = trans('admin::image.success.upload');

        return response()
            ->json($json);
    }
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');
    }
1063278
public function create_item( $request ) {

		if ( ! empty( $request['post'] ) && in_array( get_post_type( $request['post'] ), array( 'revision', 'attachment' ), true ) ) {
			return new WP_Error( 'rest_invalid_param', __( 'Invalid parent type.' ), array( 'status' => 400 ) );
		}

		// Get the file via $_FILES or raw data
		$files = $request->get_file_params();
		$headers = $request->get_headers();
		if ( ! empty( $files ) ) {
			$file = $this->upload_from_file( $files, $headers );
		} else {
			$file = $this->upload_from_data( $request->get_body(), $headers );
		}

		if ( is_wp_error( $file ) ) {
			return $file;
		}

		$name       = basename( $file['file'] );
		$name_parts = pathinfo( $name );
		$name       = trim( substr( $name, 0, -(1 + strlen( $name_parts['extension'] ) ) ) );

		$url     = $file['url'];
		$type    = $file['type'];
		$file    = $file['file'];

		// use image exif/iptc data for title and caption defaults if possible
		// @codingStandardsIgnoreStart
		$image_meta = @wp_read_image_metadata( $file );
		// @codingStandardsIgnoreEnd
		if ( ! empty( $image_meta ) ) {
			if ( empty( $request['title'] ) && trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) {
				$request['title'] = $image_meta['title'];
			}

			if ( empty( $request['caption'] ) && trim( $image_meta['caption'] ) ) {
				$request['caption'] = $image_meta['caption'];
			}
		}

		$attachment = $this->prepare_item_for_database( $request );
		$attachment->file = $file;
		$attachment->post_mime_type = $type;
		$attachment->guid = $url;

		if ( empty( $attachment->post_title ) ) {
			$attachment->post_title = preg_replace( '/\.[^.]+$/', '', basename( $file ) );
		}

		$id = wp_insert_post( $attachment, true );
		if ( is_wp_error( $id ) ) {
			if ( 'db_update_error' === $id->get_error_code() ) {
				$id->add_data( array( 'status' => 500 ) );
			} else {
				$id->add_data( array( 'status' => 400 ) );
			}
			return $id;
		}
		$attachment = $this->get_post( $id );

		// Include admin functions to get access to wp_generate_attachment_metadata().
		require_once ABSPATH . 'wp-admin/includes/admin.php';

		wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );

		if ( isset( $request['alt_text'] ) ) {
			update_post_meta( $id, '_wp_attachment_image_alt', sanitize_text_field( $request['alt_text'] ) );
		}

		$fields_update = $this->update_additional_fields_for_object( $attachment, $request );
		if ( is_wp_error( $fields_update ) ) {
			return $fields_update;
		}

		$request->set_param( 'context', 'edit' );
		$response = $this->prepare_item_for_response( $attachment, $request );
		$response = rest_ensure_response( $response );
		$response->set_status( 201 );
		$response->header( 'Location', rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $id ) ) );

		/**
		 * Fires after a single attachment is created or updated via the REST API.
		 *
		 * @param object          $attachment Inserted attachment.
		 * @param WP_REST_Request $request    The request sent to the API.
		 * @param boolean         $creating   True when creating an attachment, false when updating.
		 */
		do_action( 'rest_insert_attachment', $attachment, $request, true );

		return $response;

	}