ppml.py 23.9 KB
Newer Older
1
# -*- coding: utf-8 -*-
2 3 4 5 6 7 8 9 10 11 12 13 14 15
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# Copyright (c) 2002,2005 Nexedi SARL and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
##############################################################################

16
import re
17

18 19 20
# Import everything right now, not after
# or new patch will not work
from Shared.DC.xml.ppml import *
Yoshinori Okuji committed
21 22
from Shared.DC.xml import ppml

23
from marshal import dumps as mdumps
24
from zLOG import LOG
25

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
# For converting to a more readable expression.
reprs = {}
### patch begin: create a conversion table for [\x00-\x1f]. this table is
###              used for a valid utf-8 string.
for c in map(chr, range(32)): reprs[c] = repr(c)[1:-1]
### patch end
reprs['\n'] = "\\n\n"
reprs['\t'] = "\\t"
reprs['\\'] = "\\\\"
reprs['\r'] = "\\r"
reprs["'"] = "\\'"
reprs2={}
reprs2['<'] = "\\074"
reprs2['>'] = "\\076"
reprs2['&'] = "\\046"
41 42 43 44 45 46 47 48

reprs_re = re.compile('|'.join(re.escape(k) for k in reprs.keys()))
def sub_reprs(m):
  return reprs[m.group(0)]

reprs2_re = re.compile('|'.join(re.escape(k) for k in reprs2.keys()))
def sub_reprs2(m):
  return reprs2[m.group(0)]
49

50
def convert(S):
51 52 53 54 55
    new = ''
    ### patch begin: if the input string is a valid utf8 string, only
    ###              [\x00-\x1f] characters will be escaped to make a more
    ###              readable output.
    try:
56
        if not isinstance(S, unicode):
57
            S.decode('utf8')
58
    except UnicodeDecodeError:
59
        return 'base64', base64.encodestring(S)[:-1]
60
    else:
61
        new = reprs_re.sub(sub_reprs, S)
62 63
    ### patch end
    if len(new) > (1.4*len(S)):
64 65 66
        return 'base64', base64.encodestring(S)[:-1]
    elif '>' in new or '<' in S or '&' in S:
        if not ']]>' in S:
67
            return 'cdata', '<![CDATA[\n\n' + new + '\n\n]]>'
68
        else:
69
            return 'repr', reprs2_re.sub(sub_reprs2, new)
70
    return 'repr', new
71 72 73

ppml.convert = convert

Yoshinori Okuji committed
74 75 76
# For optimization.
def unconvert(encoding,S):
    if encoding == 'base64':
77
        return base64.decodestring(S)
Yoshinori Okuji committed
78
    else:
79
        return eval("'" + S.replace('\n', '') + "'")
Yoshinori Okuji committed
80 81

ppml.unconvert = unconvert
82 83 84 85 86 87 88 89 90 91 92 93

class Global:

    def __init__(self, module, name, mapping):
        self.module=module
        self.name=name
        self.mapping = mapping

    def __str__(self, indent=0):
        id = ''
        if hasattr(self, 'id'):
            if self.mapping.isMarked(self.id): id=' id="%s"' % self.mapping[self.id]
94
        name=self.__class__.__name__.lower()
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
        return '%s<%s%s name="%s" module="%s"/>\n' % (
            ' '*indent, name, id, self.name, self.module)

ppml.Global = Global

class Scalar:

    def __init__(self, v, mapping):
        self._v=v
        self.mapping = mapping

    def value(self): return self._v

    def __str__(self, indent=0):
        id = ''
110
        name=self.__class__.__name__.lower()
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
        result = '%s<%s%s>%s</%s>\n' % (
            ' '*indent, name, id, self.value(), name)
        if hasattr(self, 'id'):
            # The value is Immutable - let us add it the the immutable mapping
            # to reduce the number of unreadable references
            self.mapping.setImmutable(self.id, Immutable(value = result))
        return result

ppml.Scalar = Scalar

class Immutable:
    def __init__(self, value):
        self.value = value

    def getValue(self):
        return self.value

class String(Scalar):
129 130 131

    encoding = None

132 133 134
    def __init__(self, v, mapping, encoding=''):
        self._v=v
        self.mapping = mapping
135

136
    def __str__(self,indent=0,map_value=0):
137 138 139 140 141 142 143 144 145
        encoding = self.encoding
        if encoding is None:
            # lazy conversion
            if map_value:
                # This is used when strings represent references which need to
                # be converted.
                encoding = 'base64'
                v = base64.encodestring(self._v)[:-1]
                self._v = self.mapping.convertBase64(v)
146
            else:
147 148 149
                encoding, self._v = convert(self._v)
            self.encoding = encoding
        v = self.value()
150
        id = ''
151 152 153 154
        if encoding == 'repr':
            encoding = '' # JPS repr is default encoding
        else:
            encoding = ' encoding="%s"' % encoding
155
        name=self.__class__.__name__.lower()
156
        result = '<%s%s%s>%s</%s>' % (name, id, encoding, v, name)
157 158 159 160
        if hasattr(self, 'id'):
            # The value is Immutable - let us add it the the immutable mapping
            # to reduce the number of unreadable references
            self.mapping.setImmutable(self.id, Immutable(value = result))
161
        return '%s%s\n' % (' '*indent, result)
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182

ppml.String = String

class Unicode(String):
    def value(self):
        return self._v.encode('utf-8')

ppml.Unicode = Unicode

class Wrapper:

    def __init__(self, v, mapping):
        self._v=v
        self.mapping = mapping

    def value(self): return self._v

    def __str__(self, indent=0):
        id = ''
        if hasattr(self, 'id'):
            if self.mapping.isMarked(self.id): id=' id="%s"' % self.mapping[self.id]
183
        name=self.__class__.__name__.lower()
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
        v=self._v
        i=' '*indent
        if isinstance(v,Scalar):
            return '%s<%s%s> %s </%s>\n' % (i, name, id, str(v)[:-1], name)
        else:
            v=v.__str__(indent+2)
            return '%s<%s%s>\n%s%s</%s>\n' % (i, name, id, v, i, name)

ppml.Wrapper = Wrapper

class Collection:

    def __init__(self, mapping):
        self.mapping = mapping

    def __str__(self, indent=0):
        id = ''
        if hasattr(self, 'id'):
            if self.mapping.isMarked(self.id): id=' id="%s"' % self.mapping[self.id]
203
        name=self.__class__.__name__.lower()
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
        i=' '*indent
        if self:
            return '%s<%s%s>\n%s%s</%s>\n' % (
                i, name, id, self.value(indent+2), i, name)
        else:
            return '%s<%s%s/>\n' % (i, name, id)

ppml.Collection = Collection

class Dictionary(Collection):
    def __init__(self, mapping):
        self.mapping = mapping
        self._d=[]
    def __len__(self): return len(self._d)
    def __setitem__(self, k, v): self._d.append((k,v))
    def value(self, indent):
        #self._d.sort(lambda a, b: cmp(a[0]._v, b[0]._v)) # Sort the sequence by key JPS Improvement
221 222 223 224
        ind = ' ' * indent
        indent = indent + 4
        return ''.join(
            '%s<item>\n%s%s%s</item>\n'
225 226 227 228
                %
                (ind,
                 Key(i[0], self.mapping).__str__(indent),
                 Value(i[1], self.mapping).__str__(indent),
229 230 231
                 ind)
                 for i in self._d
            )
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249

ppml.Dictionary = Dictionary

class Sequence(Collection):

    def __init__(self, mapping, v=None):
        if not v: v=[]
        self._subs=v
        self.mapping = mapping

    def __len__(self): return len(self._subs)

    def append(self, v): self._subs.append(v)

    # Bugfix JPS
    def extend(self, v): self._subs.extend(v)

    def value(self, indent):
250 251 252
        return ''.join(
            v.__str__(indent) for v in
            self._subs)
253 254 255 256 257 258 259 260 261

ppml.Sequence = Sequence

class Persistent(Wrapper):

    def __str__(self, indent=0):
        id = ''
        if hasattr(self, 'id'):
            if self.mapping.isMarked(self.id): id=' id="%s"' % self.mapping[self.id]
262
        name=self.__class__.__name__.lower()
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
        v=self._v
        i=' '*indent
        if isinstance(v,String):
            return '%s<%s%s> %s </%s>\n' % (i, name, id, v.__str__(map_value=1)[:-1], name)
        elif isinstance(v,Scalar):
            return '%s<%s%s> %s </%s>\n' % (i, name, id, str(v)[:-1], name)
        else:
            v=v.__str__(indent+2)
            return '%s<%s%s>\n%s%s</%s>\n' % (i, name, id, v, i, name)

ppml.Persistent = Persistent

class Reference(Scalar):
    def __init__(self, v, mapping):
        self._v=v
        self.mapping = mapping
279
        mapping.mark(v)
280 281 282 283
    def __str__(self, indent=0):
        v=self._v
        #LOG('Reference', 0, str(v))
        if self.mapping.hasImmutable(v):
284 285 286 287 288 289
          value = self.mapping.getImmutable(v).getValue()
        else:
          name = self.__class__.__name__.lower()
          #LOG('noImmutable', 0, "%s mapped to %s" % (v, self.mapping[v]))
          value = '<%s id="%s"/>' % (name, self.mapping[v])
        return '%s%s\n' % (' '*indent, value)
290 291 292 293 294 295 296 297 298 299 300 301 302 303

ppml.Reference = Reference
Get = Reference
ppml.Get = Get

class Object(Sequence):
    def __init__(self, klass, args, mapping):
        self._subs=[Klass(klass, mapping), args]
        self.mapping = mapping

    def __setstate__(self, v): self.append(State(v, self.mapping))

ppml.Object = Object

304 305
blanck_line_expression = re.compile('^ +$')

Yoshinori Okuji committed
306
class NoBlanks:
307 308 309 310
    """
    This allows to ignore at least whitespaces between elements and also
    correctly handle string/unicode
    """
311 312 313
    previous_stack_end = None
    previous_discarded_data = None

Yoshinori Okuji committed
314
    def handle_data(self, data):
315 316 317 318 319 320 321 322
        """
        Called for each character lines of element data, twice in this
        example:

        <string>abc
        bar</string>
        """
        # Ignore element data between elements (eg '<e> <f> </f> </e>')...
323 324 325 326
        if data.strip():
            if isinstance(data, unicode):
                data = data.encode('raw_unicode_escape')
            self.append(data)
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351

        # Except for strings and unicode data as whitespaces should be
        # kept. It happened that javascript files with a line like " ];\n" was
        # replaced by "];\n", so the indent was lost. Indeed the parser was
        # calling this handle_data function first for " ", then for "];". So
        # original code was dropping the " ".
        elif (isinstance(self._stack[-1], list) and
              self._stack[-1][0] in ('string', 'unicode')):
            # If the first character data of this element is a whitespace, it
            # will be concatenated with the next line (if any, but at
            # this point it is not possible to know anyway)
            if len(self._stack[-1]) == 2:
                self.previous_stack_end = self._stack[-1]
                self.previous_discarded_data = data
            else:
                if (self._stack[-1] == self.previous_stack_end and
                    self.previous_discarded_data):
                    data = self.previous_discarded_data + data
                    self.previous_discarded_data = None
                    self.previous_stack_end = None

                if isinstance(data, unicode):
                    data = data.encode('raw_unicode_escape')

                self.append(data)
Yoshinori Okuji committed
352 353 354

ppml.NoBlanks = NoBlanks

355 356 357
class IdentityMapping:

    def __init__(self):
358
      self.resetMapping()
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
      self.immutable = {}

    def resetMapping(self):
      pass

    def __getitem__(self, id):
      return id

    def setConvertedAka(self, old, new):
      pass

    def convertBase64(self, s):
      return s

    def mark(self, v):
      pass

    def isMarked(self, v):
      return 1

    def setImmutable(self, k, v):
      self.immutable[k] = v

    def getImmutable(self, k):
      return self.immutable[k]

    def hasImmutable(self, k):
      return self.immutable.has_key(k)


ppml.IdentityMapping = IdentityMapping

class MinimalMapping(IdentityMapping):

    def resetMapping(self):
      self.mapped_id = {}
      self.mapped_core_id = {}
      self.last_sub_id = {}
      self.last_id = 1
      self.converted_aka = {}
399
      self.marked_reference = set()
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437

    def __getitem__(self, id):
      id = str(id)
      split_id = id.split('.')
      if len(split_id) == 2:
        (core_id, sub_id) = split_id
      elif len(split_id) == 1:
        core_id = split_id[0]
        sub_id = None
      else:
        raise
      if not self.mapped_id.has_key(core_id):
        if sub_id is not None:
          # Use existing id
          self.mapped_id[core_id] = {}
          self.mapped_core_id[core_id] = self.last_id - 1
          self.last_sub_id[core_id] = 1
        else:
          # Create new core_id if not defined
          self.mapped_id[core_id] = {}
          self.mapped_core_id[core_id] = self.last_id
          self.last_sub_id[core_id] = 1
          self.last_id = self.last_id + 1
      if sub_id is None:
        return self.mapped_core_id[core_id]
      if not self.mapped_id[core_id].has_key(sub_id):
        # Create new sub_id if not defined
        self.mapped_id[core_id][sub_id] = self.last_sub_id[core_id]
        self.last_sub_id[core_id] = self.last_sub_id[core_id] + 1
      return "%s.%s" % (self.mapped_core_id[core_id], self.mapped_id[core_id][sub_id])

    def convertBase64(self, s):
      return self.converted_aka.get(s, s)

    def setConvertedAka(self, old, new):
      self.converted_aka[old] =  new

    def mark(self, v):
438
      self.marked_reference.add(v)
439 440

    def isMarked(self, v):
441
      return v in self.marked_reference
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492

    def __str__(self, a):
      return "Error here"

ppml.MinimalMapping = MinimalMapping

class List(Sequence): pass
class Tuple(Sequence): pass

class Klass(Wrapper): pass
class State(Wrapper): pass
class Pickle(Wrapper): pass

class Int(Scalar): pass
class Float(Scalar): pass

class Key(Wrapper): pass
class Value(Wrapper): pass

class Long(Scalar):
    def value(self):
        result = str(self._v)
        if result[-1:] == 'L':
            return result[:-1]
        return result

class ToXMLUnpickler(Unpickler):

    def load(self, id_mapping=None):
      if id_mapping is None:
        self.id_mapping = IdentityMapping()
      else:
        self.id_mapping = id_mapping
      return Pickle(Unpickler.load(self), self.id_mapping)

    dispatch = {}
    dispatch.update(Unpickler.dispatch)

    def persistent_load(self, v):
        return Persistent(v, self.id_mapping)

    def load_persid(self):
        pid = self.readline()[:-1]
        self.append(self.persistent_load(String(pid, self.id_mapping)))
    dispatch[PERSID] = load_persid

    def load_none(self):
        self.append(none)
    dispatch[NONE] = load_none

    def load_int(self):
493
        self.append(Int(int(self.readline()[:-1]), self.id_mapping))
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
    dispatch[INT] = load_int

    def load_binint(self):
        self.append(Int(mloads('i' + self.read(4)), self.id_mapping))
    dispatch[BININT] = load_binint

    def load_binint1(self):
        self.append(Int(mloads('i' + self.read(1) + '\000\000\000'), self.id_mapping))
    dispatch[BININT1] = load_binint1

    def load_binint2(self):
        self.append(Int(mloads('i' + self.read(2) + '\000\000'), self.id_mapping))
    dispatch[BININT2] = load_binint2

    def load_long(self):
509
        self.append(Long(long(self.readline()[:-1], 0), self.id_mapping))
510 511 512
    dispatch[LONG] = load_long

    def load_float(self):
513
        self.append(Float(float(self.readline()[:-1]), self.id_mapping))
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
    dispatch[FLOAT] = load_float

    def load_binfloat(self, unpack=struct.unpack):
        self.append(Float(unpack('>d', self.read(8))[0], self.id_mapping))
    dispatch[BINFLOAT] = load_binfloat

    def load_string(self):
        self.append(String(eval(self.readline()[:-1],
                                {'__builtins__': {}}), self.id_mapping)) # Let's be careful
    dispatch[STRING] = load_string

    def load_binstring(self):
        len = mloads('i' + self.read(4))
        self.append(String(self.read(len), self.id_mapping))
    dispatch[BINSTRING] = load_binstring

    def load_unicode(self):
        self.append(Unicode(unicode(eval(self.readline()[:-1],
                                         {'__builtins__': {}})), self.id_mapping)) # Let's be careful
    dispatch[UNICODE] = load_unicode

    def load_binunicode(self):
        len = mloads('i' + self.read(4))
        self.append(Unicode(unicode(self.read(len), 'utf-8'), self.id_mapping))
    dispatch[BINUNICODE] = load_binunicode

    def load_short_binstring(self):
        len = mloads('i' + self.read(1) + '\000\000\000')
        self.append(String(self.read(len), self.id_mapping))
    dispatch[SHORT_BINSTRING] = load_short_binstring

    def load_tuple(self):
        k = self.marker()
        #LOG('load_tuple, k',0,k)
        #LOG('load_tuple, stack[k+1:]',0,self.stack[k+1:])
        self.stack[k:] = [Tuple(self.id_mapping, v=self.stack[k+1:])]
    dispatch[TUPLE] = load_tuple

    def load_empty_tuple(self):
        self.stack.append(Tuple(self.id_mapping))
    dispatch[EMPTY_TUPLE] = load_empty_tuple

    def load_empty_list(self):
        self.stack.append(List(self.id_mapping))
    dispatch[EMPTY_LIST] = load_empty_list

    def load_empty_dictionary(self):
        self.stack.append(Dictionary(self.id_mapping))
    dispatch[EMPTY_DICT] = load_empty_dictionary

    def load_list(self):
        k = self.marker()
        self.stack[k:] = [List(self.id_mapping, v=self.stack[k+1:])]
    dispatch[LIST] = load_list

    def load_dict(self):
        k = self.marker()
        d = Dictionary(self.id_mapping)
        items = self.stack[k+1:]
        for i in range(0, len(items), 2):
            key = items[i]
            value = items[i+1]
            d[key] = value
        self.stack[k:] = [d]
    dispatch[DICT] = load_dict

    def load_inst(self):
        k = self.marker()
        args = Tuple(self.id_mapping, v=self.stack[k+1:])
        del self.stack[k:]
        module = self.readline()[:-1]
        name = self.readline()[:-1]
        value=Object(Global(module, name, self.id_mapping), args, self.id_mapping)
        self.append(value)
    dispatch[INST] = load_inst

    def load_obj(self):
        stack = self.stack
        k = self.marker()
        klass = stack[k + 1]
        del stack[k + 1]
        args = Tuple(self.id_mapping, v=stack[k + 1:])
        del stack[k:]
        value=Object(klass,args, self.id_mapping)
        self.append(value)
    dispatch[OBJ] = load_obj

    def load_global(self):
        module = self.readline()[:-1]
        name = self.readline()[:-1]
        self.append(Global(module, name, self.id_mapping))
    dispatch[GLOBAL] = load_global

    def load_reduce(self):
        stack = self.stack

        callable = stack[-2]
        arg_tup  = stack[-1]
        del stack[-2:]

        value=Object(callable, arg_tup, self.id_mapping)
        self.append(value)
    dispatch[REDUCE] = load_reduce

    idprefix=''

    def load_get(self):
        self.append(Get(self.idprefix+self.readline()[:-1], self.id_mapping))
    dispatch[GET] = load_get

    def load_binget(self):
        i = mloads('i' + self.read(1) + '\000\000\000')
        self.append(Get(self.idprefix+`i`, self.id_mapping))
    dispatch[BINGET] = load_binget

    def load_long_binget(self):
        i = mloads('i' + self.read(4))
        self.append(Get(self.idprefix+`i`, self.id_mapping))
    dispatch[LONG_BINGET] = load_long_binget

    def load_put(self):
        self.stack[-1].id=self.idprefix+self.readline()[:-1]
    dispatch[PUT] = load_put

    def load_binput(self):
        i = mloads('i' + self.read(1) + '\000\000\000')
        #LOG('load_binput', 0, 'self.stack = %r, self.idprefix+`i` = %r' % (self.stack, self.idprefix+`i`))
        self.stack[-1].id=self.idprefix+`i`
    dispatch[BINPUT] = load_binput

    def load_long_binput(self):
        i = mloads('i' + self.read(4))
        self.stack[-1].id=self.idprefix+`i`
    dispatch[LONG_BINPUT] = load_long_binput

    class LogCall:
      def __init__(self, func):
        self.func = func

      def __call__(self, context):
        #LOG('LogCall', 0, 'self.stack = %r, func = %s' % (context.stack, self.func.__name__))
        return self.func(context)

    #for code in dispatch.keys():
    #  dispatch[code] = LogCall(dispatch[code])

ppml.ToXMLUnpickler = ToXMLUnpickler

def save_string(self, tag, data):
    binary=self.binary
    v=''
    a=data[1]
    if len(data)>2:
Yoshinori Okuji committed
667
        v = ''.join(data[2:])
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
    encoding=a.get('encoding','repr') # JPS: repr is default encoding
    if encoding is not '':
        v=unconvert(encoding,v)
    put='p'
    if binary:
        l=len(v)
        s=mdumps(l)[1:]
        if (l<256):
            v='U'+s[0]+v
        else:
            v='T'+s+v
        put='q'
    else: v="S'"+v+"'\012"
    return save_put(self, v, a)

ppml.save_string = save_string

def save_unicode(self, tag, data):
    binary=self.binary
    v=''
    a=data[1]
    if len(data)>2:
        for x in data[2:]:
            v=v+x
    encoding=a.get('encoding','repr') # JPS: repr is default encoding
    if encoding is not '':
        v=unconvert(encoding,v)
    if binary:
        l=len(v)
        s=mdumps(l)[1:]
        v=BINUNICODE+s+v
    else: v=UNICODE+"'"+v+"'\012"
    return save_put(self, v, a)

ppml.save_unicode = save_unicode

704 705 706 707 708
def save_object(self, tag, data):
    if len(data)==5:
        #OBJECT
        v='('+data[2]
        x=data[3][1:]
709
        stop=x.rfind('t')  # This seems
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724
        if stop>=0: x=x[:stop]    # wrong!
        v=save_put(self, v+x+'o', data[1])
        v=v+data[4]+'b' # state
        return v
    else:
        #REDUCE
        #data does not contain state.(See Object.__setstate__ definition)
        #So, we can assume that this is a reduce. (Yusei)
        v='('+data[2]
        v=save_put(self, data[2]+data[3], data[1])
        v=v+'R'
        return v

ppml.save_object = save_object

725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
def save_pickle_start(self, tag, attrs):
    return [tag, attrs]

def save_pickle(self, tag, data):
    return data[2] + '.'

def save_none(self, tag, data):
    return 'N'

def save_long(self, tag, data):
    return 'L'+data[2]+'L\012'

def save_item(self, tag, data):
    return ''.join(data[2:])

def save_value(self, tag, data):
    return data[2]
742

743
class xmlPickler(NoBlanks, xyap):
744 745 746 747 748 749 750 751 752 753 754 755
    # XXX fix a bug in xyap.
    def unknown_endtag(self, tag):
        _stack = self._stack
        top = _stack.pop()
        append = self.append = _stack[-1].append
        end = self.end_handlers
        if tag in end:
            top = end[tag](self, tag, top)
        if isinstance(top, unicode):
            top = top.encode('raw_unicode_escape')
        append(top)

756
    start_handlers={
757
        'pickle': save_pickle_start,
758 759
        }
    end_handlers={
760 761
        'pickle': save_pickle,
        'none': save_none,
762
        'int': save_int,
763
        'long': save_long,
764 765 766 767 768 769 770
        'float': save_float,
        'string': save_string,
        'unicode': save_unicode,
        'reference': save_reference,
        'tuple': save_tuple,
        'list': save_list,
        'dictionary': save_dict,
771 772 773
        'item': save_item,
        'value': save_value,
        'key' : save_value,
774
        'object': save_object,
775 776
        'klass': save_value,
        'state': save_value,
777 778 779 780
        'global': save_global,
        'persistent': save_persis,
        }

781 782 783
# FIXME: Leo: Do we still need to replace ppml.xmlPickler now that we're
# using our own xmlPickler in our own importXML function below? Do we support
# any other use of xmlPickler except for Business Template export/import?
784 785 786 787 788
ppml.xmlPickler = xmlPickler

class Tuple(Sequence): pass

ppml.Tuple = Tuple
789

790 791
# Copied from OFS.XMLExportImport.importXML (of Zope 2.12)
# Imported and used directly by Products.ERP5.Document.BusinessTemplate
792 793 794
from OFS.XMLExportImport import save_record, save_zopedata, start_zopedata
from tempfile import TemporaryFile
import xml.parsers.expat
795 796 797 798 799 800 801 802 803 804 805
def importXML(jar, file, clue=''):
    if type(file) is str:
        file=open(file, 'rb')
    outfile=TemporaryFile()
    data=file.read()
    F=xmlPickler()
    F.end_handlers['record'] = save_record
    F.end_handlers['ZopeData'] = save_zopedata
    F.start_handlers['ZopeData'] = start_zopedata
    F.binary=1
    F.file=outfile
806
    # <patch>
807 808 809 810 811
    # Our BTs XML files don't declare encoding but have accented chars in them
    # So we have to declare an encoding but not use unicode, so the unpickler
    # can deal with the utf-8 strings directly
    p=xml.parsers.expat.ParserCreate('utf-8')
    p.returns_unicode = False
812
    # </patch>
813 814 815 816 817 818
    p.CharacterDataHandler=F.handle_data
    p.StartElementHandler=F.unknown_starttag
    p.EndElementHandler=F.unknown_endtag
    r=p.Parse(data)
    outfile.seek(0)
    return jar.importFile(outfile,clue)