Copy file contents from the input stream to a temp file

@param string $name The field name
@param string $filename The name of the uploaded file
@param string $unverifiedContentType The user provided content type
@return \sndsgd\http\UploadedFile
180076
protected function getFileFromField(
        string $name,
        string $filename,
        string $unverifiedContentType
    )
    {
        # create and open a temp file to write the contents to
        $tempPath = $this->getTempFilePath();
        $tempHandle = fopen($tempPath, "w");
        if ($tempHandle === false) {
            fclose($this->fp);
            $message = \sndsgd\Error::createMessage(
                "failed to open '$tempPath' for writing"
            );
            throw new \RuntimeException($message);
        }

        # number of bytes read from the input stream in the last loop cycle
        $bytesRead = 0;
        # the total number of bytes written to the temp file
        $bytesWritten = 0;

        # if anything is left over from the previous field, add it to the file
        if ($this->buffer !== "") {
            $bytesRead = fwrite($tempHandle, $this->buffer);
            if ($bytesRead === false) {
                fclose($this->fp);
                fclose($tempHandle);
                throw new \RuntimeException(
                    "fwrite() failed to write to '$tempPath'"
                );
            }
            $bytesWritten += $bytesRead;
        }

        while (($pos = strpos($this->buffer, $this->boundary)) === false) {
            $this->buffer = fread($this->fp, $this->bytesPerRead);
            $bytesRead = fwrite($tempHandle, $this->buffer);
            if ($bytesRead === false) {
                fclose($this->fp);
                fclose($tempHandle);
                throw new \RuntimeException(
                    "fwrite() failed to write to '$tempPath'"
                );
            }
            $bytesWritten += $bytesRead;
        }

        # determine the size of the file based on the boundary position
        $size = $bytesWritten - $bytesRead + $pos - 2;

        # trim the excess contents of the local buffer to the object buffer
        $this->buffer = substr($this->buffer, $pos);

        # if the uploaded file was empty
        if ($size < 1) {
            return $this->fileUploadError(
                UPLOAD_ERR_NO_FILE,
                $tempPath,
                $tempHandle,
                $filename,
                $unverifiedContentType,
                0
            );
        }

        # if the file exceeded the max upload size
        elseif ($size > $this->maxFileSize) {
            return $this->fileUploadError(
                UPLOAD_ERR_INI_SIZE,
                $tempPath,
                $tempHandle,
                $filename,
                $unverifiedContentType,
                0
            );
        }

        ftruncate($tempHandle, $size);
        fclose($tempHandle);

        return new \sndsgd\http\UploadedFile(
            $filename,
            $unverifiedContentType,
            $size,
            $tempPath
        );
    }
1020652
private function writeTemplateToFile($fileContent, $filename, $force = false)
    {
        $created = false;
        if ($force || !file_exists($filename)) {
            try {
                $this->cache->storeData($filename, $fileContent, Cache::TEXT, true);
                $created = true;
            } catch (\Exception $e) {
                Logger::log($e->getMessage(), LOG_ERR);
            }
        } else {
            Logger::log($filename . t(' not exists or cant write'), LOG_ERR);
        }
        return $created;
    }
877780
private function save($fileName, $filePath, $extension)
    {
        $fullPath = rtrim($filePath, '/').DIRECTORY_SEPARATOR.$fileName.$extension;

        $template = $this->renderTemplate($fullPath);

        $tempExecutable = tmpfile();
        fwrite($tempExecutable, $template);
        $tempFileName = stream_get_meta_data($tempExecutable)['uri'];
        $cmd = escapeshellcmd("{$this->binPath} --ssl-protocol=any --ignore-ssl-errors=true ".$tempFileName);
        shell_exec($cmd);
        fclose($tempExecutable);

        if (!file_exists($fullPath))
        {
            throw new TimeoutException('Page load timeout.');
        }

        return $fullPath;
    }
1200079
public function getFile($name)
    {
        if (!isset($this->files)) {
            $files = $this->getUploadedFiles();
            foreach ($files as $file) {
                $key = $file->getKey();
                if (isset($key)) {
                    $this->files[$key] = $file;
                } else {
                    $this->files[] = $file;
                }
            }
        }
        if (isset($this->files[$name])) {
            return $this->files[$name];
        } else {
            throw new \InvalidArgumentException("Upload file '$name' is empty");
        }
    }
1112550
public function createFile(string $name, string $content = ""): File {
		$url = Paths::normalize(Paths::appendPath($this->getUrl(), $name));
		$this->manager->put($url, $content);

		return new File($url);
	}
292944
public function makeFromRawData($data, $name = null, $mimeType = null)
    {
        $file = new RawStorableFile;

        if ($data instanceof RawContentInterface) {
            $data = $data->content();
        }

        // Guess the mimetype directly from the content
        if (null === $mimeType) {
            $mimeType = $this->mimeTypeHelper->guessMimeTypeForContent($data);
        }

        if (empty($name)) {
            $name = $this->makeRandomName(
                $this->mimeTypeHelper->guessExtensionForMimeType($mimeType)
            );
        }

        $file->setName($name);
        $file->setData($data);
        $file->setMimeType($mimeType);

        return $this->getReturnPreparedFile($file);
    }
1279266
public function updateContentTypeGroup(
        ContentTypeGroupUpdateData $data = null,
        ?string $name = null
    ): FormInterface {
        $name = $name ?: sprintf('update-content-type-group-%d', $data->getContentTypeGroup()->id);

        return $this->formFactory->createNamed($name, ContentTypeGroupUpdateType::class, $data);
    }
36029
protected function createOrUpdateDocument($resource, $name, $filename)
    {
        if (request()->hasFile('file')) {

            // create or update
            if (is_null($resource->document)) {
                $resource->documents()->create([
                    'name'     => $name,
                    'filename' => $filename,
                ]);
            }
            else {
                // update the document entry
                $resource->document->update([
                    'name'     => $name,
                    'filename' => $filename,
                ]);
            }
        }
    }
976475
public function putBlobFromFile($container = '', $name = '', $localFileName = null, $type = '')
    {
        $this->checkConnection();
        try {
            /** @var Container $container */
            $container = $this->blobConn->getContainer($container);
            if (empty($container)) {
                throw new \Exception("No container named '$container'");
            }

            $params = ['name' => $name];
            if (!empty($type)) {
                $params['content_type'] = $type;
            }

            $container->uploadObject($name, file_get_contents($localFileName), $params);
        } catch (\Exception $ex) {
            static::handleGuzzleException($ex);
            throw new DfException("Failed to create blob '$name': " . $ex->getMessage());
        }
    }
1364165
public function copyFile($sourcePath, $targetPath, $filename)
    {
        // Check paths
        if ($sourcePath === $targetPath) {
            return;
        }

        $targetFilepath = $targetPath.$filename;

        // Check if file exists and create it
        if (file_exists($targetFilepath)) {
            return;
        }

        // Build new contents
        $sourceFilepath = $sourcePath.$filename;
        $ctns = '';

        // Check the old file to copy its contents
        if (file_exists($sourceFilepath)) {
            $copy = copy($sourceFilepath, $targetFilepath);
        } else {
            self::filePutContents($targetFilepath, '', 'This file has been auto-generated by the Zeus package without any content');
        }
    }
864008
public function createContentTypeGroup(
        ?ContentTypeGroupCreateData $data = null,
        ?string $name = null
    ): FormInterface {
        $name = $name ?: StringUtil::fqcnToBlockPrefix(ContentTypeGroupCreateType::class);

        return $this->formFactory->createNamed(
            $name,
            ContentTypeGroupCreateType::class,
            $data ?? new ContentTypeGroupCreateData()
        );
    }
28685
public function writeFile($filename)
    {
        $file = $this->getAttribute('file');
        if (empty($file) && !$this->getIsNewRecord()) {
            $file = $this->refreshFile();
        }

        if (empty($file)) {
            throw new InvalidParamException('There is no file associated with this object.');
        } elseif ($file instanceof Download) {
            return ($file->toFile($filename) == $file->getSize());
        } elseif ($file instanceof UploadedFile) {
            return copy($file->tempName, $filename);
        } elseif (is_string($file)) {
            if (file_exists($file)) {
                return copy($file, $filename);
            }
            throw new InvalidParamException("File '{$file}' does not exist.");
        }

        throw new InvalidParamException('Unsupported type of "file" attribute.');
    }
901117
private function createTempFile($name, $content)
    {
        $tempDir  = \sys_get_temp_dir();
        $fileName = \md5($name);
        $filePath = $tempDir . DIRECTORY_SEPARATOR . 'phpcq-author-validation' . DIRECTORY_SEPARATOR . $fileName;

        if (\file_exists($filePath)) {
            return $filePath;
        }

        if (!\file_exists(\dirname($filePath)) && !\mkdir($concurrentDirectory = \dirname($filePath))
            && !is_dir(
                $concurrentDirectory
            )) {
            throw new \RuntimeException(sprintf('Directory "%s" was not created', $concurrentDirectory));
        }

        $file = \fopen($filePath, 'wb');

        \fwrite($file, $content);

        return $filePath;
    }
767969
public function exportAsAttachedFile($name = "")
    {
        $this->_save();
        if (headers_sent($filename, $linenum)) {
            throw new OdfException("headers already sent ($filename at $linenum)");
        }
        
        if ($name == "") {
            $name = md5(uniqid()) . ".odt";
        }
        
        header('Content-type: application/vnd.oasis.opendocument.text');
        header('Content-Disposition: attachment; filename="'.$name.'"');
        readfile($this->tmpfile);
    }
1223235
protected function createFile($fileName, $fileContent)
    {
        $this->inCurrentDir(function($mst) use ($fileName, $fileContent) {
            $mst->_mkdir(dirname($fileName));

            $success = file_put_contents($fileName, $fileContent);

            if (false === $success) {
                throw new ExpectationException("Could not write to file $fileName");
            }
        });
    }
1205740
public function putBlobFromFile($container, $name, $localFileName = '', $type = '')
    {
        $blob = file_get_contents($localFileName);
        if (false === $blob) {
            throw new InternalServerErrorException("Failed to get contents of uploaded file.");
        }

        $this->putBlobData($container, $name, $blob, $type);
    }
185127
function writeFileFromFile($filename, $localFilename, $multicall = false)
    {
        if (!file_exists($localFilename)) {
            throw new InvalidArgumentException('localFilename = ' . print_r($localFilename, true));
        }

        $contents = file_get_contents($localFilename);
        return $this->writeFile($filename, $contents, $multicall);
    }