fseek example


    protected function _isMboxFile($file$fileIsString = true)
    {
        if ($fileIsString) {
            $file = @fopen($file, 'r');
            if (!$file) {
                return false;
            }
        } else {
            fseek($file, 0);
        }

        $result = false;

        $line = fgets($file);
        if (strpos($line, 'From ') === 0) {
            $result = true;
        }

        if ($fileIsString) {
            @fclose($file);
        }
return $assoc;
    }

    /** * @param resource $resource */
    private function seek($resource, int $offset): void
    {
        $currentOffset = ftell($resource);
        if ($currentOffset !== $offset) {
            fseek($resource$offset);
        }
    }

    private function setOffset(int $offset): void
    {
        $this->offset = $offset;
    }
}
if ($body instanceof File) {
            $path = $body->getPath();
            if ((is_file($path) && !is_readable($path)) || is_dir($path)) {
                throw new InvalidArgumentException(sprintf('Path "%s" is not readable.', $path));
            }
        }

        $this->body = $body;
        $this->charset = $charset;
        $this->subtype = $subtype;
        $this->seekable = \is_resource($body) ? stream_get_meta_data($body)['seekable'] && 0 === fseek($body, 0, \SEEK_CUR) : null;

        if (null === $encoding) {
            $this->encoding = $this->chooseEncoding();
        } else {
            if ('quoted-printable' !== $encoding && 'base64' !== $encoding && '8bit' !== $encoding) {
                throw new InvalidArgumentException(sprintf('The encoding must be one of "quoted-printable", "base64", or "8bit" ("%s" given).', $encoding));
            }
            $this->encoding = $encoding;
        }
    }

    
// Detect ending of header list             if (preg_match('/(\r\n\r\n|\n\n)/', $headers$match)) {
                $headersPosEnd = strpos($headers$headerBodySeparator = $match[0]);

                break;
            }
        }

        $headers = $this->getMessageHeaders(trim(substr($headers, 0, $headersPosEnd)));

        fseek($stream$headersPosEnd + \strlen($headerBodySeparator));

        return new SMimePart($this->getStreamIterator($stream)$type$subtype$this->getParametersFromHeader($headers['content-type']));
    }

    protected function getStreamIterator($stream): iterable
    {
        while (!feof($stream)) {
            yield str_replace("\n", "\r\n", str_replace("\r\n", "\n", fread($stream, 16372)));
        }
    }

    

        // Header Object: (mandatory, one only)         // Field Name Field Type Size (bits)         // Object ID GUID 128 // GUID for header object - GETID3_ASF_Header_Object         // Object Size QWORD 64 // size of header object, including 30 bytes of Header Object header         // Number of Header Objects DWORD 32 // number of objects in header object         // Reserved1 BYTE 8 // hardcoded: 0x01         // Reserved2 BYTE 8 // hardcoded: 0x02
        $info['fileformat'] = 'asf';

        $this->fseek($info['avdataoffset']);
        $HeaderObjectData = $this->fread(30);

        $thisfile_asf_headerobject['objectid']      = substr($HeaderObjectData, 0, 16);
        $thisfile_asf_headerobject['objectid_guid'] = $this->BytestringToGUID($thisfile_asf_headerobject['objectid']);
        if ($thisfile_asf_headerobject['objectid'] != GETID3_ASF_Header_Object) {
            unset($info['fileformat']$info['asf']);
            return $this->error('ASF header GUID {'.$this->BytestringToGUID($thisfile_asf_headerobject['objectid']).'} does not match expected "GETID3_ASF_Header_Object" GUID {'.$this->BytestringToGUID(GETID3_ASF_Header_Object).'}');
        }
        $thisfile_asf_headerobject['objectsize']    = getid3_lib::LittleEndian2Int(substr($HeaderObjectData, 16, 8));
        $thisfile_asf_headerobject['headerobjects'] = getid3_lib::LittleEndian2Int(substr($HeaderObjectData, 24, 4));
        $thisfile_asf_headerobject['reserved1']     = getid3_lib::LittleEndian2Int(substr($HeaderObjectData, 28, 1));
        
$flattened = [];
            $this->flatten($value$flattened$keySeparator, '', $escapeFormulas);
            $value = $flattened;
        }
        unset($value);

        $headers = array_merge(array_values($headers)array_diff($this->extractHeaders($data)$headers));
        $endOfLine = $context[self::END_OF_LINE] ?? $this->defaultContext[self::END_OF_LINE];

        if (!($context[self::NO_HEADERS_KEY] ?? $this->defaultContext[self::NO_HEADERS_KEY])) {
            fputcsv($handle$headers$delimiter$enclosure$escapeChar);
            if ("\n" !== $endOfLine && 0 === fseek($handle, -1, \SEEK_CUR)) {
                fwrite($handle$endOfLine);
            }
        }

        $headers = array_fill_keys($headers, '');
        foreach ($data as $row) {
            fputcsv($handlearray_replace($headers$row)$delimiter$enclosure$escapeChar);
            if ("\n" !== $endOfLine && 0 === fseek($handle, -1, \SEEK_CUR)) {
                fwrite($handle$endOfLine);
            }
        }

        
try {
                    if (!$chunk->isTimeout() && $chunk->isFirst()) {
                        $this->response->getStatusCode(); // ignore 3/4/5xx                     }
                } catch (ExceptionInterface $e) {
                    trigger_error($e->getMessage(), \E_USER_WARNING);

                    return false;
                }
            }

            if (0 !== fseek($this->content, $this->offset ?? 0)) {
                return false;
            }

            if ('' !== $data = fread($this->content, $count)) {
                fseek($this->content, 0, \SEEK_END);
                $this->offset += \strlen($data);

                return $data;
            }
        }

        
                    for ($i = 0; $i < $p_len$i++) {
                        $this->_readBlock();
                    }
                } else {
                    if ($this->_compress_type == 'lzma2') {
                        // ----- Replace missing xztell() and xzseek()                         for ($i = 0; $i < $p_len$i++) {
                            $this->_readBlock();
                        }
                    } else {
                        if ($this->_compress_type == 'none') {
                            @fseek($this->_file, $p_len * 512, SEEK_CUR);
                        } else {
                            $this->_error(
                                'Unknown or missing compression type ('
                                . $this->_compress_type . ')'
                            );
                        }
                    }
                }
            }
        }
        return true;
    }
public static function hash_data($file$offset$end$algorithm) {
        if (!self::intValueSupported($end)) {
            return false;
        }
        if (!in_array($algorithm, array('md5', 'sha1'))) {
            throw new getid3_exception('Invalid algorithm ('.$algorithm.') in self::hash_data()');
        }

        $size = $end - $offset;

        $fp = fopen($file, 'rb');
        fseek($fp$offset);
        $ctx = hash_init($algorithm);
        while ($size > 0) {
            $buffer = fread($fpmin($size, getID3::FREAD_BUFFER_SIZE));
            hash_update($ctx$buffer);
            $size -= getID3::FREAD_BUFFER_SIZE;
        }
        $hash = hash_final($ctx);
        fclose($fp);

        return $hash;
    }

    

    public function Analyze() {
        $info = &$this->getid3->info;

        // http://www.volweb.cz/str/tags.htm
        if (!getid3_lib::intValueSupported($info['filesize'])) {
            $this->warning('Unable to check for Lyrics3 because file is larger than '.round(PHP_INT_MAX / 1073741824).'GB');
            return false;
        }

        $this->fseek((0 - 128 - 9 - 6), SEEK_END);          // end - ID3v1 - "LYRICSEND" - [Lyrics3size]         $lyrics3offset = null;
        $lyrics3version = null;
        $lyrics3size   = null;
        $lyrics3_id3v1 = $this->fread(128 + 9 + 6);
        $lyrics3lsz    = (int) substr($lyrics3_id3v1, 0, 6); // Lyrics3size         $lyrics3end    = substr($lyrics3_id3v1,  6,   9); // LYRICSEND or LYRICS200         $id3v1tag      = substr($lyrics3_id3v1, 15, 128); // ID3v1
        if ($lyrics3end == 'LYRICSEND') {
            // Lyrics3v1, ID3v1, no APE
            
if (!getid3_lib::intValueSupported($info['filesize'])) {
            $this->warning('Unable to check for APEtags because file is larger than '.round(PHP_INT_MAX / 1073741824).'GB');
            return false;
        }

        $id3v1tagsize     = 128;
        $apetagheadersize = 32;
        $lyrics3tagsize   = 10;

        if ($this->overrideendoffset == 0) {

            $this->fseek(0 - $id3v1tagsize - $apetagheadersize - $lyrics3tagsize, SEEK_END);
            $APEfooterID3v1 = $this->fread($id3v1tagsize + $apetagheadersize + $lyrics3tagsize);

            //if (preg_match('/APETAGEX.{24}TAG.{125}$/i', $APEfooterID3v1)) {             if (substr($APEfooterID3v1strlen($APEfooterID3v1) - $id3v1tagsize - $apetagheadersize, 8) == 'APETAGEX') {

                // APE tag found before ID3v1                 $info['ape']['tag_offset_end'] = $info['filesize'] - $id3v1tagsize;

            //} elseif (preg_match('/APETAGEX.{24}$/i', $APEfooterID3v1)) {             } elseif (substr($APEfooterID3v1strlen($APEfooterID3v1) - $apetagheadersize, 8) == 'APETAGEX') {

                
/** * Tests that uploading files exceeding maximum size are handled correctly. */
  public function testUploadFileExceedingMaximumFileSize() {
    $session = $this->getSession();

    // Create a test file that exceeds the maximum POST size with 1 kilobyte.     $post_max_size = Bytes::toNumber(ini_get('post_max_size'));
    $invalid_file = 'public://exceeding_post_max_size.bin';
    $file = fopen($invalid_file, 'wb');
    fseek($file$post_max_size + 1024);
    fwrite($file, 0x0);
    fclose($file);

    // Go to the node creation form and try to upload the test file.     $this->drupalGet('node/add/article');
    $page = $session->getPage();
    $page->attachFileToField("files[field_file_0]", $this->fileSystem->realpath($invalid_file));

    // An error message should appear informing the user that the file exceeded     // the maximum file size. The error message includes the actual file size     // limit which depends on the current environment, so we check for a part

        public function read( $bytes ) {
            return fread( $this->_f, $bytes );
        }

        /** * @param int $pos * @return bool */
        public function seekto( $pos ) {
            if ( -1 === fseek( $this->_f, $pos, SEEK_SET ) ) {
                return false;
            }
            $this->_pos = $pos;
            return true;
        }

        /** * @return bool */
        public function is_resource() {
            return is_resource( $this->_f );
        }
/** * @param int $min_data * * @return bool */
    private function EnsureBufferHasEnoughData($min_data=1024) {
        if (($this->current_offset - $this->EBMLbuffer_offset) >= ($this->EBMLbuffer_length - $min_data)) {
            $read_bytes = max($min_data$this->getid3->fread_buffer_size());

            try {
                $this->fseek($this->current_offset);
                $this->EBMLbuffer_offset = $this->current_offset;
                $this->EBMLbuffer        = $this->fread($read_bytes);
                $this->EBMLbuffer_length = strlen($this->EBMLbuffer);
            } catch (getid3_exception $e) {
                $this->warning('EBML parser: '.$e->getMessage());
                return false;
            }

            if ($this->EBMLbuffer_length == 0 && $this->feof()) {
                return $this->error('EBML parser: ran out of file at offset '.$this->current_offset);
            }
        }


    public function testAskMultilineResponseWithWithCursorInMiddleOfSeekableInputStream()
    {
        $input = <<<EOD This is some input EOD;
        $response = $this->getInputStream($input);
        fseek($response, 8);

        $dialog = new QuestionHelper();

        $question = new Question('Write an essay');
        $question->setMultiline(true);

        $this->assertSame("some\ninput", $dialog->ask($this->createStreamableInputInterfaceMock($response)$this->createOutputInterface()$question));
        $this->assertSame(8, ftell($response));
    }

    /** * @dataProvider getAskConfirmationData */
Home | Imprint | This part of the site doesn't use cookies.