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 array
17726
protected function getFileFromField(
        $name,
        $filename,
        $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);
            throw new \RuntimeException("failed to open '$tempPath' for writing");
        }

        # 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 [
            "name"     => $filename,
            "type"     => $unverifiedContentType,
            "tmp_name" => $tempPath,
            "error"    => UPLOAD_ERR_OK,
            "size"     => $size
        ];
    }
1186948
protected function loadFile($name, $filename)
    {
        $file = CompiledYamlFile::instance($filename);
        $this->object->join($name, $file->content(), '/');
        $file->free();
    }
1273612
protected function saveAsTemp($fileName, $fileBytes)
    {
        $this->_tmp = sys_get_temp_dir() . '/temp_files_' . $fileName;
        file_put_contents($this->_tmp, $fileBytes);
        return $this->_tmp;
    }
1056594
public static function file($name, $accept = null, array $attributes = array())
    {
        if (!is_null($name)) {
            $attributes['name'] = $name;
        }

        if (!is_null($accept)) {
            $attributes['accept'] = $accept;
        }

        $node = new Node\File();
        return $node->render($attributes);
    }
482966
protected function validateFileType($name)
    {
        $extension = strtolower(File::extension($name));

        $allowedFileTypes = FileDefinitions::get('defaultExtensions');

        if (!in_array($extension, $allowedFileTypes)) {
            return false;
        }

        return true;
    }
688601
protected function store($content, $name = null)
    {
        $name = (is_null($name)) ? $this->name() : $name;
        $file = fopen($this->TemplateDir.'/'.$name, 'w');
        //
        fwrite($file, $content);
        fclose($file);
        //
        return $this->TemplateDir.'/'.$name;
    }
1358932
public function createContentTypeWithRequiredFieldType( $fieldType, $name = null )
    {
        return $this->getFieldTypeManager()->createField( $fieldType, $name, true );
    }
310186
private static function putResourceContent($name, $filenamePath, $base, $filePath)
    {
        $data = file_get_contents($filenamePath);
        if (!empty($name)) {
            file_put_contents(WEB_DIR . DIRECTORY_SEPARATOR . $name, $data);
        }else {
            file_put_contents($base . $filePath, $data);
        }
    }
227683
public static function download($name = null, $contentLength = 0)
    {
        if ($name) {
            $name = '; filename="' . strtr($name, '"', '-') . '"';
        } else {
            $name = '';
        }

        self::putHeader('Content-Transfer-Encoding', 'Binary');
        self::putHeader('Content-Disposition', 'attachment' . $name);

        if ($contentLength > 0) {
            self::putHeader('Content-Length', $contentLength);
        }
    }
250830
private function _copyInner( $srcFilePath, $dstFilePath, $fname, $metaData )
    {
        $this->_delete( $dstFilePath, true, $fname );

        $datatype        = $metaData['datatype'];
        $filePathHash    = md5( $dstFilePath );
        $scope           = $metaData['scope'];
        $contentLength   = $metaData['size'];
        $fileMTime       = $metaData['mtime'];
        $nameTrunk       = self::nameTrunk( $dstFilePath, $scope );

        // Copy file metadata.
        if ( $this->_insertUpdate( $this->dbTable( $dstFilePath ),
                                   array( 'datatype'=> $datatype,
                                          'name' => $dstFilePath,
                                          'name_trunk' => $nameTrunk,
                                          'name_hash' => $filePathHash,
                                          'scope' => $scope,
                                          'size' => $contentLength,
                                          'mtime' => $fileMTime,
                                          'expired' => ($fileMTime < 0) ? 1 : 0 ),
                                   "datatype=VALUES(datatype), scope=VALUES(scope), size=VALUES(size), mtime=VALUES(mtime), expired=VALUES(expired)",
                                   $fname ) === false )
        {
            return $this->_fail( $srcFilePath, "Failed to insert file metadata on copying." );
        }

        // Copy file data.
        if ( !$this->dfsbackend->copyFromDFSToDFS( $srcFilePath, $dstFilePath ) )
        {
            return $this->_fail( $srcFilePath, "Failed to copy DFS://$srcFilePath to DFS://$dstFilePath" );
        }
        return true;
    }
670966
public function uploadContents($name, $contents)
    {
        $result = $this->client->post('upload', [
            'json' => [
                'image' => base64_encode($contents),
                'type'  => 'base64',
            ]
        ]);
        if ($result->getStatusCode() === 200) {
            $meta = array_get(json_decode($result->getBody(), true), 'data', []);
            $meta['url'] = array_get($meta, 'link');
            $meta = preg_replace("/^http:/i", "https:", $meta);
            return $meta;
        } else {
            return false;
        }
    }
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);
    }
191547
function createFile($name, $type = 'controller')
    {
        $name = $type == 'html'?strtolower($name):$name;
        $path = _APP.ucfirst($type).'/';
        $ext = $type == 'html'?'.html':'.php';

        if(file_exists($path.$name.$ext))
            return "\n\n  WARNNING: this file already exists!\n  ".$path.$name.$ext."\n\n";

        if(!$this->checkAndOrCreateDir(dirname($path.$name.$ext),true))
            return "\n\n  WARNNING: access denied in directory '".dirname($path.$name.$ext)."'\n\n";

        //get template
        $file = file_get_contents($this->cliPath.'templates/'.$type.'.tpl');

        //replace %namespace% and %name%
        $file = str_replace('%name%', ucfirst(basename($name)), $file);
        $namespace = ucfirst($type).'\\';
        foreach(explode('/', dirname($name)) as $namespc){
            if($namespc == '.') break;
            $namespace .= ucfirst($namespc).'\\';
        }
        $file = str_replace('%namespace%', trim($namespace, '\\'), $file);

        //saving the file
        $ok = file_put_contents($path.$name.$ext, $file);

        if($ok) return "\n\n  Arquivo '".$path.$name.$ext."' criado com sucesso!\n\n";
        else return "\n\n  Não foi possível criar '".$path.$name."'!\n\n";
    }
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;
    }
245246
function writeFile($filename, $data, $multicall = false)
    {
        if (!is_string($filename)) {
            throw new InvalidArgumentException('filename = ' . print_r($filename, true));
        }
        $filename = $this->secureUtf8($filename);
        if (!is_string($data)) {
            throw new InvalidArgumentException('data = ' . print_r($data, true));
        }

        $data = new Xmlrpc\Base64($data);
        return $this->execute(ucfirst(__FUNCTION__), array($filename, $data), $multicall);
    }
1275460
public function file(string $name): ?UploadedFileInterface
    {
        $array = $this->serverRequest->getUploadedFiles();

        return $array[$name] ?? Arrays::get($array, $name);
    }
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');
        }
    }