Read uploaded files info from HTTP request data

@return void
171505
protected function readFromHttpData()
    {
        // Check validity of the uploaded files
        $aTempFiles = [];
        foreach($_FILES as $sVarName => $aFile)
        {
            if(is_array($aFile['name']))
            {
                $nFileCount = count($aFile['name']);
                for($i = 0; $i < $nFileCount; $i++)
                {
                    if(!$aFile['name'][$i])
                    {
                        continue;
                    }
                    if(!array_key_exists($sVarName, $aTempFiles))
                    {
                        $aTempFiles[$sVarName] = [];
                    }
                    // Filename without the extension
                    $sFilename = $this->filterFilename(pathinfo($aFile['name'][$i], PATHINFO_FILENAME), $sVarName);
                    // Copy the file data into the local array
                    $aTempFiles[$sVarName][] = [
                        'name' => $aFile['name'][$i],
                        'type' => $aFile['type'][$i],
                        'tmp_name' => $aFile['tmp_name'][$i],
                        'error' => $aFile['error'][$i],
                        'size' => $aFile['size'][$i],
                        'filename' => $sFilename,
                        'extension' => pathinfo($aFile['name'][$i], PATHINFO_EXTENSION),
                    ];
                }
            }
            else
            {
                if(!$aFile['name'])
                {
                    continue;
                }
                if(!array_key_exists($sVarName, $aTempFiles))
                {
                    $aTempFiles[$sVarName] = [];
                }
                // Filename without the extension
                $sFilename = $this->filterFilename(pathinfo($aFile['name'], PATHINFO_FILENAME), $sVarName);
                // Copy the file data into the local array
                $aTempFiles[$sVarName][] = [
                    'name' => $aFile['name'],
                    'type' => $aFile['type'],
                    'tmp_name' => $aFile['tmp_name'],
                    'error' => $aFile['error'],
                    'size' => $aFile['size'],
                    'filename' => $sFilename,
                    'extension' => pathinfo($aFile['name'], PATHINFO_EXTENSION),
                ];
            }
        }

        // Check uploaded files validity
        foreach($aTempFiles as $sVarName => $aFiles)
        {
            foreach($aFiles as $aFile)
            {
                // Verify upload result
                if($aFile['error'] != 0)
                {
                    throw new \Jaxon\Exception\Error($this->trans('errors.upload.failed', $aFile));
                }
                // Verify file validity (format, size)
                if(!$this->validateUploadedFile($sVarName, $aFile))
                {
                    throw new \Jaxon\Exception\Error($this->getValidatorMessage());
                }
                // Get the path to the upload dir
                $this->getUploadDir($sVarName);
            }
        }

        // Copy the uploaded files from the temp dir to the user dir
        foreach($aTempFiles as $sVarName => $aTempFiles)
        {
            $this->aUserFiles[$sVarName] = [];
            foreach($aTempFiles as $aFile)
            {
                // Get the path to the upload dir
                $sUploadDir = $this->getUploadDir($sVarName);
                // Set the user file data
                $xUploadedFile = UploadedFile::fromHttpData($sUploadDir, $aFile);
                // All's right, move the file to the user dir.
                move_uploaded_file($aFile["tmp_name"], $xUploadedFile->path());
                $this->aUserFiles[$sVarName][] = $xUploadedFile;
            }
        }
    }
1319032
private void readHttpDataChunkByChunk() {
        try {
            while (decoder.hasNext()) {
                InterfaceHttpData data = decoder.next();
                if (data != null) {
                    // check if current HttpData is a FileUpload and previously set as partial
                    if (partialContent == data) {
                        logger.info(" 100% (FinalSize: " + partialContent.length() + ")");
                        partialContent = null;
                    }
                    // new value
                    writeHttpData(data);
                }
            }
            // Check partial decoding for a FileUpload
            InterfaceHttpData data = decoder.currentPartialHttpData();
            if (data != null) {
                StringBuilder builder = new StringBuilder();
                if (partialContent == null) {
                    partialContent = (HttpData) data;
                    if (partialContent instanceof FileUpload) {
                        builder.append("Start FileUpload: ")
                            .append(((FileUpload) partialContent).getFilename()).append(" ");
                    } else {
                        builder.append("Start Attribute: ")
                            .append(partialContent.getName()).append(" ");
                    }
                    builder.append("(DefinedSize: ").append(partialContent.definedLength()).append(")");
                }
                if (partialContent.definedLength() > 0) {
                    builder.append(" ").append(partialContent.length() * 100 / partialContent.definedLength())
                        .append("% ");
                    logger.info(builder.toString());
                } else {
                    builder.append(" ").append(partialContent.length()).append(" ");
                    logger.info(builder.toString());
                }
            }
        } catch (EndOfDataDecoderException e1) {
            // end
            responseContent.append("\r\n\r\nEND OF CONTENT CHUNK BY CHUNK\r\n\r\n");
        }
    }
828208
public function processAll()
    {
        $content_range = $this->getContentRange();
        $size = $this->getSize();
        $this->files = [];
        $upload = $this->upload;

        if ($this->logger) {
            $this->logger->debug('Processing uploads', [
                'Content-range' => $content_range,
                'Size' => $size,
                'Upload array' => $upload,
                'Server array' => $this->server,
            ]);
        }

        if ($upload && is_array($upload['tmp_name'])) {
            foreach ($upload['tmp_name'] as $index => $tmp_name) {
                if (empty($tmp_name)) {
                    // Discard empty uploads
                    continue;
                }

                $this->files[] = $this->process(
                    $tmp_name,
                    $upload['name'][$index],
                    $size ? $size : $upload['size'][$index],
                    $upload['type'][$index],
                    $upload['error'][$index],
                    $index,
                    $content_range
                );
            }
        } else {
            if ($upload && ! empty($upload['tmp_name'])) {
                $this->files[] = $this->process(
                    $upload['tmp_name'],
                    $upload['name'],
                    $size ? $size : (isset($upload['size']) ? $upload['size'] : $this->getContentLength()),
                    isset($upload['type']) ? $upload['type'] : $this->getContentType(),
                    $upload['error'],
                    0,
                    $content_range
                );
            } else {
                if ($upload && $upload['error'] != 0) {
                    // $this->fileContainer is empty at this point
                    // $upload['tmp_name'] is also empty
                    // So we create a File instance from $upload['name']
                    $file = new File($upload['name'], basename($upload['name']));
                    $file->error = $this->getMessage($upload['error']);
                    $file->errorCode = $upload['error'];
                    $this->files[] = $file;
                }
            }
        }

        return [$this->files, $this->getNewHeaders($this->files, $content_range)];
    }
1135439
protected function handlePOST()
    {
        $extract = $this->request->getParameterAsBool('extract', false);
        $clean = $this->request->getParameterAsBool('clean', false);
        $checkExist = $this->request->getParameterAsBool('check_exist', false);

        if (empty($this->filePath)) {
            $fileNameHeader = str_to_utf8($this->request->getHeader('X-File-Name'));
            $folderNameHeader = str_to_utf8($this->request->getHeader('X-Folder-Name'));
            $fileUrl = filter_var($this->request->getParameter('url', ''), FILTER_SANITIZE_URL);

            if (!empty($fileNameHeader)) {
                // html5 single posting for file create
                $result = $this->handleFileContent(
                    $this->folderPath,
                    $fileNameHeader,
                    $this->request->getContent(),
                    $this->request->getContentType(),
                    $extract,
                    $clean,
                    $checkExist
                );
            } elseif (!empty($folderNameHeader)) {
                // html5 single posting for folder create
                $fullPathName = $this->folderPath . $folderNameHeader;
                $content = $this->request->getPayloadData();
                $this->driver->createFolder($this->container, $fullPathName, $content);
                $result = ['name' => $folderNameHeader, 'path' => $fullPathName];
            } elseif (!empty($fileUrl)) {
                // upload a file from a url, could be expandable zip
                $tmpName = null;
                $newFileName = $this->request->input('filename', '');
                try {
                    $tmpName = FileUtilities::importUrlFileToTemp($fileUrl);
                    $result = $this->handleFile(
                        $this->folderPath,
                        $newFileName,
                        $tmpName,
                        '',
                        $extract,
                        $clean,
                        $checkExist
                    );
                    @unlink($tmpName);
                } catch (\Exception $ex) {
                    if (!empty($tmpName)) {
                        @unlink($tmpName);
                    }
                    throw $ex;
                }
            } elseif (null !== $uploadedFiles = $this->request->getFile('files')) {
                if (Arr::isAssoc($uploadedFiles)) { //Single file upload
                    $uploadedFiles = [$uploadedFiles];
                }
                $result = $this->handleFolderContentFromFiles($uploadedFiles, $extract, $clean, $checkExist);
                $result = ResourcesWrapper::cleanResources($result);
            } else {
                // possibly xml or json post either of files or folders to create, copy or move
                if (!empty($data = ResourcesWrapper::unwrapResources($this->getPayloadData()))) {
                    $result = $this->handleFolderContentFromData($data, $extract, $clean, $checkExist);
                    $result = ResourcesWrapper::cleanResources($result);
                } else {
                    // create folder from resource path
                    $this->driver->createFolder($this->container, $this->folderPath);
                    $result = ['name' => basename($this->folderPath), 'path' => $this->folderPath];
                }
            }
        } else {
            // create the file
            // possible file handling parameters
            $name = basename($this->filePath);
            $path = (false !== strpos($this->filePath, '/')) ? dirname($this->filePath) : '';
            $files = $this->request->getFile('files');

            if (empty($files)) {
                // direct load from posted data as content
                // or possibly xml or json post of file properties create, copy or move
                $result = $this->handleFileContent(
                    $path,
                    $name,
                    $this->request->getContent(),
                    $this->request->getContentType(),
                    $extract,
                    $clean,
                    $checkExist
                );
            } else {
                if (Arr::isAssoc($files)) { // Single file upload
                    $files = [$files];
                }
                if (1 < count($files)) {
                    throw new BadRequestException("Multiple files uploaded to a single REST resource '$name'.");
                }
                $file = array_get($files, 0);
                if (empty($file)) {
                    throw new BadRequestException("No file uploaded to REST resource '$name'.");
                }
                $error = $file['error'];
                if (UPLOAD_ERR_OK == $error) {
                    $result = $this->handleFile(
                        $path,
                        $name,
                        $file["tmp_name"],
                        $file['type'],
                        $extract,
                        $clean,
                        $checkExist
                    );
                } else {
                    throw new InternalServerErrorException("Failed to upload file $name.\n$error");
                }
            }
        }

        return ResponseFactory::create($result, null, ServiceResponseInterface::HTTP_CREATED);
    }
660639
private static function http()
    {
        $files = ['Http', 'Request'];
        $folder = static::$root.'Http'.'/';

        self::call($files, $folder);

        static::links();
        static::redirect();
        static::middleware();
    }
1008104
public function getFileInfo()
    {
        $result = array(
            "state" => $this->stateInfo,
            "url" => $this->fullName,
            "title" => $this->fileName,
            "original" => $this->oriName,
            "type" => $this->fileType,
            "size" => $this->fileSize
        );
        if( in_array($_GET['action'], ['uploadfile', 'uploadvideo', 'uploadscrawl']) ) $result['url'] = yii::$app->params['site']['url'].'/uploads/article/ueditor'.$result['url'];
        return $result;
    }
248447
private function getHttpParameters()
    {
        if (empty($this->httpParameters)) {
            // Discover the parameters from the server data.
            $uri = $_SERVER['REQUEST_URI'];
            $paramsStart = strpos($uri, '?');
            if ($paramsStart !== false) {
                // Separate the parameters in the URL.
                parse_str(substr($uri, $paramsStart + 1), $this->httpParameters);
            }

            // Get POST parameters as well.
            $this->httpParameters = array_merge($this->httpParameters, $_POST);

            // Get files too.
            $this->httpParameters = array_merge($this->httpParameters, $_FILES);
        }

        return $this->httpParameters;
    }
306407
public function getUploadedFiles()
    {
        if ($this->_uploadedFiles === null) {
            $this->getParsedBody(); // uploaded files are the part of the body and may be set while its parsing
            if ($this->_uploadedFiles === null) {
                $this->_uploadedFiles = $this->defaultUploadedFiles();
            }
        }
        return $this->_uploadedFiles;
    }
150032
private function storeValues()
    {
        $this->debug->groupCollapsed(__METHOD__);
        // if (!$this->status['keyVerified']) {
        if (!$this->status['submitted']) {
            // $this->debug->warn('not submitted');
            $this->debug->groupEnd();
            return;
        }
        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == 'POST') {
            $this->debug->warn('POST method');
            if (isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'] > Str::getBytes(\ini_get('post_max_size'), true)) {
                $this->debug->warn('post_max_size exceeded');
                $this->alerts->add('Your upload has exceeded the '.Str::getBytes(\ini_get('post_max_size')).' limit');
                $this->status['postMaxExceeded'] = true;
            }
            $values = $_POST;
            foreach ($_FILES as $k => $file) {
                if ($file['error'] === UPLOAD_ERR_NO_FILE) {
                    continue;
                }
                if ($file['error'] === UPLOAD_ERR_OK) {
                    // by calling move_uploaded_file, we prevent its automatic deletion
                    \move_uploaded_file($file['tmp_name'], $file['tmp_name']);
                }
                $values[$k] = $file;
                /*
                errors:
                    UPLOAD_ERR_OK => 'There is no error, the file uploaded with success',
                    UPLOAD_ERR_INI_SIZE => 'The uploaded file exceeds the upload_max_filesize directive in php.ini ('.\ini_get('upload_max_filesize').')',
                    UPLOAD_ERR_FORM_SIZE => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
                    UPLOAD_ERR_PARTIAL => 'The uploaded file was only partially uploaded',
                    UPLOAD_ERR_NO_FILE => 'No file was uploaded',
                    UPLOAD_ERR_NO_TMP_DIR => 'Missing a temporary folder',
                    UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk.',
                    UPLOAD_ERR_EXTENSION => 'A PHP extension stopped the file upload.',
                */
            }
            $this->status['submitted'] = true;
            $this->persist->set('submitted', true);
            $this->persist->set('currentPage.values', $values);
        } elseif (\strtolower($this->cfg['attribs']['method']) == 'get') {
            $this->debug->warn('storing GET vals');
            $this->persist->set('currentPage.values', $_GET);
        }
        $this->debug->groupEnd();
    }
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());
                }
            }
        }
    }
940918
private function setHeader ()
    {
        ob_get_clean ();
        header ("Content-Type: video/mp4");
        header ("Cache-Control: max-age=2592000, public");
        header ("Expires: " . gmdate ('D, d M Y H:i:s', time () + 2592000) . ' GMT');
        header ("Last-Modified: " . gmdate ('D, d M Y H:i:s', @filemtime ($this->path)) . ' GMT');
        $this->start = 0;
        $this->size  = filesize ($this->path);
        $this->end   = $this->size - 1;
        header ("Accept-Ranges: 0-" . $this->end);

        if (isset($_SERVER['HTTP_RANGE'])) {

            $c_start = $this->start;
            $c_end   = $this->end;

            list(, $range) = explode ('=', $_SERVER['HTTP_RANGE'], 2);

            if (strpos ($range, ',') !== false) {
                header ('HTTP/1.1 416 Requested Range Not Satisfiable');
                header ("Content-Range: bytes $this->start-$this->end/$this->size");
                exit;
            }

            if ($range == '-') {
                $c_start = $this->size - substr ($range, 1);
            } else {
                $range   = explode ('-', $range);
                $c_start = $range[0];

                $c_end = (isset($range[1]) && is_numeric ($range[1])) ? $range[1] : $c_end;
            }

            $c_end = ($c_end > $this->end) ? $this->end : $c_end;

            if ($c_start > $c_end || $c_start > $this->size - 1 || $c_end >= $this->size) {
                header ('HTTP/1.1 416 Requested Range Not Satisfiable');
                header ("Content-Range: bytes $this->start-$this->end/$this->size");
                exit;
            }

            $this->start = $c_start;
            $this->end   = $c_end;
            $length      = $this->end - $this->start + 1;

            fseek ($this->stream, $this->start);
            header ('HTTP/1.1 206 Partial Content');
            header ("Content-Length: " . $length);
            header ("Content-Range: bytes $this->start-$this->end/" . $this->size);
        } else
            header ("Content-Length: " . $this->size);
    }
914396
protected function determineInputFiles()
    {
        if (empty($this->route->getParameters()->files))
        {
            $this->setNotReady("No input files found.", null, 404);
            return;
        }

        if (is_array($this->route->getParameters()->files))
        {
            foreach ($this->route->getParameters()->files as $file)
            {
                $this->addFileObject((string) $file);
            }
        }
        else
        {
            $this->addFileObject((string) $this->route->getParameters()->files);
        }
    }
531915
protected function _uploadFile() : string
    {
        if (! is_string($this->request->getData('file.name'))) {
            return '';
        }

        if (! is_string($this->request->getData('file.tmp_name'))) {
            return '';
        }

        $uploadPath = $this->_getUploadPath();
        if ('' === $uploadPath) {
            return '';
        }

        $pathInfo = pathinfo($this->request->getData('file.name'));

        $filename = (string)preg_replace('/\W/', '_', $pathInfo['filename']);
        $filename = (string)preg_replace('/_+/', '_', $filename);
        $filename = trim($filename, '_');
        $extension = $pathInfo['extension'] ?? '';
        if (!empty($extension)) {
            $extension = '.' . $extension;
        }

        $path = sprintf(
            '%s%s_%s%s',
            $uploadPath,
            (new Time())->i18nFormat('yyyyMMddHHmmss'),
            $filename,
            $extension
        );

        if (! move_uploaded_file($this->request->getData('file.tmp_name'), $path)) {
            return '';
        }

        return $path;
    }
308721
public function uploadedFiles()
    {
        if (!$this->files) {
            $this->files = new UploadedFiles($_FILES);
        }
        return $this->files->files();
    }
186100
public function getFileInfo()
    {
        $ret = array(
            'uploadId' => $this->id,
            'mimeType' => $this->mime_type,
            'filename' => $this->filename,
            'extension'=> $this->extension,
            'fileSize' => $this->getFileSize(),
            'hashKey'  => $this->getHashKey()
        );
        if (!$this->id && is_file($this->filename)) {
            $ret['mimeType'] = $this->_getMimeType($this->filename);
            $ret['extension'] = substr(strrchr($this->filename, '.'), 1);
        }
        $size = $this->getImageDimensions();
        if ($size) {
            $ret['image'] = true;
            $ret['imageHandyScaleFactor'] = Kwf_Media_Image::getHandyScaleFactor($size);
            if (abs($size['rotation']) == 90) {
                $size = array('width'=>$size['height'], 'height'=>$size['width']);
            }
            $ret['imageWidth'] = $size['width'];
            $ret['imageHeight'] = $size['height'];
        } else {
            $ret['image'] = false;
        }
        return $ret;
    }
31739
private static function input()
    {
        $files = ['Input'];
        $folder = static::$root.'Http'.'/';

        self::call($files, $folder);

        Input::register();
    }
478860
public function getData() {
        $values = array_filter(filter_input_array(INPUT_POST));
        foreach ($values as $key => $value) {
            if ( is_array($value) )  {
                $values[$key] = array_filter($value);
            }
        }

        return $values + $_FILES;
    }