This actions is responsible for validation, uploading of files

@return Response
550725
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')
            ));
        }
        
        $fileManager = $this->container->get('thrace_media.filemanager');
        $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->validateFile($handle);

        if ($validate !== true) {
            return new JsonResponse(array(
                'success' => false,
                'err_msg' => $validate
            ));
        }
        
        $content = file_get_contents($handle->getRealPath());
        $fileManager->saveToTemporaryDirectory($name, $content);
        $hash = $fileManager->checksumTemporaryFileByName($name);

        return new JsonResponse(array(
            'success' => true,
            'name'    => $name,
            'hash'    => $hash,
        ));
        
    }
9043
public function actionImagesUpload()
    {
        $result = $this->actionFilesUpload();

        if ($result['upload'] && $result['file']) {
            $fileId = $result['file']->id;

            $image = Yii::$app->storage->createImage($fileId, 0);

            if ($image) {
                // create system thumbnails
                $tinyCrop = Yii::$app->storage->createImage($fileId, Yii::$app->storage->getFilterId(TinyCrop::identifier()));
                $mediumThumbnail = Yii::$app->storage->createImage($fileId, Yii::$app->storage->getFilterId(MediumThumbnail::identifier()));
            }

            return [
                'image' => $image,
                'tinyCrop' => $tinyCrop,
                'mediumThumbnail' => $mediumThumbnail,
            ];
        }

        return $this->sendArrayError(['image' => 'Unable to create the given with and the corresponding filters.']);
    }
1034338
public function actionFilemanagerMoveFiles()
    {
        $this->checkRouteAccess(self::PERMISSION_ROUTE);
        
        $toFolderId = Yii::$app->request->post('toFolderId', 0);
        $fileIds = Yii::$app->request->post('fileIds', []);
        
        $currentPageId = Yii::$app->request->post('currentPageId', 0);
        $currentFolderId = Yii::$app->request->post('currentFolderId', 0);
        
        $response = Storage::moveFilesToFolder($fileIds, $toFolderId);
        $this->flushApiCache($currentFolderId, $currentPageId);
        $this->flushApiCache($toFolderId, $currentPageId);
        $this->flushHasCache($toFolderId, 0);
        return $response;
    }
1013723
protected function checkUploadPostback()
    {
        if (!($uniqueId = Request::header('X-OCTOBER-FILEUPLOAD')) || $uniqueId != $this->getId()) {
            return;
        }

        try {
            if (!Input::hasFile('file_data')) {
                throw new ApplicationException('File missing from request');
            }

            $fileModel = $this->getRelationModel();
            $uploadedFile = Input::file('file_data');

            $validationRules = ['max:'.$fileModel::getMaxFilesize()];
            if ($fileTypes = $this->getAcceptedFileTypes()) {
                $validationRules[] = 'extensions:'.$fileTypes;
            }

            if ($this->mimeTypes) {
                $validationRules[] = 'mimes:'.$this->mimeTypes;
            }

            $validation = Validator::make(
                ['file_data' => $uploadedFile],
                ['file_data' => $validationRules]
            );

            if ($validation->fails()) {
                throw new ValidationException($validation);
            }

            if (!$uploadedFile->isValid()) {
                throw new ApplicationException('File is not valid');
            }

            $fileRelation = $this->getRelationObject();

            $file = $fileModel;
            $file->data = $uploadedFile;
            $file->is_public = $fileRelation->isPublic();
            $file->save();

            /**
             * Attach directly to the parent model if it exists and attachOnUpload has been set to true
             * else attach via deferred binding
             */
            $parent = $fileRelation->getParent();
            if ($this->attachOnUpload && $parent && $parent->exists) {
                $fileRelation->add($file);
            } else {
                $fileRelation->add($file, $this->sessionKey);
            }

            $file = $this->decorateFileAttributes($file);

            $result = [
                'id' => $file->id,
                'thumb' => $file->thumbUrl,
                'path' => $file->pathUrl
            ];

            Response::json($result, 200)->send();

        }
        catch (Exception $ex) {
            Response::json($ex->getMessage(), 400)->send();
        }

        exit;
    }
157113
public function upload()
    {
        // validate that all options properties was properly set to correct type.
        $this->validateOptionsProperties();
        // setup file extensions and mime types for validation. (in case that it was not set).
        $this->setupFileExtensionsMimeTypesForValidation();

        // verify that location where the uploaded file(s) will be moved to is writable.
        if (!is_dir($this->move_uploaded_to)) {
            $this->setErrorMessage(
                static::__('The target location where the uploaded file(s) will be moved to is not folder or directory.'),
                'RDU_MOVE_UPLOADED_TO_NOT_DIR',
                $this->move_uploaded_to
            );
            return false;
        } elseif (is_dir($this->move_uploaded_to) && !is_writable($this->move_uploaded_to)) {
            $this->setErrorMessage(
                static::__('The target location where the uploaded file(s) will be moved to is not writable. Please check the folder permission.'),
                'RDU_MOVE_UPLOADED_TO_NOT_WRITABLE',
                $this->move_uploaded_to
            );
            return false;
        } else {
            // solve the move uploaded to as a real path.
            $this->move_uploaded_to = realpath($this->move_uploaded_to);
        }

        if (isset($_FILES[$this->input_file_name]['name']) && is_array($_FILES[$this->input_file_name]['name'])) {
            // if multiple file upload.
            foreach ($_FILES[$this->input_file_name]['name'] as $key => $value) {
                $this->files[$this->input_file_name]['input_file_key'] = $key;
                $this->files[$this->input_file_name]['name'] = $_FILES[$this->input_file_name]['name'][$key];
                $this->files[$this->input_file_name]['type'] = (isset($_FILES[$this->input_file_name]['type'][$key]) ? $_FILES[$this->input_file_name]['type'][$key] : null);
                $this->files[$this->input_file_name]['tmp_name'] = (isset($_FILES[$this->input_file_name]['tmp_name'][$key]) ? $_FILES[$this->input_file_name]['tmp_name'][$key] : null);
                $this->files[$this->input_file_name]['error'] = (isset($_FILES[$this->input_file_name]['error'][$key]) ? $_FILES[$this->input_file_name]['error'][$key] : 4);
                $this->files[$this->input_file_name]['size'] = (isset($_FILES[$this->input_file_name]['size'][$key]) ? $_FILES[$this->input_file_name]['size'][$key] : 0);

                $result = $this->uploadSingleFile();

                if ($result == false && $this->stop_on_failed_upload_multiple === true) {
                    // it was set to sop on failed to upload multiple file. return false.
                    unset($result);
                    return false;
                }
            }// endforeach;
            unset($key, $value);
        } else {
            // if single file upload.
            $this->files[$this->input_file_name] = $_FILES[$this->input_file_name];
            $this->files[$this->input_file_name]['input_file_key'] = 0;

            $result = $this->uploadSingleFile();
        }

        if (isset($result) && $result == false && $this->stop_on_failed_upload_multiple === true) {
            // there is at lease one upload error and it was set to stop on error.
            unset($result);
            $this->clearUploadedAtTemp();
            return false;
        } elseif (count($this->error_messages) > 0 && $this->stop_on_failed_upload_multiple === true) {
            // there is at lease one upload error and it was set to stop on error.
            unset($result);
            $this->clearUploadedAtTemp();
            return false;
        }

        return $this->moveUploadedFiles();
    }
1041038
final protected function validateFile () : bool
	{
		$file = $this->file;
		// Perform error checking on the file parameter parsed in
		if (!$file || empty($file) || !is_array($file)):
			// Error: nothing uploaded or wrong argument usage
			$this->error = "No file was uploaded.";
			return FALSE;
		endif;
		// Check if file is not empty
		if (!isset($file) || !is_uploaded_file($file['tmp_name'])):
			// Error: in file upload
			$this->error = "Uploaded file is Missing.";
			return FALSE;
		endif;
		// Check if file doesn't contain any error
		if ($file['error'] != 0):
			// Error: report what php says went wrong
			$this->error = $this->fileUploadErrors[$file['error']];
			return FALSE;
		endif;
		return TRUE;
	}
1258851
public function actionIndex()
    {
        $this->requirePostRequest();
        $request = Craft::$app->getRequest();
        $plugin = Plugin::getInstance();
        $settings = $plugin->getSettings();

        $submission = new Submission();
        $submission->fromEmail = $request->getBodyParam('fromEmail');
        $submission->fromName = $request->getBodyParam('fromName');
        $submission->subject = $request->getBodyParam('subject');

        $message = $request->getBodyParam('message');
        if (is_array($message)) {
            $submission->message = array_filter($message, function($value) {
                return $value !== '';
            });
        } else {
            $submission->message = $message;
        }

        if ($settings->allowAttachments && isset($_FILES['attachment']) && isset($_FILES['attachment']['name'])) {
            if (is_array($_FILES['attachment']['name'])) {
                $submission->attachment = UploadedFile::getInstancesByName('attachment');
            } else {
                $submission->attachment = [UploadedFile::getInstanceByName('attachment')];
            }
        }

        if (!$plugin->getMailer()->send($submission)) {
            if ($request->getAcceptsJson()) {
                return $this->asJson(['errors' => $submission->getErrors()]);
            }

            Craft::$app->getSession()->setError(Craft::t('contact-form', 'There was a problem with your submission, please check the form and try again!'));
            Craft::$app->getUrlManager()->setRouteParams([
                'variables' => ['message' => $submission]
            ]);

            return null;
        }

        if ($request->getAcceptsJson()) {
            return $this->asJson(['success' => true]);
        }

        Craft::$app->getSession()->setNotice($settings->successFlashMessage);
        return $this->redirectToPostedUrl($submission);
    }
1205837
protected function handleUpload()
    {
        $this->uploadedField = array_keys($_FILES)[0];
        //check if any uploaded file for a defined field
        $this->uploadOk = $this->checkUpload();
        if(!$this->uploadOk) {
            return;
        }
        //exec upload
        $this->uploadOk = $this->uploadFields[$this->uploadedField]->handleUpload($this->uploader);
        if(!$this->uploadOk) {
            return;
        }
        //outputs post processing
        $outputs = $this->uploadFields[$this->uploadedField]->getOutputsFiles();
        foreach($this->uploadFieldsDefinitions[$this->uploadedField]['outputs'] as $output => $outputDefinition) {
            if(isset($outputDefinition['processor'])) {
                $this->{$outputDefinition['processor']}($outputs[$output]['path']);
            }
        }
    }
808384
public function store()
    {
        try {
            $request = app(FileStoreRequest::class);
            $this->model->manageUpload($request->file('file'), $request->except('file'));
            return redirect()->route('admin.files.index')->withStatus(__('msg.uploaded_success'));
        } catch (ValidationException $e) {
            $message = $e->validator->errors()->first();
            return redirect()->back()->withInput()->withErrors($message);
        } catch (\Exception $e) {
            $message = 'owner' == user('role') ? $e->getMessage() : __('validation.uploaded');
            return redirect()->back()->withInput()->withErrors($message);
        }
    }
77744
public function validate()
    {
        $multipleUploads = false;
        if (strval($this->multiple) != '') {
            $field = str_replace('[]', '', $this->name);
            if (isset($_FILES[$field]['name'][0]) && strlen($_FILES[$field]['name'][0]) > 0) {
                $multipleUploads = true;
            }
        }

        if (!$this->checkValue($multipleUploads)) {
            return false;
        }

        $validator = $this->getValidator();
        $this->callValidator($validator);

        if ($this->customError) {
            return false;
        }

        return true;
    }
987913
public function handleRequest()
    {
        $response = '';

        if(!isset($_GET)) {
            $this->error('INVALID_ACTION');
        } else {

            if(isset($_GET['mode']) && $_GET['mode']!='') {

                switch($_GET['mode']) {

                    default:
                        $this->error('MODE_ERROR');
                        break;

                    case 'initiate':
                        $response = $this->actionInitiate();
                        break;

                    case 'getfile':
                        if($this->getvar('path')) {
                            $response = $this->actionGetFile();
                        }
                        break;

                    case 'getfolder':
                        if($this->getvar('path')) {
                            $response = $this->actionGetFolder();
                        }
                        break;

                    case 'rename':
                        if($this->getvar('old') && $this->getvar('new')) {
                            $response = $this->actionRename();
                        }
                        break;

                    case 'copy':
                        if($this->getvar('source') && $this->getvar('target')) {
                            $response = $this->actionCopy();
                        }
                        break;

                    case 'move':
                        if($this->getvar('old') && $this->getvar('new')) {
                            $response = $this->actionMove();
                        }
                        break;

                    case 'editfile':
                        if($this->getvar('path')) {
                            $response = $this->actionEditFile();
                        }
                        break;

                    case 'delete':
                        if($this->getvar('path')) {
                            $response = $this->actionDelete();
                        }
                        break;

                    case 'addfolder':
                        if($this->getvar('path') && $this->getvar('name')) {
                            $response = $this->actionAddFolder();
                        }
                        break;

                    case 'download':
                        if($this->getvar('path')) {
                            $response = $this->actionDownload();
                        }
                        break;

                    case 'getimage':
                        if($this->getvar('path')) {
                            $thumbnail = isset($_GET['thumbnail']);
                            $this->actionGetImage($thumbnail);
                        }
                        break;

                    case 'readfile':
                        if($this->getvar('path')) {
                            $this->actionReadFile();
                        }
                        break;

                    case 'summarize':
                        $response = $this->actionSummarize();
                        break;
                }

            } else if(isset($_POST['mode']) && $_POST['mode']!='') {

                switch($_POST['mode']) {

                    default:
                        $this->error('MODE_ERROR');
                        break;

                    case 'upload':
                        if($this->postvar('path')) {
                            $response = $this->actionUpload();
                        }
                        break;

                    case 'replace':
                        if($this->postvar('path')) {
                            $response = $this->actionReplace();
                        }
                        break;

                    case 'savefile':
                        if($this->postvar('path') && $this->postvar('content', false)) {
                            $response = $this->actionSaveFile();
                        }
                        break;

                    case 'extract':
                        if($this->postvar('source') && $this->postvar('target')) {
                            $response = $this->actionExtract();
                        }
                        break;
                }
            }
        }

        echo json_encode([
            'data' => $response,
        ]);
        exit;
    }
1053090
public function upload()
    {
        if ($this->isValid() === false) {
            throw new \Upload\Exception('File validation failed');
        }

        foreach ($this->objects as $fileInfo) {
            $this->applyCallback('beforeUpload', $fileInfo);
            $this->storage->upload($fileInfo);
            $this->applyCallback('afterUpload', $fileInfo);
        }

        return true;
    }
111120
protected function handleDownload()
    {
        $path = explode('/', str_replace('/get', '', $this->request->path()));
        $key  = end($path);

        if ( ! $fileMeta = $this->cache->get($key)) {
            return $this->response->send('404 upload not found.', HttpResponse::HTTP_NOT_FOUND);
        }

        $resource = $fileMeta['file_path'] ?? null;
        $fileName = $fileMeta['name'] ?? null;

        if ( ! $resource || ! file_exists($resource)) {
            return $this->response->send('404 upload not found.', HttpResponse::HTTP_NOT_FOUND);
        }

        return $this->response->download($resource, $fileName);
    }
954286
public function actionUpload()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        $model = new Mediafile();
        $routes = $this->module->routes;
        $rename = $this->module->rename;
	    $tagIds = Yii::$app->request->post('tagIds');

	    if ($tagIds !== 'undefined') {
		    $model->setTagIds(explode(',', $tagIds));
	    }

        $model->saveUploadedFile($routes, $rename);
        $bundle = FilemanagerAsset::register($this->view);

        if ($model->isImage()) {
            $model->createThumbs($routes, $this->module->thumbs);
        }

        $response['files'][] = [
            'url'           => $model->url,
            'thumbnailUrl'  => $model->getDefaultThumbUrl($bundle->baseUrl),
            'name'          => $model->filename,
            'type'          => $model->type,
            'size'          => $model->file->size,
            'deleteUrl'     => Url::to(['file/delete', 'id' => $model->id]),
            'deleteType'    => 'POST',
        ];

        return $response;
    }
228872
public function actions()
    {
        return [
            'image-upload' => \bizley\contenttools\actions\UploadAction::class,
            'image-insert' => \bizley\contenttools\actions\InsertAction::class,
            'image-rotate' => \bizley\contenttools\actions\RotateAction::class,
        ];
    }
1243908
public function isValid()
    {
        $isOk = $this->error === UPLOAD_ERR_OK;

        return $this->test ? $isOk : $isOk && is_uploaded_file($this->getPathname());
    }
695536
public function validateUpload()
    {
        $varInput = parent::validateUpload();

        // Check image size
        if (($arrImageSize = @getimagesize(TL_ROOT . '/' . $varInput)) !== false) {

            // Image exceeds maximum image width
            if ($arrImageSize[0] > $GLOBALS['TL_CONFIG']['imageWidth']) {
                $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['filewidth'], '', $GLOBALS['TL_CONFIG']['imageWidth']));
            }

            // Image exceeds maximum image height
            if ($arrImageSize[1] > $GLOBALS['TL_CONFIG']['imageHeight']) {
                $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['fileheight'], '', $GLOBALS['TL_CONFIG']['imageHeight']));
            }
        }

        return $varInput;
    }