<?php
require_once(searchinc('base.inc'));

/* This file defines classes that enable the reading and manipulation of machine defined data types
 *  and data structures embeded in files
 */

function normalizeUuid(string $uuidstring)
{
    $normal = false;
    if (strlen($uuidstring) == 16)
    {
        // this appears to be a binary string - leave it alone
        $normal = $uuidstring;
    }
    elseif ((strlen($uuidstring)==32) &&                         // contains exactly 16 hex digits and no prefix
            (strspn($uuidstring, '0123456789abcdefABCDEF')==strlen($uuidstring)))  // and consists entirely of hex characters
    {
        // convert to a binary string
        $normal = '';
        for($i=0; $i<strlen($uuidstring); $i+=2)
        {
            $normal .= chr(hexdec(substr($uuidstring, $i, 2)));
        }
    }
    elseif ((strlen($uuidstring)==34) &&                         // contains exactly 16 hex digits plus a 2 charcater prefix
            (strcasecmp(substr($uuidstring, 0, 2), '0x')==0) &&   // prefix indicates a hex digit string
            (strspn($uuidstring, '0123456789abcdefABCDEF', 2)==(strlen($uuidstring)-2)))  // and consists entirely of hex characters
    {
        // convert to a binary string
        $normal = '';
        for($i=2; $i<strlen($uuidstring); $i+=2)
        {
            $normal .= chr(hexdec(substr($uuidstring, $i, 2)));
        }
    }
    elseif ((strlen($uuidstring)==36) &&                         // contains exactly 16 hex digits plus 4 seperator characters
            (strspn($uuidstring, '0123456789abcdefABCDEF-')==strlen($uuidstring)))  // and consists entirely of hex characters or hyphen
    {
        // remove hyphens
        $uuidstring = str_replace('-', '', $uuidstring);
        // convert to a binary string
        $normal='';
        for($i=0; $i<strlen($uuidstring); $i+=2)
        {
            $normal .= chr(hexdec(substr($uuidstring, $i, 2)));
        }
    }
    return $normal;
}


define('MDU_BIG_ENDIAN', 1);
define('MDU_LITTLE_ENDIAN', 0);

define('MDU_SIGNED', 0);
define('MDU_UNSIGNED', 1);

define('MDU_AUTOFILL_BUFFER', 0);
define('MDU_NOFILL_BUFFER', 1);

define('MDU_DEFAULT_READ_BUFFER_SIZE', 4096);
define('MDU_MAX_READ_BUFFER_SIZE', 256*1024);

class MDU_buffer EXTENDS base
{
    protected $stream_res = null;
    protected $stream_obj = null;
    protected $stream_str = null;
    
    protected $stream_offset = 0;       // file offset of start of buffer data
    protected $curr_data_offset = 0;    // current client offset within buffer data
    protected $seekable = false;        // whether stream implementatio supposts seeks
    protected $eof = true;              // client is at end-of-file
    
    protected $next_read_offset = 0;    // file offset of next steram read (end of buffer dtata + 1)
    
    protected $buffer_data = '';
    protected $buffer_len = 0;

    protected $readable = false;
    protected $streamid;
    
    public function __construct($stream, $err_mode=TRIGGER_ON_ERROR)
    {
        $proc = __CLASS__.'::'.__FUNCTION__.': ';
        $this->dbgecho($proc.'() entered', DEBUG_PROC_TRACE);
        $this->clear_error();
        
        // validate as a stream type 
        if (is_resource($stream) && (get_resource_type($stream) === 'stream'))
        {
            $this->stream_res = $stream;
            $str_info = stream_get_meta_data($stream);
            $this->readable = (stripos($str_info['mode'], 'r') !== false) ||
                              (stripos($str_info['mode'], '+') !== false);
            $this->seekable = $str_info['seekable'];
            $this->stream_offset = ftell($stream);
            $this->next_read_offset = $this->stream_offset;
 
            $this->streamid = $str_info['uri'];
            $this->eof = feof($stream);
        }
        elseif (is_a($stream, 'SplFileInfo'))
        {
            $this->stream_obj = $stream;
            $this->readable = $stream->isReadable();
            $this->seekable = true;
            $this->stream_offset = $stream->ftell();
            $this->next_read_offset = $this->stream_offset;
            $this->streamid = $stream->getPathname();
            $this->eof = $stream->eof();
        }
        elseif(is_string($stream))
        {
            $this->stream_str = $stream;
            $this->readable = true;
            $this->seekable = true;
            $this->stream_offset = 0;
            $this->next_read_offset = $this->stream_offset;
            $this->streamid = 'string';
            $this->eof = false;
        }
        else
        {
            $this->set_error('Stream parameter is of wrong type:'.get_type($stream).
                             (is_resource($stream)?('('.get_resource_type($stream).')'):''), __FILE__,__LINE__);
        }
        if ($this->is_ok() && !$this->readable)
        {
            $this->set_error('Stream parameter is not readable: '.$streamid, __FILE__,__LINE__);
        }
            
        
        $this->dbgecho($proc.'('
                .(isset($this->stream_res)?'resource':(isset($this->stream_obj)?'object':'string')).', '
                .($this->seekable?'seekable':'not seekable').') leaving', DEBUG_PROC_TRACE);
        if (!$this->is_ok())
        {
            $this->trigger_error();
        }
    }
    
    public function load_buffer (int $size=MDU_DEFAULT_READ_BUFFER_SIZE)
    {
        $proc = __CLASS__.'::'.__FUNCTION__.': ';
        $this->dbgecho($proc.'('.$size.') entered', DEBUG_PROC_TRACE);
        
       
        if ($this->curr_data_offset < $this->buffer_len)  // buffer isn't empty yet
        {
            $remainder = substr($this->buffer_data, $this->curr_data_offset);
        }
        else
        {
            $remainder = '';
        }
        // move stream offset pointer to the beginning of our new buffer data
        $this->stream_offset += $this->curr_data_offset;
        // reset current data offset to start of buffer
        $this->curr_data_offset = 0;

        if (isset($this->stream_res))
        {
            $this->buffer_data = fread($this->stream_res, $size);
            $this->eof = feof($this->stream_res);
        }
        elseif (isset($this->stream_obj))
        {
            $this->buffer_data = $this->stream_obj->fread($size);
            $this->eof = $this->stream_obj->eof();
        }
        else    // isset($this->stream_str)
        {
            if ($this->next_read_offset>=strlen($this->stream_str))
            {
                $this->buffer_data = false;
                $this->eof = true;
            }
            else
            {
                $this->buffer_data = substr($this->stream_str, $this->next_read_offset, $size);
                $this->eof = (($this->next_read_offset+$size)>=strlen($this->stream_str));
            }
        }
        $this->dbgecho($proc.'read result: '.(($this->buffer_data === false)?'failed':(strlen($this->buffer_data).'bytes')), DEBUG_DETAIL_TRACE);
        $this->dbgecho($proc.'end-of-file: '.($this->eof?'true':'false'), DEBUG_DETAIL_TRACE);
 
        if ($this->buffer_data !== false)
        {
            $this->buffer_data = $remainder.$this->buffer_data;
            $this->buffer_len = strlen($this->buffer_data);
            $this->next_read_offset = $this->stream_offset + $this->buffer_len;
            $this->dbgecho($proc.'next_read_offset = '.$this->next_read_offset.
                             ' should equal file pointer offset = '.$this->file_offset().' : '.
                             '('.sprintf('0x%x ==? 0x%x', $this->next_read_offset, $this->file_offset()).')',
                        DEBUG_DETAIL_TRACE);
        }
        elseif ($this->eof)
        {
            $this->buffer_data = '';
            $this->buffer_len = 0;
        }
    }
    
    public function current_offset()
    {
        $proc = __CLASS__.'::'.__FUNCTION__.': ';
        $this->dbgecho($proc.'stream offset = '.$this->stream_offset.
                             ' plus current data offset = '.$this->curr_data_offset.' = '.
                             ($this->stream_offset+$this->curr_data_offset).
                             ' (0x'.sprintf('%x', ($this->stream_offset+$this->curr_data_offset)).')',
                        DEBUG_DETAIL_TRACE);
        return ($this->stream_offset+$this->curr_data_offset);
    }
    
     public function file_offset()
    {
        if (isset($this->stream_res))
        {
            $ret = ftell($this->stream_res);
        }
        elseif (isset($this->stream_obj))
        {
            $ret = $this->stream_obj->ftell();
        }
        else   // isset($this->stream_str)
        {
            $ret = $this->next_read_offset;
        }
        return ($ret);
    }
    
   public function eof()
    {
        return ($this->eof && ($this->curr_data_offset == $this->buffer_len));
    }
    
    public function leftinbuffer()
    {
        return $this->buffer_len-$this->curr_data_offset;
    }
    
    public function slurp($bytecount=1, $fill=MDU_AUTOFILL_BUFFER)
    {
        $proc = __CLASS__.'::'.__FUNCTION__.': ';
        $this->dbgecho($proc.'before '.__FUNCTION__.' '.((string)$bytecount).': stream offset = '.$this->stream_offset.' plus '.
                             'curr_data_offset='.$this->curr_data_offset.' = '.
                             ($this->stream_offset+$this->curr_data_offset).
                             ' (0x'.sprintf('%x', ($this->stream_offset+$this->curr_data_offset)).')',
                        DEBUG_DETAIL_TRACE);
        
        $this->dbgecho($proc.'before '.__FUNCTION__.' '.((string)$bytecount).': next_read_offset = '.$this->next_read_offset.' minus '.
                             'leftinbuffer()='.$this->leftinbuffer().' = '.
                             ($this->next_read_offset-$this->leftinbuffer()).
                             ' (0x'.sprintf('%x', ($this->next_read_offset-$this->leftinbuffer())).')',
                        DEBUG_DETAIL_TRACE);
        
        while ($this->leftinbuffer()<$bytecount)
        {
            if ($this->eof || $fill===MDU_NOFILL_BUFFER) { return false; }
            $this->load_buffer();
        }
        $sip = substr($this->buffer_data, $this->curr_data_offset, $bytecount);
        $this->curr_data_offset += strlen($sip);
        
        $this->dbgecho($proc.'after '.__FUNCTION__.' '.((string)$bytecount).': stream offset='.$this->stream_offset.' plus '.
                             'curr_data_offset='.$this->curr_data_offset.' = '.
                             ($this->stream_offset+$this->curr_data_offset).
                             ' (0x'.sprintf('%x', ($this->stream_offset+$this->curr_data_offset)).')',
                        DEBUG_DETAIL_TRACE);
        
        return $sip;
    }

    public function peek($bytecount=1, $fill=MDU_AUTOFILL_BUFFER)
    {
        $proc = __CLASS__.'::'.__FUNCTION__.': ';
        $this->dbgecho($proc.'before '.__FUNCTION__.' '.$bytecount.': stream offset = '.$this->stream_offset.' plus '.
                             'curr_data_offset='.$this->curr_data_offset.' = '.
                             ($this->stream_offset+$this->curr_data_offset).
                             ' (0x'.sprintf('%x', ($this->stream_offset+$this->curr_data_offset)).')',
                        DEBUG_DETAIL_TRACE);
        
        if ($bytecount > $this->leftinbuffer())
        {
            $needmore = $bytecount-$this->leftinbuffer();
            if ($fill == MDU_AUTOFILL_BUFFER)
            {
                $this->load_buffer($needmore);
            }
        }
        if ($bytecount <= $this->leftinbuffer())
        {
            $res = substr($this->buffer_data, $this->curr_data_offset, $bytecount);
        }
        else
        {
            $res = false;
        }
        
        $this->dbgecho($proc.'after '.__FUNCTION__.' '.$bytecount.': stream offset = '.$this->stream_offset.' plus '.
                             'curr_data_offset='.$this->curr_data_offset.' = '.
                             ($this->stream_offset+$this->curr_data_offset).
                             ' (0x'.sprintf('%x', ($this->stream_offset+$this->curr_data_offset)).')',
                        DEBUG_DETAIL_TRACE);
       
        return $res;
    }
    
    public function skip($bytecount=1)
    {
        $proc = __CLASS__.'::'.__FUNCTION__.': ';
        $this->dbgecho($proc.'before '.__FUNCTION__.' '.$bytecount.': stream offset = '.$this->stream_offset.' plus '.
                             'curr_data_offset='.$this->curr_data_offset.' = '.
                             ($this->stream_offset+$this->curr_data_offset).
                             ' (0x'.sprintf('%x', ($this->stream_offset+$this->curr_data_offset)).')',
                        DEBUG_DETAIL_TRACE);
        
        $res = true;
        if ((($bytecount>=0) && ($bytecount<$this->leftinbuffer())) ||
            (($bytecount<0) && (($this->curr_data_offset+$bytecount)>=0)))  // skip fits entirely within our current buffer
        {
            $this->curr_data_offset+=$bytecount;    // just increment (or decrement) the bytecount
        }
        else
        {
            $expected_stream_offset = $this->stream_offset + $this->curr_data_offset + $bytecount;
            if ($this->seekable)
            {
                if (isset($this->stream_res))
                {
                    fseek($this->stream_res, $bytecount-$this->leftinbuffer(), SEEK_CUR);
                    $actual_stream_offset = ftell($this->stream_res);
                }
                elseif (isset($this->stream_obj))
                {
                    $this->stream_obj->fseek($bytecount-$this->leftinbuffer(), SEEK_CUR);
                    $actual_stream_offset = $this->stream_obj->ftell();
                }
                else   // isset($this->stream_str)
                {
                    if ((($this->next_read_offset-$this->leftinbuffer())+$bytecount)>=strlen($this->stream_str))
                    {
                        $actual_stream_offset = strlen($this->stream_str);
                    }
                    else
                    {
                        $actual_stream_offset = ($this->next_read_offset-$this->leftinbuffer())+$bytecount;
                    }
                }
                if (($actual_stream_offset != $expected_stream_offset))  // reached end of file first
                {
                    $res = false;
                }
                else
                {
                    $this->stream_offset = $next_read_offset = $actual_stream_offset;
                    $this->curr_data_offset = $this->buffer_len = 0;
                    $this->load_buffer();
                }
            }
            else
            {
                if ($bytecount<0)
                {
                    $res = false;
                    $this->set_error('Unsuported seek backwards of '.($bytecount*-1).' bytes attempetd on unseekable file stream.',
                                     __FILE__, __LINE__);
                }
                else
                {
                    $read = 0;
                    while ($read < $bytecount)
                    {
                        $read_size = MIN(MDU_MAX_READ_BUFFER_SIZE, $bytecount);
                        if (isset($this->stream_res))
                        {
                            $this->buffer_data = fread($this->stream_res, $read_size);
                            $this->eof = feof($this->stream_res);
                        }
                        else
                        {
                            $this->buffer_data = $this->stream_obj->fread($read_size);
                            $this->eof = $this->stream_obj->eof();
                        }
                        if ($this->buffer_data !== false)
                        {
                            $bytecount -= strlen($this->buffer_data);
                        }
                        if ($this->eof || ($this->buffer_data === false))
                        {
                            break;
                        }
                    }
                    if ($this->buffer_data === FALSE)
                    {
                        $res = false;
                    }
                    elseif (!$this->eof)
                    {
                        $this->stream_offset = $next_read_offset = $actual_stream_offset;
                        $this->curr_data_offset = $this->buffer_len = 0;
                        $this->load_buffer();
                    }
                }
            }
        }
        $this->dbgecho($proc.'after '.__FUNCTION__.' '.$bytecount.': stream offset = '.$this->stream_offset.' plus '.
                             'curr_data_offset='.$this->curr_data_offset.' = '.
                             ($this->stream_offset+$this->curr_data_offset).
                             ' (0x'.sprintf('%x', ($this->stream_offset+$this->curr_data_offset)).')',
                        DEBUG_DETAIL_TRACE);
        
        return $res;
    }
    
    public function skip_to($new_stream_offset)
    {
        $res = false;
        if ($new_stream_offset != ($this->stream_offset + $this->curr_data_offset))
        {
            $res = $this->skip($new_stream_offset-($this->stream_offset + $this->curr_data_offset));
        }
        return $res;
    }
}

class MDU_parsable EXTENDS MDU_buffer
{
    protected $endian;
    
    const highbit = array(1 => 0xF0,
                          2 => 0xF000,
                          3 => 0xF00000,
                          4 => 0xF0000000,
                          5 => 0xF000000000,
                          6 => 0xF00000000000,
                          7 => 0xF0000000000000,
                          8 => 0xF000000000000000);
    const allbits = array(1 => 0xFF,
                          2 => 0xFFFF,
                          3 => 0xFFFFFF,
                          4 => 0xFFFFFFFF,
                          5 => 0xFFFFFFFFFF,
                          6 => 0xFFFFFFFFFFFF,
                          7 => 0xFFFFFFFFFFFFFF,
                          8 => 0xFFFFFFFFFFFFFFFF);

    public function __construct($stream, $default_endian=MDU_BIG_ENDIAN, $err_mode=TRIGGER_ON_ERROR)
    {
        $this->endian = $default_endian;
        parent::__construct($stream, $err_mode);
    }
    
    public static function str_to_int($intdata, $signed=MDU_UNSIGNED, $endian=null)
    {
        $byte_len = strlen($intdata);
        if ($endian === MDU_LITTLE_ENDIAN) { $intdata = strrev($intdata); }  // swap ends
        // compile into an unsigned integer
        $int = 0;
        foreach(str_split($intdata) as $byte)
        {
            $int = ($int*256)+ord($byte);
        }
        // correct sign
        if ($signed === MDU_SIGNED)
        {
            // if high bit is set, two's complement to get unsigned value
            if (($int & self::highbit[$byte_len]) == self::highbit[$byte_len])
            {
                $int = (((~ $int) & self::allbits[$byte_len])+1);
            }
        }
        
        return $int;
    }

    public function getinteger($byte_len, $signed=MDU_UNSIGNED, $endian=null)
    {
        $intdata = $this->slurp($byte_len);
        if ($intdata === false)
        {
            $int = null;
        }
        else
        {
        if (!isset($endian)) { $endian = $this->endian; }
            $int = self::str_to_int($intdata, $signed, $endian);
        }
        return $int;
    }
    
    public function getstring($len)
    {
        return $this->slurp($len);
    }
    
    public function endianness($new=null)
    {
        if (isset($new))
        {
            $this->endian = $new;
        }
        return $this->endian;
    }
}
 ?>