Action to handle upload of a single file

@param SS_HTTPRequest $request
@return string json
320408
public function upload(SS_HTTPRequest $request)
    {
        if (!$this->currentVersionFile) {
            return;
        }


        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->has_many($name) || $record->many_many($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->has_one($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']) {
            // Get the uploaded file into a new file object.
            try {
                $currentFilePath = $this->currentVersionFile->getFullPath();
                if (file_exists($currentFilePath)) {
                    unlink($this->currentVersionFile->getFullPath());
                }

                // If $folderName == assets (by default), then this will try and create a file inside assets/assets
                // instead of creating it in the root. This check ensures that the newly uploaded files overwrites the
                // old file in the assets root directory.
                $folderName = $this->folderName;
                if ($folderName == basename(ASSETS_PATH)) {
                    $folderName = "/";
                }

                $this->upload->loadIntoFile(
                    array_merge($tmpfile, array('name' => $this->currentVersionFile->Name)),
                    $this->currentVersionFile,
                    $folderName
                );
            } 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();

                    $file->createVersion();

                    // Attach the file to the related record.
                    if ($this->relationAutoSetting) {
                        $this->attachFile($file);
                    }

                    // Collect all output data.
                    $file =  $this->customiseFile($file);
                    $return = array_merge($return, array(
                        'id' => $file->ID,
                        'name' => $file->getTitle() . '.' . $file->getExtension(),
                        'url' => $file->getURL(),
                        'thumbnail_url' => $file->UploadFieldThumbnailURL,
                        'edit_url' => $file->UploadFieldEditLink,
                        'size' => $file->getAbsoluteSize(),
                        'buttons' => $file->UploadFieldFileButtons
                    ));
                }
            }
        }
        $response = new SS_HTTPResponse(Convert::raw2json(array($return)));
        $response->addHeader('Content-Type', 'text/plain');
        return $response;
    }
531871
public function uploadAction ()
    {
        $handle = $this->getRequest()->files->get('file');
        
        if ($handle && $handle->getError()){
            return new JsonResponse(array(
                'success' => false,
                'err_msg' => $this->container->get('translator')
                    ->trans('file_upload_http_error', array(), 'ThraceMediaBundle')
            ));
        }

        $imageManager = $this->container->get('thrace_media.imagemanager');
        $options = $this->container->getParameter('thrace_media.plupload.options');
        $extension = $handle->getClientOriginalExtension();
        $name = uniqid() . '.' . $extension;
        
        if(!$extension){
            return new JsonResponse(array(
                'success' => false,
                'err_msg' => sprintf('Unknown Mime Type: "%s"', $handle->getMimeType())
            ));
        }

        $validate = $this->validateImage($handle);

        if ($validate !== true) {
            return new JsonResponse(array(
                'success' => false,
                'err_msg' => $validate
            ));
        }

        $content = $imageManager->normalizeImage(
            $name, file_get_contents($handle->getRealPath()), 
            $options['normalize_width'], $options['normalize_height']
        );
        
        $imageManager->saveToTemporaryDirectory($name, $content);
        $imageManager->makeImageCopyToOriginalDirectory($name);
        $hash = $imageManager->checksumTemporaryFileByName($name);

        return new JsonResponse(array(
            'success' => true,
            'name'    => $name,
            'hash'    => $hash
        ));
    }
787818
private function input(Request $request)
    {
        $files = $request->files->all();

        array_walk_recursive($files, function (&$file) {
            $file = [
                'name' => $file->getClientOriginalName(),
                'size' => $file->isFile() ? ($file->getSize() / 1000).'KB' : '0',
            ];
        });

        return array_replace_recursive($request->input(), $files);
    }
157789
public function attach(HTTPRequest $request)
    {
        $fileID = $request->requestVar('fileID'); //why is this not POST?
        $dataObject = $this->createDataObject($fileID);

        $response = new HTTPBulkToolsResponse(false, $this->gridField);
        $response->addSuccessRecord($dataObject);
        return $response;
    }
93985
public function addSnippet(SS_HTTPRequest $request)  {
        if($request->getVar('Type')=='SnippetFolder') {
            return $this->redirect(Controller::join_links($this->Link('addFolder'), '?FolderID='.str_replace('folder-', '', $request->getVar('ID'))));
        }else {
            return $this->redirect(Controller::join_links($this->Link('add'), '?LanguageID='.str_replace('language-', '', $request->getVar('ID'))));
        }
    }
262373
public function uploadsnapshot(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);
		}

		return $this->customise(array(
			'Project' => $project,
			'CurrentProject' => $project,
			'SnapshotsSection' => 1,
			'UploadLimit' => $maxSize = File::format_size(min(
				File::ini2bytes(ini_get('upload_max_filesize')),
				File::ini2bytes(ini_get('post_max_size'))
			)),
			'UploadSnapshotForm' => $this->getUploadSnapshotForm($request),
			'PostSnapshotForm' => $this->getPostSnapshotForm($request)
		))->renderWith(array('DNRoot_uploadsnapshot', 'DNRoot'));
	}
593219
public function uploadFiles(UploadFileRequest $request)
    {
        try {
            $files = $request->file('files');
            $folder = $request->get('folder', '/');
            $uploadedFiles = new UploadedFiles($files);

            $response = $this->mediaManager->saveUploadedFiles($uploadedFiles, $folder);
            if ($response != 0) {
                $response = trans('media-manager::messages.upload_success', ['entity' => $response.' New '.str_plural('File', $response)]);
            }

            $errors = $this->mediaManager->errors();
            if (!empty($errors)) {
                return $this->errorResponse($errors, $response);
            }

            return ['success' => $response];
        } catch (\Exception $e) {
            return $this->errorResponse([$e->getMessage()]);
        }
    }
648555
public function uploadAction(Request $request)
    {
        $files = $this->uploadFiles($request);
        $data = [];

        foreach ($files as $file) {
            $data[] = $this->serializer->serialize($file);
        }

        return new JsonResponse($data, 200);
    }
201965
public function handleDelete(SS_HTTPRequest $request)
    {
        parse_str($request->getBody(), $vars);
        $count = 0;
        if ($vars['ids']) {
            foreach (explode(',', $vars['ids']) as $id) {
                if ($file = File::get()->byID($id)) {
                    if ($file->canDelete()) {
                        $file->delete();
                        $count++;
                    }
                }
            }
        }

        $result = array(
            'deleted' => $count
        );

        $response = new SS_HTTPResponse(
            Convert::array2json($result), 200
        );

        return $response->addHeader('Content-Type', 'application/json');
    }
760444
public function movesnapshot($request) {
		$dataArchive = DNDataArchive::get()->byId($request->param('DataArchiveID'));

		if(!$dataArchive) {
			throw new SS_HTTPResponse_Exception('Archive not found', 404);
		}

		// We check for canDownload because that implies access to the data.
		if(!$dataArchive->canDownload()) {
			throw new SS_HTTPResponse_Exception('Not allowed to access archive', 403);
		}

		$form = $this->getMoveForm($this->request, $dataArchive);

		// View currently only available via ajax
		return $form->forTemplate();
	}
959547
public function filesAction(Request $request)
    {
        $id = $request->query->get('id');
        $em = $this->getDoctrine()->getManager();

        $files = $this->getDoctrine()->getRepository('ClasticMediaBundle:File')
            ->findBy(array(
                'directory' => $em->getReference('ClasticMediaBundle:Directory', $id),
            ));

        $data = array_map(function (File $file) {
            return array(
                'id' => $file->getId(),
                'text' => $file->getName(),
                'path' => '/uploads/documents/'.$file->getPath(),
            );
        }, $files);

        return new JsonResponse($data);
    }
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;
    }
1364632
public function fileInsertForm($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->getFileInsertForm($id);
    }
1298744
public function saveAction(Request $request)
	{
		$file = $this->getEntity();

		// set private
		if ($request->request->has('private')) {
			$private = $request->request->get('private');

			if ($private == 0) {
				$this->getFileStorage()->setPublic($file);
			}

			if ($private == 1) {
				$this->getFileStorage()->setPrivate($file);
			}

			$this->container->getDoctrine()->getManager()->flush();

			return new SupraJsonResponse();
		}

		// renaming
		if ($request->request->has('filename')) {

			$fileName = $request->request->get('filename');

			if (trim($fileName) == '') {
				throw new CmsException(null, 'Empty filename not allowed');
			}

			$newFileInfo = pathinfo($fileName);

			if (mb_strlen($newFileInfo['basename'], 'utf-8') > self::MAX_FILE_BASENAME_LENGTH) {

				if ($file instanceof Folder) {
					throw new CmsException(null, 'Folder name is too long! Maximum length is ' . self::MAX_FILE_BASENAME_LENGTH . ' characters!');
				} else {
					throw new CmsException(null, 'File name is too long! Maximum length is ' . self::MAX_FILE_BASENAME_LENGTH . ' characters!');
				}
			}

			try {
				if ($file instanceof Folder) {
					$this->getFileStorage()->renameFolder($file, $fileName);
				} else {
					$this->getFileStorage()->renameFile($file, $fileName);
				}
			} catch (\Exception $e) {
				$key = $e instanceof UploadFilterException ? $e->getMessageKey() : null;
				throw new CmsException($key, $e->getMessage(), $e);
			}
		}

//		// Custom Properties
//		$dirty = false;
//
//		$propertyConfigurations = $this->getFileStorage()->getCustomPropertyConfigurations();
//		foreach ($propertyConfigurations as $configuration) {
//			$propertyName = $configuration->name;
//
//			if ($request->request->has($propertyName)) {
//				$value = $request->request->get($propertyName);
//
//				$property = $this->getFileStorage()->getFileCustomProperty($file, $propertyName);
//
//				$property->setEditableValue($value, $configuration->getEditable());
//
//				$dirty = true;
//			}
//		}
//
//		if ($dirty) {
//			$this->container->getDoctrine()->getManager()->flush();
//		}

		$response = array();

		// when changing image private attribute, previews and thumbs will change their paths
		// so we will output new image info
		if ($file instanceof File) {
			$response = $this->imageAndFileOutput($file);
		}

		return new SupraJsonResponse($response);
	}
56582
public function upload(Request $request)
    {
        try {
            $realPath = Storage::disk($this->filesystem)->getDriver()->getAdapter()->getPathPrefix();

            $allowedImageMimeTypes = [
                'image/jpeg',
                'image/png',
                'image/gif',
                'image/bmp',
                'image/svg+xml',
            ];

            if (in_array($request->file->getMimeType(), $allowedImageMimeTypes)) {
                $file = $request->file->store($request->upload_path, $this->filesystem);

                $image = Image::make($realPath.$file);

                if ($request->file->getClientOriginalExtension() == 'gif') {
                    copy($request->file->getRealPath(), $realPath.$file);
                } else {
                    $image->orientate()->save($realPath.$file);
                }
            } else {
                $file = $request->file->move($realPath, $request->file->getClientOriginalName());
            }

            $success = true;
            $message = __('admin.media.success_uploaded_file');
            $path = preg_replace('/^public\//', '', $file);
        } catch (Exception $e) {
            $success = false;
            $message = $e->getMessage();
            $path = '';
        }

        return response()->json(compact('success', 'message', 'path'));
    }
88987
public function handleRecentItems(SS_HTTPRequest $request)
    {
        $result = array();

        $fileIDs = File::get()
            ->sort('LastEdited', 'DESC')
            ->limit($this->config()->recent_items_limit)
            ->column('ID');

        if (!empty($fileIDs)) {
            $files = File::get()
                ->sort($this->getSortClause($request->getVar('sort')))
                ->byIDs($fileIDs);

            foreach ($files as $file) {
                if (!$file->canView()) {
                    continue;
                }

                $result[] = ($file instanceof Folder) ?
                    $this->createFolderJson($file) :
                    $this->createFileJson($file);

            }
        }

        $response = new SS_HTTPResponse(
            Convert::array2json($result), 200
        );

        return $response->addHeader('Content-Type', 'application/json');
    }
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);
    }