Action: store a file record.

@param UploadFileRequest $request
@return mixed
977566
public function store(UploadFileRequest $request)
    {
        $file = $request->file('file');

        $fileName  = uniqid('upload') . '.' . $file->extension();
        $storeDir  = rtrim(config('cms-upload-module.upload.path'), '/');
        $storePath = $storeDir . '/' . $fileName;

        $mimeType = $file->getMimeType();

        if ( ! $this->fileChecker->check($file->getClientOriginalName(), $mimeType)) {
            return response()->json([
                'success' => false,
                'error'   => cms_trans('upload.error.disallowed-type'),
            ]);
        }

        // Apply custom request-specified validation
        $rules     = $request->getNormalizedValidationRules();
        $validator = $this->getCustomValidator($file, $rules);

        if ($validator) {
            try {
                if ($validator->fails()) {
                    return response()->json([
                        'success' => false,
                        'error'   => implode("\n", array_get($validator->getMessageBag()->toArray(), 'file', [])),
                    ]);
                }
            } catch (Exception $e) {
                cms()->log('error', "Error applying validation custom rules for uploaded file", [
                    'file'  => $storePath,
                    'rules' => $rules,
                ]);
                return response()->json([
                    'success' => false,
                    'error'   => cms_trans('upload.error.validation-failed'),
                ]);
            }
        }

        $path = $file->move($storeDir, $fileName);

        if (false === $path || ! $this->files->exists($storePath)) {
            // @codeCoverageIgnoreStart
            cms()->log('error', "Error moving uploaded file to {$storePath}");
            return response()->json([
                'success' => false,
                'error'   => cms_trans('upload.error.upload-failed'),
            ]);
            // @codeCoverageIgnoreEnd
        }

        $data = [
            'reference' => $request->input('reference'),
            'name'      => $request->input('name'),
            'uploader'  => $this->core->auth()->user()->getUsername(),
            'file_size' => $this->files->exists($path) ? $this->files->size($path) : null,
        ];

        if ( ! ($record = $this->fileRepository->create($path, $data))) {
            // @codeCoverageIgnoreStart
            cms()->log('error', "Error saving record for uploaded file at {$storePath}");
            return response()->json([
                'success' => false,
                'error'   => cms_trans('upload.error.saving-record-failed'),
            ]);
            // @codeCoverageIgnoreEnd
        }

        if ($this->sessionGuard->enabled()) {
            $this->sessionGuard->link($record->getKey());
        }

        $this->performGarbageCollection();

        return response()->json([
            'success'   => true,
            'id'        => $record->getKey(),
            'reference' => $record->reference,
            'name'      => $record->name,
            'size'      => $record->file_size,
            'mimetype'  => $mimeType,
        ]);
    }
429450
public static function getFileSafe(
        string $uploadField,
        Request $request
    ) {
        if (!$request) {
            return null;
        }

        $uploadedFile = $request->file($uploadField);

        //check type because request file method, may returns UploadedFile, array or null
        if (!is_a($uploadedFile, UploadedFile::class)) {
            return null;
        }

        return $uploadedFile;
    }
662573
public function pagerfanta(Request $request)
    {
        $sql = $this->createQueryBuilder('data');
        $sql->select('data');
        $sql->andWhere('data.uploadFile = :uploadFile');
        $sql->setParameter('uploadFile', $request->get('import_id'));

        switch ($request->get('type', 'all')) {
            case 'success':
                $sql->andWhere('data.status = 1 or data.status = 2 or data.status = 0');
                break;
            case 'nochanges':
                $sql->andWhere('data.status = 0');
                break;
            case 'new':
                $sql->andWhere('data.status = 1');
                break;
            case 'update':
                $sql->andWhere('data.status = 2');
                break;
            case 'error':
                $sql->andWhere('data.status = 3');
                break;
        }

        return $sql->getQuery();
    }
1147475
public function store(Create $request)
    {
        $data = $request->all();

        unset($data['image']);

        if (\Input::hasFile('image')) {
            // upload image
            $this->uploader->upload('image')->save('images/articles');

            $data['image'] = $this->uploader->getFilename();
        }

        $data['user_id'] = \Auth::id();
        $data['slug'] = Str::slug($data['title']);

        $this->repository->create($data);

        return $this->redirect(isOnPages() ? 'pages.index' : 'articles.index');
    }
530927
public function uploadAction(Request $request)
    {
        // @todo This method is insecure. Need to implement a CSFR check?

        global $kernel;

        $defaultUploadDir = realpath($kernel->getRootDir() . '/../web/uploads');
        $defaultUri       = '/uploads/';

        // Fire the pre-move event.
        $preMoveEvent = new UploadPreMoveEvent($request);
        $dispatcher   = $this->get('event_dispatcher');
        $dispatcher->dispatch('filefield.upload.pre_move', $preMoveEvent);

        $session = $this->get('session');
        $helper  = $this->get('filefield.upload_helper');

        $files     = $preMoveEvent->getFiles();
        $responses = [];
        foreach ($files as $formId => $file) {
            $ns        = 'filefield/' . $formId . '/';
            $uploadDir = $session->get($ns . 'uploadDir', $defaultUploadDir);
            $uri       = $session->get($ns . 'uri', $defaultUri);

            $response = null;
            if ($preMoveEvent->isDefaultMoveAllowed()) {
                if (empty($uploadDir) || empty($uri)) {
                    throw new \Exception('Missing uploadDir or uri.');
                }

                // Ensure upload directory exists.
                $fs = new Filesystem();
                if (!$fs->exists($uploadDir)) {
                    $fs->mkdir($uploadDir);
                }

                // @todo: Need to limit extension base on configuration.
                $ext     = strtolower($file->getClientOriginalExtension());
                $name    = basename(strtolower($file->getClientOriginalName()), $ext);
                $name    = $helper->getSaveName($name) . '.' . $ext;
                $size    = $helper->formatSize($file->getSize());
                $mime    = strtolower($file->getMimeType());
                $icon    = $helper->getFileIcon($mime);
                $iconUri = $helper->getIconUri() . $icon;

                // Move file(s) to permanent location.
                $file->move($uploadDir, $name);

                // Build a ajax response.
                $response = [
                    'name'     => $name,
                    'size'     => $size,
                    'mime'     => $mime,
                    'uri'      => $uri . $name,
                    'iconUri'  => $iconUri,
                    'template' => [
                        '.filefield-filename' => [
                            'text' => substr($name, 0, 40),
                            'attr' => [
                                'href' => $uri . $name,
                            ],
                        ],
                        '.filefield-filesize' => [
                            'text' => $size,
                        ],
                        '.filefield-fileicon' => [
                            'attr' => [
                                'src' => $iconUri,
                            ]
                        ],
                        '.filefield-value' => [
                            'val' => $uri . $name,
                        ]
                    ],
                ];
            }

            // Fire the move event.
            $moveEvent = new UploadMoveEvent($file, $uploadDir, $uri, $response);
            $dispatcher = $this->get('event_dispatcher');
            $dispatcher->dispatch('filefield.upload.move', $moveEvent);

            // Get the final file response.
            $response = $moveEvent->getResponse();

            if (empty($response) || !is_array($response)) {
                throw new \Exception('Invalid upload response.');
            }

            $responses[] = $response;
        }

        // Fire the post-move event.
        $postMoveEvent = new UploadPostMoveEvent($files, $responses);
        $dispatcher = $this->get('event_dispatcher');
        $dispatcher->dispatch('filefield.upload.post_move', $postMoveEvent);

        $response = new JsonResponse(['files' => $postMoveEvent->getResponse()]);
        if (!in_array('application/json', $request->getAcceptableContentTypes())) {
            $response->headers->set('Content-Type', 'text/plain');
        }

        return $response;
    }
1061594
public function store(CreateUserRequest $request)
    {
        $input = $request->all();

        $user = $this->repository->create($input);
        $user->load($request->getWith());

        return $this->sendResponse($user, 'User saved successfully.');
    }
164380
public function store(FormRequest $request)
    {
        $data = $request->all();
        $model = $this->repository->create($data);

        return $this->redirect($request, $model);
    }
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'));
    }
1167996
public function store(Request $request)
    {
        $this->validate(
            $request,
            [
                'key' => 'required|string|unique:settings',
                'value' => 'required'
            ]
        );

        $requestData = $request->all();

        Setting::create($requestData);

        return redirect('admin/settings')->with('flash_message', 'Setting added!');
    }
1175076
public function postAction(Request $request)
    {
        $file = new File();
        $request = $this->requestManager->updateFileRequest($request);

        if ($formData = $request->get('metadata')) {
            $file = $this->restUtils->validateRequest($formData, $this->getModel());
        }

        /** @var FileModel $model */
        $model = $this->getModel();
        $file = $this->fileManager->handleSaveRequest($file, $request, $model);

        // Set status code and content
        $response = $this->getResponse();
        $response->setStatusCode(Response::HTTP_CREATED);
        $response->headers->set(
            'Location',
            $this->getRouter()->generate('gravitondyn.file.rest.file.get', array('id' => $file->getId()))
        );
        return $response;
    }
368206
public function store(SubmitRequest $request)
    {
        $this->service->create($request->all());

        return $this->success();
    }
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');
    }
721604
public function saveAction(Request $request)
    {
        $all = $request->get('all');
        $action = $request->get('action');
        $tempId = $request->get('temp_id');

        $metaData = $request->get('meta', null);
        if ($metaData) {
            $metaData = json_decode($metaData, true);
        }

        $tempHandler = $this->get('phlexible_media_manager.upload.temp_handler');

        if ($all) {
            $tempHandler->handleAll($action);
        } else {
            $file = $tempHandler->handle($action, $tempId);

            if ($file && $metaData) {
                $this->saveMeta($file, $metaData);
            }
        }

        return new ResultResponse(true, ($all ? 'All' : 'File').' saved with action '.$action);
    }
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);
    }
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;
    }
1283509
public function store(Request $request)
    {
        $this->manager->resetPath($request->folder);

        if (empty($request->name)) {
            return $this->json('Name property is required.', 422);
        }

        if (!$this->manager->blobExists()) {
            return $this->json('Folder not found.', 404);
        }

        $result = $this->manager->makeDirectory($request->name)->fullDetails();

        return $this->json($result);
    }
248214
public function store(FormRequest $request)
    {
        $data = $request->all();
        $data['parent_id'] = null;
        $page = $this->repository->create($data);
        Menulinks::forgetCache();

        return $this->redirect($request, $page);
    }