<?php
/***********************************************
* File      :   wbxml.php
* Descr     :   WBXML mapping file
*
* Original by Zarafa Deutschland GmbH released under GPLv2.
* Modifications by Atmail published under GPLv2
* Consult LICENSE file for details
************************************************/
include_once('debug.php');

define('WBXML_DEBUG', false);

define('WBXML_SWITCH_PAGE',     0x00);
define('WBXML_END',             0x01);
define('WBXML_ENTITY',          0x02);
define('WBXML_STR_I',           0x03);
define('WBXML_LITERAL',         0x04);
define('WBXML_EXT_I_0',         0x40);
define('WBXML_EXT_I_1',         0x41);
define('WBXML_EXT_I_2',         0x42);
define('WBXML_PI',              0x43);
define('WBXML_LITERAL_C',       0x44);
define('WBXML_EXT_T_0',         0x80);
define('WBXML_EXT_T_1',         0x81);
define('WBXML_EXT_T_2',         0x82);
define('WBXML_STR_T',           0x83);
define('WBXML_LITERAL_A',       0x84);
define('WBXML_EXT_0',           0xC0);
define('WBXML_EXT_1',           0xC1);
define('WBXML_EXT_2',           0xC2);
define('WBXML_OPAQUE',          0xC3);
define('WBXML_LITERAL_AC',      0xC4);

define('EN_TYPE',               1);
define('EN_TAG',                2);
define('EN_CONTENT',            3);
define('EN_FLAGS',              4);
define('EN_ATTRIBUTES',         5);

define('EN_TYPE_STARTTAG',      1);
define('EN_TYPE_ENDTAG',        2);
define('EN_TYPE_CONTENT',       3);

define('EN_FLAGS_CONTENT',      1);
define('EN_FLAGS_ATTRIBUTES',   2);

function printtag($el)
{
    $typemap = array(false => '', EN_TYPE_STARTTAG => "EN_TYPE_STARTTAG", EN_TYPE_ENDTAG => 'EN_TYPE_ENDTAG', EN_TYPE_CONTENT => 'EN_TYPE_CONTENT');
    $flagmap = array(false => '', EN_FLAGS_CONTENT => "EN_FLAGS_CONTENT", EN_FLAGS_ATTRIBUTES => 'EN_FLAGS_ATTRIBUTES');

    $tagtype = array_key_exists(EN_TYPE, $el) ? $el[EN_TYPE] : false;
    $tag = array_key_exists(EN_TAG, $el) ? $el[EN_TAG] : false;
    $tagflags = array_key_exists(EN_FLAGS, $el) ? $el[EN_FLAGS] : false;
    $tagcontent = array_key_exists(EN_CONTENT, $el) ? $el[EN_CONTENT] : false;
    $tagattributes = array_key_exists(EN_ATTRIBUTES, $el) ? $el[EN_ATTRIBUTES] : false;

    return ($tag . " " . $typemap[$tagtype] . "/" . $flagmap[$tagflags] . "=" . $tagcontent . " (" . $tagattributes . ")");
}

class WBXMLDecoder {
    var $dtd;
    var $in;

    var $version;
    var $publicid;
    var $publicstringid;
    var $charsetid;
    var $stringtable;

    var $tagcp = 0;
    var $attrcp = 0;

    var $ungetbuffer = array();

    var $logStack = array();

    function WBXMLDecoder($input, $dtd) {
        $this->in = $input;
        $this->dtd = $dtd;

        $this->version = $this->getByte();
        $this->publicid = $this->getMBUInt();
        if($this->publicid == 0) {
            $this->publicstringid = $this->getMBUInt();
        }

        $this->charsetid = $this->getMBUInt();
        $this->stringtable = $this->getStringTable();

    }

    function consumeElement($tag)
    {
        $elements = array();
        $level = 1;

        while(1) {
            $element = $this->getToken();

            if($tag == "GetChanges")
            {
                //debugLog(print_r($element, true));
            }
            if(is_array($element))
            {
                if($tag == "GetChanges")
                {
                    //debugLog('ARRAY');
                }
                if(!array_key_exists(EN_TAG, $element)) $element[EN_TAG] = '';
            }

            array_push($elements, $element);

            if($element == false)
            {
                array_pop($elements);
                break;
            }

            if($element[EN_TYPE] == EN_TYPE_STARTTAG)
            {
                $level++;
            }
            else if($element[EN_TYPE] == EN_TYPE_ENDTAG)
            {
                $level--;
            }

            if($element[EN_TYPE] == EN_TYPE_STARTTAG && array_key_exists(EN_FLAGS, $element) && $element[EN_FLAGS] != EN_FLAGS_CONTENT)
                $level--;

            if($tag == "GetChanges")
            {
                //debugLog($level);
            }

            if($level == 0)
            {
                if($tag == "GetChanges")
                {
                    //debugLog("BREAK");
                }
                break;
            }

            if($element[EN_TYPE] == EN_TYPE_STARTTAG && $element[EN_TAG] == $tag) {
                array_pop($elements);
                break;
            }
        }

        $content = false;

        if($element[EN_TYPE] == EN_TYPE_STARTTAG && $element[EN_TAG] == $tag)
        {

            if($element[EN_FLAGS] == EN_TYPE_STARTTAG)
            {
                $content = $this->getElementContent();
                if(!$this->getElementEndTag())
                    return false;
            }
            else
                $content = true;
        }

        $elements = array_reverse($elements);
        foreach($elements as $undoElement)
        {
            if(!is_null($undoElement))
            {
                $this->ungetElement($undoElement);
            }
        }

        return $content;
    }

    // Returns either start, content or end, and auto-concatenates successive content
    function getElement()
    {
        $element = $this->getToken();

        switch($element[EN_TYPE]) {
            case EN_TYPE_STARTTAG:
                return $element;
            case EN_TYPE_ENDTAG:
                return $element;
            case EN_TYPE_CONTENT:
                while(1) {
                    $next = $this->getToken();
                    if($next == false)
                        return false;
                    else if($next[EN_TYPE] == EN_CONTENT) {
                        $element[EN_CONTENT] .= $next[EN_CONTENT];
                    } else {
                        $this->ungetElement($next);
                        break;
                    }
                }
                return $element;
        }

        return false;
    }

    function peek()
    {
        $element = $this->getElement();

        $this->ungetElement($element);

        return $element;
    }

    function getElementStartTag($tag, $consume = false)
    {
        $elements = array();
        $level = 1;
        while(1) {
            $element = $this->getToken();

            if(is_array($element))
            {
                if(!array_key_exists(EN_TAG, $element)) $element[EN_TAG] = '';
            }

            array_push($elements, $element);

            if($element == false)
            {
                array_pop($elements);
                break;
            }

            if($element[EN_TYPE] == EN_TYPE_STARTTAG)
            {
                $level++;
            }
            else if($element[EN_TYPE] == EN_TYPE_ENDTAG)
            {
                $level--;
            }
            if($element[EN_TYPE] == EN_TYPE_STARTTAG && array_key_exists(EN_FLAGS, $element) && $element[EN_FLAGS] != EN_FLAGS_CONTENT)
                $level--;


            if($level == 0)
            {
                break;
            }

            if($element[EN_TYPE] == EN_TYPE_STARTTAG && $element[EN_TAG] == $tag) {

                array_pop($elements);
                break;
            }
        }

        $elements = array_reverse($elements);
        foreach($elements as $undoElement)
        {
            if(!is_null($undoElement))
            {
                $this->ungetElement($undoElement);
            }
        }

        if($element[EN_TYPE] == EN_TYPE_STARTTAG && $element[EN_TAG] == $tag)
        {
            return $element;
        }


        return false;
    }

    function getElementEndTag()
    {
        $elements = array();
        while(1) {
            $element = $elements[] = $this->getToken();
            if($element == false)
            {
                foreach($elements as $undoElement)
                {
                    if(is_array($undoElement) && array_key_exists(EN_TYPE, $undoElement) && !$undoElement[EN_TYPE] == EN_TYPE_ENDTAG) {
                        $this->ungetElement($undoElement);
                    }
                }
                break;
            }
            else if($element[EN_TYPE] == EN_TYPE_ENDTAG) {
                break;
            }
        }

        if($element[EN_TYPE] == EN_TYPE_ENDTAG)
        {
            return $element;
        }
        else {
            //debugLog("Unmatched end tag:");
            //debugLog(print_r($element,true));
            $this->ungetElement($element);
        }

        return false;
    }

    function getElementContent()
    {
        $element = $this->getToken();

        if($element[EN_TYPE] == EN_TYPE_CONTENT) {
            return $element[EN_CONTENT];
        } else {
            //debugLog("Unmatched content:");
            //debugLog(print_r($element, true));
            $this->ungetElement($element);
        }

        return false;
    }

    // ---------------------- Private functions ------------------------

    function getToken() {
        // See if there's something in the ungetBuffer
        if(count($this->ungetbuffer) > 0 ) {
            $ungetbuffer = array_reverse($this->ungetbuffer);
            $element = array_pop($this->ungetbuffer);
            return $element;
        }

        $el = $this->_getToken();

        $this->logToken($el);

        return $el;
    }

    function logToken($el, $popped = false) {
        if(!WBXML_DEBUG)
            return;
        $spaces = str_repeat(" ", count($this->logStack));

        switch($el[EN_TYPE]) {
            case EN_TYPE_STARTTAG:
                if($el[EN_FLAGS] & EN_FLAGS_CONTENT)
                {
                    //debugLog($popped . "I " . $spaces . " <". $el[EN_TAG] . ">");
                    array_push($this->logStack, $el[EN_TAG]);
                }
                else
                {
                    //debugLog($popped . "I " . $spaces . " <" . $el[EN_TAG] . "/>");
                }

                break;
            case EN_TYPE_ENDTAG:
                $tag = array_pop($this->logStack);
                //debugLog($popped . "I " . $spaces . "</" . $tag . ">");
                break;
            case EN_TYPE_CONTENT:
                //debugLog($popped . "I " . $spaces . " " . $el[EN_CONTENT]);
                break;
        }
    }

    // Returns either a start tag, content or end tag
    function _getToken() {

        // Get the data from the input stream
        $element = array();

        while(1) {
            $byte = $this->getByte();

            if(!isset($byte))
                break;

            switch($byte) {
                case WBXML_SWITCH_PAGE:
                    $this->tagcp = $this->getByte();
                    continue;

                case WBXML_END:
                    $element[EN_TYPE] = EN_TYPE_ENDTAG;
                    return $element;

                case WBXML_ENTITY:
                    $entity = $this->getMBUInt();
                    $element[EN_TYPE] = EN_TYPE_CONTENT;
                    $element[EN_CONTENT] = $this->entityToCharset($entity);
                    return $element;

                case WBXML_STR_I:
                    $element[EN_TYPE] = EN_TYPE_CONTENT;
                    $element[EN_CONTENT] = $this->getTermStr();
                    return $element;

                case WBXML_LITERAL:
                    $element[EN_TYPE] = EN_TYPE_STARTTAG;
                    $element[EN_TAG] = $this->getStringTableEntry($this->getMBUInt());
                    $element[EN_FLAGS] = 0;
                    return $element;

                case WBXML_EXT_I_0:
                case WBXML_EXT_I_1:
                case WBXML_EXT_I_2:
                    $this->getTermStr();
                    // Ignore extensions
                    continue;

                case WBXML_PI:
                    // Ignore PI
                    $this->getAttributes();
                    continue;

                case WBXML_LITERAL_C:
                    $element[EN_TYPE] = EN_TYPE_STARTTAG;
                    $element[EN_TAG] = $this->getStringTableEntry($this->getMBUInt());
                    $element[EN_FLAGS] = EN_FLAGS_CONTENT;
                    return $element;

                case WBXML_EXT_T_0:
                case WBXML_EXT_T_1:
                case WBXML_EXT_T_2:
                    $this->getMBUInt();
                    // Ingore extensions;
                    continue;

                case WBXML_STR_T:
                    $element[EN_TYPE] = EN_TYPE_CONTENT;
                    $element[EN_CONTENT] = $this->getStringTableEntry($this->getMBUInt());
                    return $element;

                case WBXML_LITERAL_A:
                    $element[EN_TYPE] = EN_TYPE_STARTTAG;
                    $element[EN_TAG] = $this->getStringTableEntry($this->getMBUInt());
                    $element[EN_ATTRIBUTES] = $this->getAttributes();
                    $element[EN_FLAGS] = EN_FLAGS_ATTRIBUTES;
                    return $element;
                case WBXML_EXT_0:
                case WBXML_EXT_1:
                case WBXML_EXT_2:
                    continue;

                case WBXML_OPAQUE:
                    $length = $this->getMBUInt();
                    $element[EN_TYPE] = EN_TYPE_CONTENT;
                    $element[EN_CONTENT] = $this->getOpaque($length);
                    return $element;

                case WBXML_LITERAL_AC:
                    $element[EN_TYPE] = EN_TYPE_STARTTAG;
                    $element[EN_TAG] = $this->getStringTableEntry($this->getMBUInt());
                    $element[EN_ATTRIBUTES] = $this->getAttributes();
                    $element[EN_FLAGS] = EN_FLAGS_ATTRIBUTES | EN_FLAGS_CONTENT;
                    return $element;

                default:
                    $element[EN_TYPE] = EN_TYPE_STARTTAG;
                    $element[EN_TAG] = $this->getMapping($this->tagcp, $byte & 0x3f);
                    $element[EN_FLAGS] = ($byte & 0x80 ? EN_FLAGS_ATTRIBUTES : 0) | ($byte & 0x40 ? EN_FLAGS_CONTENT : 0);
                    if($byte & 0x80)
                        $element[EN_ATTRIBUTES] = $this->getAttributes();
                    return $element;
            }
        }
    }

    function ungetElement($element) {
        if($element != NULL)
           array_push($this->ungetbuffer, $element);
    }

    function getAttributes() {
        $attributes = array();
        $attr = "";

        while(1) {
            $byte = $this->getByte();

            if(count($byte) == 0)
                break;

            switch($byte) {
                case WBXML_SWITCH_PAGE:
                    $this->attrcp = $this->getByte();
                    break;

                case WBXML_END:
                    if($attr != "")
                        $attributes += $this->splitAttribute($attr);

                    return $attributes;

                case WBXML_ENTITY:
                    $entity = $this->getMBUInt();
                    $attr .= $this->entityToCharset($entity);
                    return $element;

                case WBXML_STR_I:
                    $attr .= $this->getTermStr();
                    return $element;

                case WBXML_LITERAL:
                    if($attr != "")
                        $attributes += $this->splitAttribute($attr);

                    $attr = $this->getStringTableEntry($this->getMBUInt());
                    return $element;

                case WBXML_EXT_I_0:
                case WBXML_EXT_I_1:
                case WBXML_EXT_I_2:
                    $this->getTermStr();
                    continue;

                case WBXML_PI:
                case WBXML_LITERAL_C:
                    // Invalid
                    return false;

                case WBXML_EXT_T_0:
                case WBXML_EXT_T_1:
                case WBXML_EXT_T_2:
                    $this->getMBUInt();
                    continue;

                case WBXML_STR_T:
                    $attr .= $this->getStringTableEntry($this->getMBUInt());
                    return $element;

                case WBXML_LITERAL_A:
                    return false;

                case WBXML_EXT_0:
                case WBXML_EXT_1:
                case WBXML_EXT_2:
                    continue;

                case WBXML_OPAQUE:
                    $length = $this->getMBUInt();
                    $attr .= $this->getOpaque($length);
                    return $element;

                case WBXML_LITERAL_AC:
                    return false;

                default:
                    if($byte < 128) {
                        if($attr != "") {
                            $attributes += $this->splitAttribute($attr);
                            $attr = "";
                        }
                    }

                    $attr .= $this->getMapping($this->attrcp, $byte);
                    break;
            }
        }

    }

    function splitAttribute($attr) {
        $attributes = array();

        $pos = strpos($attr,chr(61)); // equals sign

        if($pos)
            $attributes[substr($attr, 0, $pos)] = substr($attr, $pos+1);
        else
            $attributes[$attr] = null;

        return $attributes;
    }

    function getTermStr() {
        $str = "";
        while(1) {
            $in = $this->getByte();

            if($in == 0)
                break;
            else
                $str .= chr($in);
        }

        return $str;
    }

    function getOpaque($len) {
        return fread($this->in, $len);
    }

    function tell()
    {
       return ftell($this->in);
    }
    function seek($offset, $whence = SEEK_SET)
    {
        return fseek($this->in, $offset, $whence);
    }
    function getByte() {
        $ch = fread($this->in, 1);
        if(strlen($ch) > 0)
            return ord($ch);
        else
            return;
    }

    function getMBUInt() {
        $uint = 0;

        while(1) {
          $byte = $this->getByte();

          $uint |= $byte & 0x7f;

          if($byte & 0x80)
              $uint = $uint << 7;
          else
              break;
        }

        return $uint;
    }

    function getStringTable() {
        $stringtable = "";

        $length = $this->getMBUInt();
        if($length > 0)
            $stringtable = fread($this->in, $length);

        return $stringtable;
    }

    function getMapping($cp, $id) {
        if(!isset($this->dtd["codes"][$cp]) || !isset($this->dtd["codes"][$cp][$id]))
            return false;
        else {
            if(isset($this->dtd["namespaces"][$cp])) {
                return $this->dtd["namespaces"][$cp] . ":" . $this->dtd["codes"][$cp][$id];
            } else
                return $this->dtd["codes"][$cp][$id];
        }
    }
}

class WBXMLEncoder {
    var $_dtd;
    var $_out;

    var $_tagcp;
    var $_attrcp;

    var $logStack = array();

    // We use a delayed output mechanism in which we only output a tag when it actually has something
    // in it. This can cause entire XML trees to disappear if they don't have output data in them; Ie
    // calling 'startTag' 10 times, and then 'endTag' will cause 0 bytes of output apart from the header.

    // Only when content() is called do we output the current stack of tags

    var $_stack;

    function WBXMLEncoder($output, $dtd) {
        $this->_out = $output;

        $this->_tagcp = 0;
        $this->_attrcp = 0;

        // reverse-map the DTD
        foreach($dtd["namespaces"] as $nsid => $nsname) {
            $this->_dtd["namespaces"][$nsname] = $nsid;
        }

        foreach($dtd["codes"] as $cp => $value) {
            $this->_dtd["codes"][$cp] = array();
            foreach($dtd["codes"][$cp] as $tagid => $tagname) {
                $this->_dtd["codes"][$cp][$tagname] = $tagid;
            }
        }
        $this->_stack = array();
    }

    function startWBXML() {
        header("Content-Type: application/vnd.ms-sync.wbxml");

        $this->outByte(0x03); // WBXML 1.3
        $this->outMBUInt(0x01); // Public ID 1
        $this->outMBUInt(106); // UTF-8
        $this->outMBUInt(0x00); // string table length (0)
    }

    function startTag($tag, $attributes = false, $nocontent = false) {
        $stackelem = array();

        if(!$nocontent) {
            $stackelem['tag'] = $tag;
            $stackelem['attributes'] = $attributes;
            $stackelem['nocontent'] = $nocontent;
            $stackelem['sent'] = false;

            array_push($this->_stack, $stackelem);

            // If 'nocontent' is specified, then apparently the user wants to force
            // output of an empty tag, and we therefore output the stack here
        } else {
            $this->_outputStack();
            $this->_startTag($tag, $attributes, $nocontent);
        }
    }

    function endTag() {
        $stackelem = array_pop($this->_stack);

        // Only output end tags for items that have had a start tag sent
        if($stackelem['sent']) {
            $this->_endTag();
        }
    }

    function content($content) {
        // We need to filter out any \0 chars because it's the string terminator in WBXML. We currently
        // cannot send \0 characters within the XML content anywhere.
        $content = str_replace("\0","",$content);

        if("x" . $content == "x")
            return;
        $this->_outputStack();
        $this->_content($content);
    }

    // Output any tags on the stack that haven't been output yet
    function _outputStack() {
        for($i=0;$i<count($this->_stack);$i++) {
            if(!$this->_stack[$i]['sent']) {
                $this->_startTag($this->_stack[$i]['tag'], $this->_stack[$i]['attributes'], $this->_stack[$i]['nocontent']);
                $this->_stack[$i]['sent'] = true;
            }
        }
    }

    // Outputs an actual start tag
    function _startTag($tag, $attributes = false, $nocontent = false) {
        $this->logStartTag($tag, $attributes, $nocontent);

        $mapping = $this->getMapping($tag);

        if(!$mapping)
            return false;

        if($this->_tagcp != $mapping["cp"]) {
            $this->outSwitchPage($mapping["cp"]);
            $this->_tagcp = $mapping["cp"];
        }

        $code = $mapping["code"];
        if(isset($attributes) && is_array($attributes) && count($attributes) > 0) {
            $code |= 0x80;
        }

        if(!isset($nocontent) || !$nocontent)
            $code |= 0x40;

        $this->outByte($code);

        if($code & 0x80)
            $this->outAttributes($attributes);
    }

    // Outputs actual data
    function _content($content) {
        $this->logContent($content);
        $this->outByte(WBXML_STR_I);
        $this->outTermStr($content);
    }

    // Outputs an actual end tag
    function _endTag() {
        $this->logEndTag();
        $this->outByte(WBXML_END);
    }

    // --------------------------- Private

    function outByte($byte) {
        fwrite($this->_out, chr($byte));
    }

    function outMBUInt($uint) {
        while(1) {
            $byte = $uint & 0x7f;
            $uint = $uint >> 7;
            if($uint == 0) {
                $this->outByte($byte);
                break;
            } else {
                $this->outByte($byte | 0x80);
            }
        }
    }

    function outTermStr($content) {                                      
		//to catch occational, illegal arrays 
        if( is_array($content) )
		{
			die('<hr/><pre>' . __METHOD__ . ' #' . __LINE__ . ': $content <br />' . htmlentities(print_r($content, true),null,'utf-8') . '</pre>');
		}
			
		fwrite($this->_out, $content);
        fwrite($this->_out, chr(0));
    }

    function outAttributes() {
        // We don't actually support this, because to do so, we would have
        // to build a string table before sending the data (but we can't
        // because we're streaming), so we'll just send an END, which just
        // terminates the attribute list with 0 attributes.
        $this->outByte(WBXML_END);
    }

    function outSwitchPage($page) {
        $this->outByte(WBXML_SWITCH_PAGE);
        $this->outByte($page);
    }

    function getMapping($tag) {
        $mapping = array();

        $split = $this->splitTag($tag);

        if(isset($split["ns"])) {
            $cp = $this->_dtd["namespaces"][$split["ns"]];
        } else {
            $cp = 0;
        }

        $code = $this->_dtd["codes"][$cp][$split["tag"]];

        $mapping["cp"] = $cp;
        $mapping["code"] = $code;

        return $mapping;
    }

    function splitTag($fulltag) {
        $ns = false;
        $pos = strpos($fulltag, chr(58)); // chr(58) == ':'

        if($pos) {
            $ns = substr($fulltag, 0, $pos);
            $tag = substr($fulltag, $pos+1);
        } else {
            $tag = $fulltag;
        }

        $ret = array();
        if($ns)
            $ret["ns"] = $ns;
        $ret["tag"] = $tag;

        return $ret;
    }

    function logStartTag($tag, $attr, $nocontent) {
        if(!WBXML_DEBUG)
            return;

        $spaces = str_repeat(" ", count($this->logStack));
        if($nocontent)
        {
            //debugLog("O " . $spaces . " <$tag/>");
        }
        else
        {
            array_push($this->logStack, $tag);
            //debugLog("O " . $spaces . " <$tag>");
        }
    }

    function logEndTag() {
        if(!WBXML_DEBUG)
            return;

        $spaces = str_repeat(" ", count($this->logStack));
        $tag = array_pop($this->logStack);
        //debugLog("O " . $spaces . "</$tag>");
    }

    function logContent($content) {
        if(!WBXML_DEBUG)
            return;

        $spaces = str_repeat(" ", count($this->logStack));
        //debugLog("O " . $spaces . $content);
    }
}