Beispiel #1
0
def readData(ob, default=None):
  """
  Read data of Zope-object.
  """
  data = default
  if ob is None and default is not None:
    return default
  if ob.meta_type in [ 'DTML Document', 'DTML Method', 'Filesystem DTML Document', 'Filesystem DTML Method']:
    data = ob.raw
  elif ob.meta_type in [ 'File', 'Filesystem File', 'Filesystem Image', 'Image']:
    data = ob.data
    if not standard.is_bytes(data):
      b = b''
      while data is not None:
        b += data.data
        data = data.next
      data = b
  elif ob.meta_type in [ 'Filesystem Page Template', 'Filesystem Script (Python)', 'Page Template', 'Script (Python)']:
    data = ob.read()
  elif ob.meta_type in [ 'External Method']:
    if isinstance(ob,MissingArtefactProxy):
      return ob.getData()
    else:
      context = ob
      id = ob.getId()
      while context is not None:
        m = getExternalMethodModuleName(context, id)
        filepath = standard.getINSTANCE_HOME()+'/Extensions/'+m+'.py'
        if os.path.exists(filepath):
          break
        try:
          context = context.getParentNode()
        except:
          context = None
      if context is None:
        m = id
      filepath = standard.getINSTANCE_HOME()+'/Extensions/'+m+'.py'
      if os.path.exists(filepath):
        f = open(filepath, 'rb')
        data = standard.pystr(f.read(),encoding='utf-8')
        f.close()
  elif ob.meta_type == 'Z SQL Method':
    lines = []
    lines.append('<connection>%s</connection>'%ob.connection_id)
    lines.append('<params>%s</params>'%ob.arguments_src)
    lines.append('<max_rows>%i</max_rows>'%ob.max_rows_)
    lines.append('<max_cache>%i</max_cache>'%ob.max_cache_)
    lines.append('<cache_time>%i</cache_time>'%ob.cache_time_)
    lines.append(ob.src)
    data = '\n'.join(lines)
  return data
Beispiel #2
0
def createBlobField(self, objtype, file=b''):
  if standard.is_bytes(file):
    blob = uploadBlobField( self, objtype, file)
  elif isinstance(file, dict):
    data = file.get( 'data', '')
    if standard.is_str(data):
      data = standard.pybytes(data,'utf-8')
      data = standard.PyBytesIO( data)
    blob = uploadBlobField( self, objtype, data, file.get('filename', ''))
    if file.get('content_type'):
      blob.content_type = file.get('content_type')
  else:
    blob = uploadBlobField( self, objtype, file, file.filename)
  return blob
Beispiel #3
0
    def parse(self, input, root=None, bInRootTag=0):
        """ Builder.parse """

        # prepare builder
        self.oRootTag = None
        self.oCurrNode = None
        self.bInCData = False
        if bInRootTag:
            self.oCurrNode = root

        # create parser object
        p = pyexpat.ParserCreate()

        # connect parser object with handler methods
        p.StartElementHandler = self.OnStartElement
        p.EndElementHandler = self.OnEndElement
        p.CharacterDataHandler = self.OnCharacterData
        p.StartCdataSectionHandler = self.OnStartCData
        p.EndCdataSectionHandler = self.OnEndCData
        p.ProcessingInstructionHandler = self.OnProcessingInstruction
        p.CommentHandler = self.OnComment
        p.StartNamespaceDeclHandler = self.OnStartNamespaceDecl
        p.EndNamespaceDeclHandler = self.OnEndNamespaceDecl

        #### parsing ####
        if standard.is_bytes(input):
            # input is a string!
            rv = p.Parse(input, 1)
        else:
            # input is a file object!
            while True:

                v = input.read(self.iBufferSize)
                if v == "":
                    rv = 1
                    break

                rv = p.Parse(v, 0)
                if not rv:
                    break

        # raise parser exception
        if not rv:
            raise ParseError(
                '%s at line %s' %
                (pyexpat.ErrorString(p.ErrorCode), p.ErrorLineNumber))
        ####

        return root
Beispiel #4
0
    def parse(self, input):
      """ XmlAttrBuilder.parse """

      # prepare builder
      self.dValueStack = collections.deque()
      self.dTagStack = collections.deque()

      # create parser object
      p = pyexpat.ParserCreate()

      # connect parser object with handler methods
      p.StartElementHandler = self.OnStartElement
      p.EndElementHandler = self.OnEndElement
      p.CharacterDataHandler = self.OnCharacterData
      p.StartCdataSectionHandler = self.OnStartCData
      p.EndCdataSectionHandler = self.OnEndCData
      p.ProcessingInstructionHandler = self.OnProcessingInstruction
      p.CommentHandler = self.OnComment
      p.StartNamespaceDeclHandler = self.OnStartNamespaceDecl
      p.EndNamespaceDeclHandler = self.OnEndNamespaceDecl

      #### parsing ####
      if standard.is_bytes(input):
        # input is a string!
        rv = p.Parse(input, 1)
      else:
        # input is a file object!
        while True:

          v = input.read(self.iBufferSize)
          if len(v) == 0:
            rv = 1
            break

          rv = p.Parse(v, 0)
          if not rv:
            break

      # raise parser exception
      if not rv:
        raise ParseError('%s at line %s' % (pyexpat.ErrorString(p.ErrorCode), p.ErrorLineNumber))

      return self.dValueStack.pop()
Beispiel #5
0
def toCdata(self, s, xhtml=False):
  rtn = ''

  # Return Text (HTML) in CDATA as XHTML.
  from Products.zms import _filtermanager
  processId = 'tidy'
  if not xhtml \
     and self.getConfProperty('ZMS.export.xml.tidy', 0) \
     and processId in self.getProcessIds():

    # Create temporary folder.
    folder = tempfile.mktemp()
    os.mkdir(folder)

    # Save <HTML> to file.
    filename = _fileutil.getOSPath('%s/xhtml.html' % folder)
    _fileutil.exportObj(s, filename)

    # Call <HTML>Tidy
    processOb = self.getProcess(processId)
    command = processOb.get('command')
    if command.find('{trans}') >= 0:
      trans = _fileutil.getOSPath(package_home(globals()) + '/conf/xsl/tidy.html2xhtml.conf')
      command = command.replace('{trans}', trans)
    filename = _filtermanager.processCommand(self, filename, command)

    # Read <XHTML> from file.
    f = open(htmfilename, 'rb')
    rtn = f.read().strip()
    f.close()

    # Read Error-Log from file.
    f = open(logfilename, 'rb')
    log = f.read().strip()
    f.close()

    # Remove temporary files.
    _fileutil.remove(folder, deep=1)

    # Process <XHTML>.
    prefix = '<p>'
    if s[:len(prefix)] != prefix and rtn[:len(prefix)] == prefix:
      rtn = rtn[len(prefix):]
      suffix = '</p>'
      if s[-len(suffix):] != suffix and rtn[-len(suffix):] == suffix:
        rtn = rtn[:-len(suffix)]
    f.close()

    # Process Error-Log.
    if log.find('0 errors') < 0:
      rtn += '<!-- ' + log + '-->'

  # Return Text.
  elif standard.is_str(s) and s.find(' ') < 0 and s.find('<') < 0 and s.find('&') < 0:
    rtn = s

  # Return Text in CDATA.
  elif s is not None:
    if standard.is_bytes(s):
      s = standard.pystr(s)
    # Hack for invalid characters
    s = s.replace(chr(30), '')
    # Hack for nested CDATA
    s = re.compile(r'\<\!\[CDATA\[(.*?)\]\]\>').sub(r'<!{CDATA{\1}}>', s)
    # Wrap with CDATA
    rtn = '<![CDATA[%s]]>' % s

  # Return.
  return rtn