Uploads current chunk.
@throws \yii\base\ErrorException
556329
public function uploadChunk ()
		{
			move_uploaded_file($this->_file[ 'tmp_name' ], $this->chunkPath);

			Yii::$app->response->setStatusCode(200);
		}
39118
public function uploadFile()
    {
        if (!$this->request->files->has('file')) {
            return false;
        }
        $file   = $this->request->files->get('file');
        $upload = rtrim($this->uploadDir, '/');
        if (!is_dir($upload)) {
            mkdir($upload, 0777, true);
        }
        $file->move(realpath($upload), $file->getClientOriginalName());

        return sprintf('/%s/%s', pathinfo($upload, PATHINFO_BASENAME),
            pathinfo($file->getClientOriginalName(), PATHINFO_BASENAME));
    }
511816
public function upload()
    {
        $multipartStream = new Psr7\MultipartStream([
            [
                'name' => 'metadata',
                'headers' => ['Content-Type' => 'application/json; charset=UTF-8'],
                'contents' => $this->jsonEncode($this->metadata)
            ],
            [
                'name' => 'data',
                'headers' => ['Content-Type' => $this->contentType],
                'contents' => $this->data
            ]
        ], 'boundary');

        $headers = [
            'Content-Type' => 'multipart/related; boundary=boundary',
            'Content-Length' => $multipartStream->getSize()
        ];

        return $this->jsonDecode(
            $this->requestWrapper->send(
                new Request(
                    'POST',
                    $this->uri,
                    $headers,
                    $multipartStream
                ),
                $this->requestOptions
            )->getBody(),
            true
        );
    }
423817
protected function flow(): void
	{
		// Erase output buffers and disable output buffering

		while(ob_get_level() > 0) ob_end_clean();

		// Send the stream

		$stream = $this->stream;

		$stream($this);

		// Send empty chunk to tell the client that we're done

		$this->flush(null, true);
	}
185514
public function performUploading() {
        for ($i = 0; $i < $this->concurrentTaskNumber; ++$i) {
            if ($this->offset >= $this->fileSize) {
                break;
            }

            $sliceContent = file_get_contents($this->srcFpath, false, null, $this->offset, $this->sliceSize);
            if ($sliceContent === false) {
                $this->setError(Response::COSAPI_PARAMS_ERROR, 'read file ' . $this->srcFpath . ' error');
                return false;
            }

            $request = new HttpRequest();
            $request->timeoutMs = $this->timeoutMs;
            $request->url = $this->url;
            $request->method = 'POST';
            $request->customHeaders = array(
                        'Authorization: ' . $this->signature,
                    );
            $request->dataToPost = array(
                        'op' => 'upload_slice_data',
                        'session' => $this->session,
                        'offset' => $this->offset,
                        'filecontent' => $sliceContent,
                        'datamd5' => md5($sliceContent),
                    );
            $request->userData = array(
                        'retryCount' => 0,
                    );

            $this->libcurlWrapper->startSendingRequest($request, array($this, 'uploadCallback'));

            $this->offset += $this->sliceSize;
        }

        $this->libcurlWrapper->performSendingRequest();

        if ($this->errorCode !== Response::COSAPI_SUCCESS) {
            return false;
        }

        return true;
    }
498883
function(e){
          var status = $.status();
          if(status=='success'||status=='error') {
            $.callback(status, $.message());
            $.resumableObj.uploadNextChunk();
          } else {
            $.callback('retry', $.message());
            $.abort();
            $.retries++;
            var retryInterval = $.getOpt('chunkRetryInterval');
            if(retryInterval !== undefined) {
              $.pendingRetry = true;
              setTimeout($.send, retryInterval);
            } else {
              $.send();
            }
          }
        }
1040317
public function actionProcess()
    {
        ini_set("memory_limit", "512M");

        $imaging = \Yii::$app->imaging;
        if (!$imaging) {
            //TODO: можно добавить проверку YII ensure...
            throw new \yii\base\Exception("Component Imaging not found");
        }

        $newFileSrc = \Yii::$app->request->getPathInfo();
        $extension = Imaging::getExtension($newFileSrc);

        if (!$extension) {
            throw new \yii\base\Exception("Extension not found: ".$newFileSrc);
        }


        if (!$imaging->isAllowExtension($extension)) {
            throw new \yii\base\Exception("Extension '{$extension}' not supported in Imaging component");
        }


        $newFile = File::object($newFileSrc);
        $strposFilter = strpos($newFileSrc, "/".Imaging::THUMBNAIL_PREFIX);
        if (!$strposFilter) {
            throw new NotFoundHttpException("This is not a filter thumbnail: ".$newFileSrc);
        }

        $originalFileSrc = substr($newFileSrc, 0, $strposFilter).".".$newFile->getExtension();

        //TODO: hardcode delete it in the future
        $webRoot = \Yii::getAlias('@webroot');

        $originalFileRoot = $webRoot.DIRECTORY_SEPARATOR.$originalFileSrc;
        $newFileRoot = $webRoot.DIRECTORY_SEPARATOR.$newFileSrc;
        $newFileRootDefault = $webRoot.DIRECTORY_SEPARATOR.str_replace($newFile->getBaseName(),
                Imaging::DEFAULT_THUMBNAIL_FILENAME.".".$extension, $newFileSrc);

        $originalFile = new File($originalFileRoot);

        if (!$originalFile->isExist()) {
            throw new NotFoundHttpException("The original file is not found: ".$newFileSrc);
        }

        //Проверено наличие оригинального файла, есть пути к оригиналу, и результирующему файлу.
        //Отслось собрать фильтр, и проверить наличие параметров. А так же проверить разрешены ли эти параметры, для этого в строке есть захэшированный ключь

        $filterSting = substr($newFileSrc, ($strposFilter + strlen(DIRECTORY_SEPARATOR.Imaging::THUMBNAIL_PREFIX)),
            strlen($newFileSrc));
        $filterCode = explode("/", $filterSting);
        $filterCode = $filterCode[0]; //Код фильтра

        //Если указаны парамтры, то ноужно проверить контрольную строчку, и если они не соответствуют ей, то ничего делать не будем
        if ($params = \Yii::$app->request->get()) {
            $pramsCheckArray = explode(DIRECTORY_SEPARATOR, $filterSting);
            if (count($pramsCheckArray) < 3) {
                throw new \yii\base\Exception("the control line not found: ".$newFileSrc);
            }

            $string = $imaging->getParamsCheckString($params);
            if ($pramsCheckArray[1] != $string) {
                throw new \yii\base\Exception("Parameters invalid: ".$newFileSrc);
            }
        }

        $filterClass = str_replace("-", "\\", $filterCode);


        if (!class_exists($filterClass)) {
            throw new \ErrorException("Filter class is not created: ".$newFileSrc);
        }

        /**
         * @var Filter $filter
         */
        $filter = new $filterClass((array)$params);
        if (!is_subclass_of($filter, Filter::className())) {
            throw new NotFoundHttpException("No child filter class: ".$newFileSrc);
        }

        try {
            //Проверяем а создан ли уже файл, и если да то просто делаем на него ссылку.
            $filter
                ->setOriginalRootFilePath($originalFileRoot)
                ->setNewRootFilePath($newFileRootDefault)
                ->save();

            if (PHP_OS === 'Windows') {
                if ($newFileRoot != $newFileRootDefault) {
                    //Не тестировалось
                    copy($newFileRootDefault, $newFileRoot);
                }
            } else {
                if ($newFileRoot != $newFileRootDefault) {
                    symlink($newFileRootDefault, $newFileRoot);
                }
            }

            $url = \Yii::$app->request->getUrl().($params ?
                    ""//"?" . http_build_query($params) . '&sx-refresh'
                    : '?sx-refresh');

            /*Header("HTTP/1.0 200 OK");
            Image::getImagine()->open($newFileRootDefault)->show('png');
            return '';*/

            return \Yii::$app->response->redirect($url, 302);

        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }
577748
public function commit()
    {
        if ($this->rollbackAgain) {
            throw new \wf\db\Exception('Please throw exception after rollback in last catch block');
        }

        --$this->transactions;
    
        if($this->transactions == 0 && false === $this->dbh->commit()) {
            throw new \wf\db\Exception('transaction commit error: ' . $this->getLastErr());
        }

        if ($this->transactions < 0) {
            $this->transactions = 0;
        }
    }
539299
def _flush(self):
        
        # Initialize multipart upload
        if self._upload_id is None:
            with _handle_oss_error():
                self._upload_id = self._bucket.init_multipart_upload(
                    self._key).upload_id

        # Upload part with workers
        response = self._workers.submit(
            self._bucket.upload_part, key=self._key, upload_id=self._upload_id,
            part_number=self._seek, data=self._get_buffer().tobytes())

        # Save part information
        self._write_futures.append(
            dict(response=response, part_number=self._seek))
233333
def _flush(self):
        
        # Initialize multi-part upload
        if 'UploadId' not in self._upload_args:
            with _handle_client_error():
                self._upload_args[
                    'UploadId'] = self._client.create_multipart_upload(
                    **self._client_kwargs)['UploadId']

        # Upload part with workers
        response = self._workers.submit(
            self._client.upload_part, Body=self._get_buffer().tobytes(),
            PartNumber=self._seek, **self._upload_args)

        # Save part information
        self._write_futures.append(
            dict(response=response, PartNumber=self._seek))
417920
public function validateUpload()
    {
        \Message::reset();
        $strTempName = $this->strName . '_fineuploader';
        $objUploader = new \Haste\Util\FileUpload($this->strName);
        $blnIsChunk = isset($_POST['qqpartindex']);

        // Convert the $_FILES array to Contao format
        if (!empty($_FILES[$strTempName])) {
            $arrFile = array
            (
                'name' => array($_FILES[$strTempName]['name']),
                'type' => array($_FILES[$strTempName]['type']),
                'tmp_name' => array($_FILES[$strTempName]['tmp_name']),
                'error' => array($_FILES[$strTempName]['error']),
                'size' => array($_FILES[$strTempName]['size']),
            );

            // Replace the comma character (#22)
            $arrFile['name'] = str_replace(',', '_', $arrFile['name']);

            // Set the UUID as the filename
            if ($blnIsChunk) {
                $arrFile['name'][0] = \Input::post('qquuid') . '.chunk';
            }

            // Check if the file exists
            if (file_exists(TL_ROOT . '/' . $this->strTemporaryPath . '/' . $arrFile['name'][0])) {
                $arrFile['name'][0] = $this->getFileName($arrFile['name'][0], $this->strTemporaryPath);
            }

            $_FILES[$this->strName] = $arrFile;
            unset($_FILES[$strTempName]); // Unset the temporary file
        }

        $varInput = '';

        // Add the "chunk" extension to upload types
        if ($blnIsChunk) {
            $extensions   = trimsplit(',', $GLOBALS['TL_CONFIG']['uploadTypes']);
            $extensions[] = 'chunk';

            $objUploader->setExtensions($extensions);
        }

        // Validate the minlength
        if ($this->arrConfiguration['minlength'] > 0 && !$blnIsChunk) {
            $objUploader->setMinFileSize($this->arrConfiguration['minlength']);
        }

        // Validate the maxlength
        if ($this->arrConfiguration['maxlength'] > 0 || $blnIsChunk) {
            $objUploader->setMaxFileSize($blnIsChunk ? $this->arrConfiguration['chunkSize'] : $this->arrConfiguration['maxlength']);
        }

        // Set the maximum width
        if ($this->arrConfiguration['maxWidth']) {
            $objUploader->setImageWidth($this->arrConfiguration['maxWidth']);
        }

        // Set the maximum height
        if ($this->arrConfiguration['maxHeight']) {
            $objUploader->setImageHeight($this->arrConfiguration['maxHeight']);
        }

        try {
            $varInput = $objUploader->uploadTo($this->strTemporaryPath);

            if ($objUploader->hasError()) {
                if (version_compare(VERSION, '4.2', '>=')) {
                    $session = \System::getContainer()->get('session');

                    foreach ($session->getFlashBag()->peek('contao.'.TL_MODE.'.error') as $strError) {
                        $this->addError($strError);
                    }
                } else {
                    foreach ((array) $_SESSION['TL_ERROR'] as $strError) {
                        $this->addError($strError);
                    }
                }
            }

            \Message::reset();
        } catch (\Exception $e) {
            $this->addError($e->getMessage());
        }

        if (!is_array($varInput) || empty($varInput)) {
            $this->addError($GLOBALS['TL_LANG']['MSC']['fineuploader_error']);
        }

        $varInput = $varInput[0];

        // Store the chunk in the session for further merge
        if ($blnIsChunk) {
            $_SESSION[$this->strName . '_FINEUPLOADER_CHUNKS'][\Input::post('qqfilename')][] = $varInput;

            // This is the last chunking request, merge the chunks and create the final file
            if (\Input::post('qqpartindex') == \Input::post('qqtotalparts') - 1) {
                $strFileName = \Input::post('qqfilename');

                // Get the new file name
                if (file_exists(TL_ROOT . '/' . $this->strTemporaryPath . '/' . $strFileName)) {
                    $strFileName = $this->getFileName($strFileName, $this->strTemporaryPath);
                }

                $objFile = new \File($this->strTemporaryPath . '/' . $strFileName);

                // Merge the chunks
                foreach ($_SESSION[$this->strName . '_FINEUPLOADER_CHUNKS'][\Input::post('qqfilename')] as $strChunk) {
                    $objFile->append(file_get_contents(TL_ROOT . '/' . $strChunk), '');

                    // Delete the file
                    \Files::getInstance()->delete($strChunk);
                }

                $objFile->close();
                $varInput = $objFile->path;

                // Validate the minlength
                if ($this->arrConfiguration['minlength'] > 0 && $objFile->size < $this->arrConfiguration['minlength']) {
                    $readableSize = \System::getReadableSize($this->arrConfiguration['minlength']);
                    $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['minFileSize'], $readableSize));
                    \System::log('File "'.$objFile->name.'" is smaller than the minimum file size of '.$readableSize, __METHOD__, TL_ERROR);
                }

                // Validate the maxlength
                if ($this->arrConfiguration['maxlength'] > 0 && $objFile->size > $this->arrConfiguration['maxlength']) {
                    $readableSize = \System::getReadableSize($this->arrConfiguration['maxlength']);
                    $this->addError(sprintf($GLOBALS['TL_LANG']['ERR']['maxFileSize'], $readableSize));
                    \System::log('File "'.$objFile->name.'" exceeds the maximum file size of '.$readableSize, __METHOD__, TL_ERROR);
                }

                // Reset the chunk flag
                $blnIsChunk = false;

                // Unset the file session after merging the chunks
                unset($_SESSION[$this->strName . '_FINEUPLOADER_CHUNKS'][\Input::post('qqfilename')]);
            }
        }

        // Validate and move the file immediately
        if ($this->arrConfiguration['directUpload'] && !$blnIsChunk) {
            $varInput = $this->validatorSingle($varInput, $this->getDestinationFolder());
        }

        return $varInput;
    }
1009552
public function upload()
    {
        $files = request()->file('file');
        $error_bag = [];
        foreach (is_array($files) ? $files : [$files] as $file) {
            $validation_message = $this->uploadValidator($file);
            $new_filename = $this->proceedSingleUpload($file);

            if ($validation_message !== 'pass') {
                array_push($error_bag, $validation_message);
            } elseif ($new_filename == 'invalid') {
                array_push($error_bag, $response);
            }
        }

        if (is_array($files)) {
            $response = count($error_bag) > 0 ? $error_bag : parent::$success_response;
        } else { // upload via ckeditor 'Upload' tab
            $response = $this->useFile($new_filename);
        }

        return $response;
    }
15506
public function init() {

        parent::init();
        $this->registerTranslations();
        
        if(!$this->secure)
            $this->uploadAction = '/uploader/one-file/create';

        // set min & max file sizes
        if(is_null($this->minFileSize))
            $this->minFileSize = isset(\Yii::$app->params['fileSize']['min']) ? \Yii::$app->params['fileSize']['min'] : 0.01;
        if(is_null($this->maxFileSize))
            $this->maxFileSize = isset(\Yii::$app->params['fileSize']['max']) ? \Yii::$app->params['fileSize']['max'] : 2;

        // errors of the file uploading
        $this->errors['size'] = Yii::t('byone', 'File size can be from {minFileSize} to {maxFileSize}Mb', ['minFileSize' => $this->minFileSize, 'maxFileSize' => $this->maxFileSize]);
        $this->errors['type'] = Yii::t('byone', 'There is not right file type! Allowed types - {acceptFileTypes}.', ['acceptFileTypes' => $this->acceptFileTypes]);
        $this->errors['maxFiles'] = Yii::t('byone', 'Only {maxFiles} file(s) can be uploaded.', ['maxFiles' => $this->maxFiles]);

        // captions of the buttons and other strings that should be translated
        self::$defaults['choose']['label'] = Yii::t('byone', 'Photo');
        self::$defaults['choose']['caption'] = Yii::t('byone', 'Choose a file');
        self::$defaults['delete']['question'] = Yii::t('byone', 'Are you shure you want to delete this element?');
        self::$defaults['crop']['caption'] = Yii::t('byone', 'Upload');
        
        // set buttons by widget parameters or defaults
        foreach(self::$defaults as $name => $values) {
            foreach($values as $property => $value)
                if(!isset($this->btns[$name][$property]))
                    $this->btns[$name][$property] = $property == 'action' && !$this->secure 
                        ? str_replace('-secure', '', self::$defaults[$name][$property])
                        : self::$defaults[$name][$property];
        }
        
        // full path server side handlers
        $this->btns['delete']['action'] = Url::toRoute($this->btns['delete']['action']);
        $this->btns['save']['action'] = Url::toRoute($this->btns['save']['action']);
        $this->btns['crop']['action'] = Url::toRoute($this->btns['crop']['action']);
        $this->btns['swap']['action'] = Url::toRoute($this->btns['swap']['action']);
        
        $this->blueimp['url'] = Url::toRoute($this->uploadAction);
        
        $this->blueimp['minFileSize'] = $this->minFileSize;
        $this->blueimp['maxFileSize'] = $this->maxFileSize;
        
        // max files that can be uploaded
        $this->blueimp['maxFiles'] = $this->maxFiles;

        // if model name is not set, set it
        if(!isset($this->modelName))
            $this->modelName = get_class($this->model);
        // parent_id has to exist
        if(is_null($this->model->id))
            $this->model->id = false;
        if(is_null($this->parent_id))
            $this->parent_id = $this->model->id;
        if(is_null($this->subdir))
            $this->subdir = $this->model->id;
        // POST-type data for the handler
        $this->blueimp['formData'] = [
            'model' => $this->modelName,
            'parent_id' => $this->parent_id,
            'subdir' => $this->subdir,
            'cropAllowed' => ($this->cropAllowed ? 1 : 0),
        ];
        
        // min pixels for X and Y when cropping
        $minW = $this->model->getMin();
        $aspectRatio = $this->model->getAspectRatio();
        $minH = $minW * $aspectRatio;

        // send params to JavaScript environment
        $options = [
            'btns' => $this->btns,
            'barClass' => $this->barClass,
            'cropAllowed' => $this->cropAllowed,
            'minW' => $minW,
            'minH' => $minH,
            'aspectRatio' => $aspectRatio,
            'appendixView' => $this->appendixView,
            'acceptFileTypes' => $this->acceptFileTypes,
            'errors' => $this->errors,
        ];
        $this->view->registerJs(
            "editLine.options = " . json_encode($options) . ";", 
            View::POS_READY, 
            'editLineOptions'
        );
        
        // assets 
        BlueimpAsset::register($this->view);
        EditLineAsset::register($this->view);
        if($this->draggable) {
            JQueryUiAsset::register($this->view);
            DraggableAsset::register($this->view);
        }
        if($this->cropAllowed) 
            JcropAsset::register($this->view);
        // plugin
        $selector = $name = $this->blueimp['name'];
        $option = json_encode($this->blueimp);
        $script = "jQuery('#{$selector}').{$name}({$option});";
        $this->view->registerJs($script, View::POS_END, 'byone-plugin');
    }
346783
public function actionEdit ()
		{
			if (Yii::$app->request->isAjax)
			{
				$setting = Setting::findOne([ 'name' => Yii::$app->request->post('name') ]);
				if ($setting !== null and $setting->fixed == 0)
				{
					$setting->setAttributes([ 'value' => Yii::$app->request->post('value'), 'description' => Yii::$app->request->post('description') ]);
					if (!$setting->save())
						echo Json::encode(current($setting->firstErrors));
					else
						echo 0;
				}
			}
			Yii::$app->end();
		}
190681
public function upload()
    {
        if ($newFile = $this->getNewFileName()){
            $origin = $destination = \Devil::getPathOf($this->config['dest']);
            $this->remove();
            if (isset($this->config['onload'])) {
                $destination .= '/origin';
            }
            if (!is_dir($destination)) mkdir ($destination, 0777, true);
            $realFileName = $destination . '/' . $this->_primaryKey . '_' . $this->getNewFileName();
            if (move_uploaded_file($this->uploaded['tmp_name'], $realFileName)) {
                if (isset($this->config['onload'])) foreach ($this->config['onload'] as $method=>$config) {
                    $this->$method($realFileName, $origin, $config, $this->_primaryKey . '_' . $this->getNewFileName());
                }
            }
        }
    }
592590
public function actionFileReplace()
    {
        $this->checkRouteAccess(self::PERMISSION_ROUTE);
        
        $fileId = Yii::$app->request->post('fileId', false);
        $pageId = Yii::$app->request->post('pageId', 0);
        Yii::warning('replace request for file id' . $fileId, __METHOD__);
        $raw = $_FILES['file'];
        /** @var $file \luya\admin\file\Item */
        if ($file = Yii::$app->storage->getFile($fileId)) {
            $newFileSource = $raw['tmp_name'];
            if (is_uploaded_file($newFileSource)) {
                
                // check for same extension / mimeType
                $fileData = Yii::$app->storage->ensureFileUpload($raw['tmp_name'], $raw['name']);
                
                if ($fileData['mimeType'] != $file->mimeType) {
                    throw new BadRequestHttpException("The type must be the same as the original file in order to replace.");
                }
                
                if (Storage::replaceFile($file->systemFileName, $newFileSource, $raw['name'])) {
                    foreach (StorageImage::find()->where(['file_id' => $file->id])->all() as $img) {
                        $removal = Storage::removeImage($img->id, false);
                    }
                    
                    // calculate new file files based on new file
                    $model = StorageFile::findOne((int) $fileId);
                    $fileHash = FileHelper::md5sum($newFileSource);
                    $fileSize = @filesize($newFileSource);
                    $model->updateAttributes([
                        'hash_file' => $fileHash,
                        'file_size' => $fileSize,
                        'upload_timestamp' => time(),
                    ]);
                    $this->flushApiCache($model->folder_id, $pageId);
                    return true;
                }
            }
        }
        
        return false;
    }
441120
public function handleUpload(): void
	{
		if ($this->request->isAjax()) {
			$file = $this->request->getFile('file');
			if ($file->error !== UPLOAD_ERR_OK) {
				header('HTTP/1.1 500 Internal Server Error');
				header('Content-type: text/plain');
				switch ($file->error) {
					case UPLOAD_ERR_INI_SIZE:
					case UPLOAD_ERR_FORM_SIZE:
						$msg = 'tooBig';
						break;
					case UPLOAD_ERR_NO_FILE:
						$msg = 'noFile';
						break;
					case UPLOAD_ERR_PARTIAL:
					case UPLOAD_ERR_NO_TMP_DIR:
					case UPLOAD_ERR_CANT_WRITE:
					case UPLOAD_ERR_EXTENSION:
						$msg = 'failedUpload';
						break;
				}
				exit($this->translator->translate('nattreid.gallery.error.' . $msg));
			}

			$resource=$this->imageStorage->createResource($file->temporaryFile,$file->sanitizedName);
			$resource->setNamespace($this->namespace);
			$this->imageStorage->save($resource);

			$this->getStorage()->add($resource->getIdentifier());
		}
		throw new AbortException;
	}