<?xml version="1.0" encoding="utf-8" ?>

<list>
  <item type="dictionary">
    <dictionary>
      <item key="data"><![CDATA[## Script (Python) "manage_sitemapxml"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=
##title=*** DO NOT DELETE OR MODIFY ***
##
# Author:   SNTL Publishing GmbH & Co. KG
# WWW:      http://www.sntl-publishing.com
# Date:     26.07.2020
# Version:  4.0.1
# Comments: Create a multiligual static Google compliant sitemap for FTP-/HTML-Export
#           Note: Uses the "IP / Domain" under Configuration to set the URL path,
#           make sure to set that correctly (w/o http://)!
#           float-string conversion for prio-attr
#           isResource() excluded
# HINT:     Set Variable URL1 '/content/' | '/' depending on Webserver-config
##########################################################################################

URL1 = '/' #or '/content/' depending on Webserver-config

request = container.REQUEST
response =  request.response

zms = context.content
request.set('preview',None)
standard_html_request = zms.f_standard_html_request(request)

domain = zms.getConfProperty('ASP.ip_or_domain')
if domain == None:
    domain = ''
protocol = zms.getConfProperty('ASP.protocol')
if protocol == '' or protocol == None:
    protocol = 'http'
loc = ''
nodes = []
node_count = 0
sitemap_xml = ''
urlitems = []

def get_all_date_attrs(node):
	list_of_dates = []
	list_of_dates.append(node.getLangFmtDate(node.attr('change_dt'),'eng','%Y-%m-%d'))
	list_of_dates.append(node.getLangFmtDate(node.attr('work_dt'),'eng','%Y-%m-%d'))
	list_of_dates.append(node.getLangFmtDate(node.attr('created_dt'),'eng','%Y-%m-%d'))
	list_of_dates = [ d for d in list_of_dates if d != 'None' ]
	return list_of_dates

def get_lastmod(node,request):
	list_of_dates = []
	list_of_dates.extend(get_all_date_attrs(node))
	subnodes = node.filteredChildNodes(request,zms.PAGEELEMENTS)
	for node in subnodes:
		list_of_dates.extend(get_all_date_attrs(node))
	list_of_dates.sort(reverse=True)
	return list_of_dates[0]

# ############ XML-TEMPLATE-1 ##################
urlset_tmpl = """<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<!-- Generated by ZMS3 for %s Public Content-Nodes -->
%s
</urlset>"""

# ############ XML-TEMPLATE-2 ##################
urlitem_tmpl = """
		<url>
			<!-- %s. [%s] %s -->
			<loc>%s</loc>
			<lastmod>%s</lastmod>
			<changefreq>%s</changefreq>
			<priority>%s</priority>
		</url>"""
# ##############################################

# ITERATE TREE FOR EVERY LANGUAGE
for lang in zms.getLanguages(request):
	request.set('lang',lang)
	nodes = [zms]
	nodes.extend(zms.filteredTreeNodes(request,[zms.PAGES,'ZMSFile','downloadfile','file'],max_len=None))
	for node in nodes:
		path = node.breadcrumbs_obj_path(portalMaster=False)
		forbidden_nodes = [ ob for ob in path if not ( ob.hasPublicAccess() and ob.isActive(request) ) ]
		# AVOID forbidden nodes and deep linking induced url repeating
		if not forbidden_nodes and ( loc != node.getHref2IndexHtml(request) ):
			node_count+=1
			title = node.attr('titlealt')
			loc = node.getHref2IndexHtml(request)
			# if loc.find(domain)<0  and loc.find('localhost')<0 and loc.find('127.0.0.1')<0 and loc.find('content')>0:
			if loc.find(domain)<0  and loc.find('content')>0:
				loc = 'https://' + domain + URL1 + node.getHref2IndexHtml(request).split('/content/')[1]
			lastmod = get_lastmod(node,request)
			changefreq = 'monthly'
			priority = node.attr('attr_bot_priority')!='' and node.attr('attr_bot_priority') or '0.5'
			urlitem = urlitem_tmpl%(node_count,request.get('lang','n.a.'),title,loc,lastmod,changefreq,priority)
			urlitems.append(urlitem)
			#	urlitems.append('		<!-- ERROR: %s -->'%(node.getHref2IndexHtml(request)))

sitemap_xml = urlset_tmpl%(node_count,'\n'.join(urlitems))

root_node = zms.getHome()
# Check whether file object 'sitemap.xml' alread exists:
if len([f for f in root_node.objectValues('File') if f.getId()=='sitemap.xml'])==0:
	root_node.manage_addFile('sitemap.xml',title='SITEMAP',content_type='text/xml')
f = [f for f in root_node.objectValues('File') if f.getId()=='sitemap.xml'][0]
f.manage_edit(title='SITEMAP', content_type='text/xml',precondition='', filedata=sitemap_xml)

# FEEDBACK
request.set('message','<a href="%s" target="_blank">sitemap.xml</a> successfully generated on %s visible pages'%(f.absolute_url(),node_count))
return request.get('message','ERROR: No Message')

# TEST
# response.setHeader('content-type','text/xml; charset=utf-8')
# return sitemap_xml
]]>
      </item>
      <item key="description"></item>
      <item key="execution" type="int">1</item>
      <item key="icon_clazz"><![CDATA[icon-sitemap fab fa-google]]></item>
      <item key="id">manage_sitemapxml</item>
      <item key="meta_type"><![CDATA[Script (Python)]]></item>
      <item key="meta_types" type="list">
        <list>
          <item>ZMS</item>
        </list>
      </item>
      <item key="name"><![CDATA[Generate Google Sitemap]]></item>
      <item key="revision">4.0.1</item>
      <item key="roles" type="list">
        <list>
          <item>ZMSAdministrator</item>
          <item>ZMSEditor</item>
        </list>
      </item>
      <item key="title"><![CDATA[Generate sitemap.xml for Google]]></item>
    </dictionary>
  </item>
</list>