source: ZMS/trunk/Extensions/urls_xml.py @ 1656

Revision 1656, 10.8 KB checked in by fhoffmann, 8 months ago (diff)

applied fix to xml-sitemap (req. by xm)

Line 
1"""
2Add External Method with the following option:
3
4'Id':       urls.xml
5'Title':    Mirror-Manager
6'Module':   zms.urls_xml
7'Function': manage_getMirrorURLs
8
9Request-Params:
10DEBUG                debug-mode
11EXPORT_RESOURCE_ZMS  export files from /++resource++zms_/jquery
12"""
13#
14# Copyright 2008 {xmachina GmbH. All rights reserved.
15# xmachina. Use is subject to license terms.
16#
17# $Id: urls_xml.py 13940 2010-06-28 07:45:47Z vy $
18#
19
20import Products.zms._blobfields
21import Products.zms._globals
22import urllib
23
24def guess_content_type( filename, default='application/octet-stream'):
25    content_type = default
26    if filename.endswith('.gif'):
27      content_type = 'image/gif'
28    elif filename.endswith('.jpg'):
29      content_type = 'image/jpeg'
30    elif filename.endswith('.png'):
31      content_type = 'image/png'
32    elif filename.endswith('.css'):
33      content_type = 'text/css'
34    elif filename.endswith('.js'):
35      content_type = 'text/javascript'
36    elif filename.endswith('.html'):
37      content_type = 'text/html'
38    return content_type
39
40# see _blobfields.py::recurse_downloadRessources
41def recurseRessources(self, base_path, REQUEST, incl_embedded, RESPONSE):
42    try:
43      if REQUEST.get('DEBUG'):
44        RESPONSE.write('<!-- DEBUG recurseRessources(%s, %s, REQUEST, incl_embedded, RESPONSE) -->\n'%(base_path,self.id))
45    except:
46        RESPONSE.write('<!-- ERROR exception -->\n')
47   
48    root = getattr( self, '__root__', None)
49    if root is not None or self.meta_type == 'ZMSTrashcan':
50      return
51    ob = self
52    if ob.meta_type != 'ZMS':
53      base_path += self.id + '/'
54    if ob.meta_type == 'ZMSLinkElement' and ob.isEmbedded( REQUEST) and incl_embedded:
55      ob = ob.getRefObj()
56      # xm-cw 0018774: urls_xml.py scheitert an cms/pub_ra und cms/pub_psa...
57      return
58    if ob is None:
59      return
60   
61    l = []
62    for lang in ob.getLangIds():
63      req = {'lang':lang}
64      if ob.isVisible(req):
65        # Attributes.
66        keys = ob.getObjAttrs().keys()
67        for key in keys:
68          obj_attr = ob.getObjAttr(key)
69          datatype = obj_attr['datatype_key']
70          if datatype in Products.zms._globals.DT_BLOBS:
71            try:
72              if obj_attr['multilang']==1 or lang==ob.getPrimaryLanguage() or (obj_attr['multilang']==0 and lang!=ob.getPrimaryLanguage()):
73                blob = ob.getObjProperty(key,req)
74                if blob is not None:
75                  filename = blob.getHref(req)
76                  filename = filename[filename.index(base_path):]
77                  filename = filename.replace('\\','/')
78                  if filename not in l:
79                    l.extend([filename,blob.getContentType()])
80            except:
81              s = Products.zms._globals.writeError(ob,"[recurse_downloadRessources]: Can't export %s"%key)
82              RESPONSE.write('<!-- ERROR %s -->\n'%(s))
83              raise
84          elif datatype == Products.zms._globals.DT_LIST and obj_attr.get('type') in ['image','file']:
85            try:
86              if obj_attr['multilang']==1 or lang==ob.getPrimaryLanguage() or (obj_attr['multilang']==0 and lang!=ob.getPrimaryLanguage()):
87                obj_vers = ob.getObjVersion(req)
88                blobs = ob._getObjAttrValue(obj_attr,obj_vers,lang)
89                i = 0
90                for blob in blobs:
91                  filename = blob.getFilename()
92                  filename = '%s@%i/%s'%(base_path,i,filename)
93                  filename = filename.replace('\\','/')
94                  if filename not in l:
95                    l.extend([filename,blob.getContentType()])
96                  i += 1
97            except:
98              s = Products.zms._globals.writeError(ob,"[recurse_downloadRessources]: Can't export %s"%key)
99              RESPONSE.write('<!-- ERROR %s -->\n'%(s))
100              raise
101    for i in range(len(l)/2):
102      fn = l[i*2]
103      ct = l[i*2+1]
104      RESPONSE.write('<url content_type="%s"><![CDATA[%s]]></url>\n'%(ct,fn))
105   
106    # Process children.
107    for child in ob.getChildNodes():
108        # Return list of ressources.
109        recurseRessources( child, base_path, REQUEST, incl_embedded, RESPONSE)
110   
111    return
112
113
114# see _exportable.py::recurse_downloadHtmlPages
115def recurseHtmlPages(self, obj, path, lang, REQUEST, RESPONSE):
116    try:
117      if REQUEST.get('DEBUG'):
118        RESPONSE.write('<!-- DEBUG recurseHtmlPages(self, obj, %s, %s, REQUEST, RESPONSE) -->\n'%(path, lang))
119        RESPONSE.write('<!-- DEBUG isVisible %s -->\n'%(obj.isVisible(REQUEST)))
120    except:
121        RESPONSE.write('<!-- ERROR exception -->\n')
122   
123    if obj.isVisible( REQUEST):
124     
125      level = obj.getLevel()
126     
127      try:
128        dctOp = getattr(self,'urls.dctOp')() # Hook for custom pages 'urls.dctOp': return dict.
129      except:
130        dctOp = {'index':'','sitemap':'sitemap','index_print':'print'}
131
132      # BO 0024404: ZMS-Erweiterungen News-Archiv -> Hook to include attr_stage4_urls Porperty into dctOp
133      if obj.getObjProperty('attr_stage4_urls',REQUEST):
134
135          stage4_urls = obj.getObjProperty('attr_stage4_urls',REQUEST).split(',')
136
137          for s4_url in stage4_urls:
138
139              s4_url = s4_url.strip()
140              dctOp.update({str(s4_url):str(s4_url)})
141      # EO 0024404
142         
143      for key in dctOp.keys():
144          if key == 'sitemap':
145              pageext = '.html'
146          else:
147              pageext = obj.getPageExt( REQUEST)
148          filename = '%s/%s_%s%s'%( path, key, lang, pageext)
149          content_type = 'text/html'
150          RESPONSE.write('<url lang="%s" content_type="%s"><![CDATA[%s]]></url>\n'%(lang,content_type,filename))
151         
152          # Process DTML-methods of meta-objects.
153          for metadictAttrId in self.getMetaobjAttrIds( obj.meta_id):
154            try:
155              metadictAttr = self.getMetaobjAttr( obj.meta_id, metadictAttrId)
156              if metadictAttr is not None and metadictAttr['meta_type'] and metadictAttr['type'] in self.getMetaobjIds( sort=0):
157                metaObj = self.getMetaobj( metadictAttr['type'])
158                if metaObj['type'] == 'ZMSResource':
159                  for metadictObj in obj.getObjChildren( metadictAttr['id'], REQUEST):
160                    for metaObjAttr in metaObj['attrs']:
161                      if metaObjAttr['type'] in [ 'DTML Document', 'DTML Method']:
162                        filename = '%s/%s'%( path, metaObjAttr['id'])
163                        RESPONSE.write('<url><![CDATA[%s]]></url>\n'%(filename))
164            except:
165              s = Products.zms._globals.writeError( self, "[recurse_downloadHtmlPages]: Can't process DTML-method '%s' of meta-object"%metadictAttr)
166              RESPONSE.write('<!-- ERROR %s -->\n'%(s))
167              raise
168   
169    # Process children.
170    for child in obj.filteredChildNodes(REQUEST,self.PAGES):
171        recurseHtmlPages(self,child,'%s/%s'%(path,child.getDeclId(REQUEST)),lang, REQUEST, RESPONSE)
172
173
174# see _exportable.py::exportFolder
175def recurseFolder(self, root, path, id, REQUEST, RESPONSE):
176    try:
177      if REQUEST.get('DEBUG'):
178        RESPONSE.write('<!-- DEBUG recurseFolder(%s, %s, %s, %s, REQUEST, RESPONSE) -->\n'%(self, "root", path, id))
179    except:
180        RESPONSE.write('<!-- ERROR exception -->\n')
181   
182    if hasattr(root,id):
183        folder = getattr(root,id)
184        if folder.meta_type == 'Folder':
185            for ob in folder.objectValues():
186                if ob.meta_type == 'Folder':
187                    ob_id = ob.id
188                    recurseFolder(self,ob,'%s/%s'%(path,id), ob_id, REQUEST, RESPONSE)
189                else:
190                    try:
191                      ob_id = ob.id()
192                    except:
193                      ob_id = str(ob.id)
194                    #if ob.meta_type in [ 'DTML Document', 'DTML Method']:
195                    #    ob = Products.zms._globals.dt_html(self,ob.raw,REQUEST)
196                    content_type = getattr(ob,'content_type','application/octet-stream')
197                    if content_type == 'application/octet-stream':
198                      content_type = guess_content_type( ob_id)
199                    RESPONSE.write('<url content_type="%s"><![CDATA[%s/%s/%s]]></url>\n'%(content_type,path,id,ob_id))
200
201
202# see _exportable::exportMetaobjManager
203def recurseMetaobjManager(self, root, path, REQUEST, RESPONSE):
204  try:
205    if REQUEST.get('DEBUG'):
206      RESPONSE.write('<!-- DEBUG recurseMetaobjManager(%s, %s, %s) -->\n'%(self, "root", path))
207  except:
208      RESPONSE.write('<!-- ERROR exception -->\n')
209 
210  id = 'metaobj_manager'
211  if hasattr(root,id):
212    folder = getattr(root,id)
213    for ob in folder.objectValues(['File']):
214      try:
215        ob_id = ob.id()
216      except:
217        ob_id = str(ob.id)
218      content_type = getattr(ob,'content_type','application/octet-stream')
219      if content_type == 'application/octet-stream':
220        content_type = guess_content_type( ob_id)
221      RESPONSE.write('<url content_type="%s"><![CDATA[%s/%s/%s]]></url>\n'%(content_type,path,id,ob_id))
222
223def manage_getMirrorURLs(self, REQUEST, RESPONSE):
224    lang = REQUEST.get('lang',self.getPrimaryLanguage())
225    REQUEST.set('lang',lang)
226    RESPONSE.write('<?xml version="1.0" encoding="utf-8"?>\n');
227    RESPONSE.write('<urls base="%s">\n'%(self.getHome().absolute_url()));
228   
229    # @see _exportable.py::exportRessources, etc.
230    folder = '/misc_/zms'
231    for ob_id in self.misc_.zms._d.keys():
232      if ob_id.find('.') > 0:
233        content_type = guess_content_type( ob_id)
234        RESPONSE.write('<url content_type="%s"><![CDATA[%s/%s]]></url>\n'%(content_type,folder,ob_id))
235   
236    # plugins
237    if REQUEST.get('EXPORT_RESOURCE_ZMS'):
238      resourcepath = '/++resource++zms_/jquery'
239      basepath = self.localfs_package_home()+'/plugins/www/jquery'
240      for file in self.localfs_readPath(basepath,recursive=True):
241        if file['local_filename'].find('/.svn/') < 0:
242          filepath = resourcepath+file['local_filename'][len(basepath):].replace('\\','/')
243          filename = file['filename']
244          content_type = guess_content_type( filename)
245          RESPONSE.write('<url content_type="%s"><![CDATA[%s]]></url>\n'%(content_type,filepath))
246    else:
247      # @see headScript
248      RESPONSE.write('<url content_type="text/javascript"><![CDATA[%s]]></url>\n'%self.getConfProperty('jquery.plugin.version','/++resource++zms_/jquery/plugin/jquery.plugin.js'))
249      RESPONSE.write('<url content_type="text/javascript"><![CDATA[%s]]></url>\n'%self.getConfProperty('jquery.plugin.extensions','/++resource++zms_/jquery/plugin/jquery.plugin.extensions.js'))
250   
251    for id in [ 'common', 'instance']:
252        recurseFolder( self, self.getHome(), "", id, REQUEST, RESPONSE)
253
254    recurseMetaobjManager( self, self, "/content", REQUEST, RESPONSE)
255    recurseRessources(self, "/content/", REQUEST, True, RESPONSE)
256    for lang in self.getLangIds():
257      REQUEST.set('lang',lang)
258      REQUEST.set('preview',None)
259      recurseHtmlPages(self, self, "/content", lang, REQUEST, RESPONSE)
260   
261    RESPONSE.write('</urls>\n');
262    return
263
264# eof
Note: See TracBrowser for help on using the repository browser.