File:  [Repository] / ECHO_content / ECHO_collection.py
Revision 1.91: download - view: text, annotated - select for diffs - revision graph
Thu May 27 09:31:25 2004 UTC (19 years, 11 months ago) by dwinter
Branches: MAIN
CVS tags: HEAD
resourceid added bei creating a resource

"""New version of the product started February, 8th. Without scientific classification, use content-type for further classification."""
"""Echo collection provides the classes for the ECHO content web-site.

class ECHO_collection is the basis class for an ECHO collection.

class ECHO_resource contains information on ECHO resources (e.g. an Display environment for Metadata

class ECHO_externalLink contains information on externalLinks


"""
import string
import re
import os
import OFS.Image
from types import *
from OFS.Image import Image
from Globals import DTMLFile
from OFS.Folder import Folder
from OFS.SimpleItem import SimpleItem
from AccessControl import ClassSecurityInfo
from AccessControl.User import UserFolder
from Globals import InitializeClass
from Globals import DTMLFile
import Globals
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
from Products.PageTemplates.PageTemplate import PageTemplate
from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate
from Globals import Persistent, package_home
from Acquisition import Implicit
from ECHO_helpers import displayTypes


try:
	from psycopg import libpq
except:
	try:
		from pyPgSQL import libpq
	except:
		print "ECHO_collection: Warning - No libpq imported!"
		
import xml.dom.minidom

import urllib
import xml.dom.minidom
from ECHO_graphicalOverview import javaHandler,javaScriptMain
import ECHO_helpers

#List of different types for the graphical linking viewer
viewClassificationListMaster=['view point','area']

def checkDiffs(self,metadict):
	    """check differences"""

	    

    
	    def NoneToEmpty(obj):
		    if obj:
			    return obj
		    else:
			    return ""

	    
	    
	    diffs={}
	    
	    tags=self.findTagsFromMapping(self.contentType)
	    self.referencetypes=tags[2]
	    self.fields=tags[3]
	    
    
	    for field in tags[1]:
		    try:
			    if (NoneToEmpty(self.getFieldValue(self.getFieldTag(tags,field)))==metadict[self.getFieldTag(tags,field)]):
				    diffs[self.getFieldTag(tags,field)]=1
			    else:
				    
				    diffs[self.getFieldTag(tags,field)]=0
		    except:
			    diffs[self.getFieldTag(tags,field)]=0
			    
	    return diffs
    
def content_html(self,type):
        """template fuer content"""
        #templates = self.ZopeFind(self.aq_parent,obj_ids=[type+"_template"])
        #
        #if templates:
        #    return templates[0][1]()

        try:
            obj=getattr(self,type+"_template")
            return obj()
        except:
            pt=PageTemplateFile('Products/ECHO_content/zpt/ECHO_%s_template_standard.zpt'%type).__of__(self)
            pt.content_type="text/html"
            return pt()
    
def toList(field):
    """Einzelfeld in Liste umwandeln"""
    if type(field)==StringType:
        return [field]
    else:
        return field
    
def getText(nodelist):

    rc = ""
    for node in nodelist:
    	if node.nodeType == node.TEXT_NODE:
           rc = rc + node.data
    return rc


def sendFile(self, filename, type):
    """sends an object or a local file (in the product) as response"""
    paths = filename.split('/')
    object = self
    # look for an object called filename
    for path in paths:
        if hasattr(object, path):
	    object = getattr(object, path)
	else:
	    object = None
	    break
    if object:
	# if the object exists then send it
	return object.index_html(self.REQUEST.REQUEST, self.REQUEST.RESPONSE)
    else:
	# send a local file with the given content-type
	fn = os.path.join(package_home(globals()), filename)
	self.REQUEST.RESPONSE.setHeader("Content-Type", type)
	self.REQUEST.RESPONSE.write(file(fn).read())
    return

class BrowserCheck:
    """check the browsers request to find out the browser type"""
    
    def __init__(self, zope):
	self.ua = zope.REQUEST.get_header("HTTP_USER_AGENT")
	self.isN4 = (string.find(self.ua, 'Mozilla/4.') > -1) and (string.find(self.ua, 'MSIE') < 0)
	self.isIE = string.find(self.ua, 'MSIE') > -1
	self.nav = self.ua[string.find(self.ua, '('):]
	ie = string.split(self.nav, "; ")[1]
	if string.find(ie, "MSIE") > -1:
	    self.versIE = string.split(ie, " ")[1]
	self.isMac = string.find(self.ua, 'Macintosh') > -1
	self.isWin = string.find(self.ua, 'Windows') > -1
	self.isIEWin = self.isIE and self.isWin
	self.isIEMac = self.isIE and self.isMac


def writeMetadata(url,metadict):
	"""Einlesen der Metadaten und und erstellen des geaenderten XML file"""

	try:
		geturl=""
		for line in urllib.urlopen(url).readlines():
			geturl=geturl+line
        
        
	except:
		return (None,"Cannot open: "+url)

	try:
		dom=xml.dom.minidom.parseString(geturl)
	except:
		return (None,"Cannot parse: "+url+"<br>"+geturl)

	metanodes=dom.getElementsByTagName('bib')

	if not metanodes:
		metanodes=dom.getElementsByTagName('archimedes')

	metanode=metanodes[0]

	for metaData in metadict.keys():
		
		try:
			nodeOld=metanode.getElementsByTagName(metaData)
		except:
			nodeOld=None
			
		if nodeOld:
			metanode.removeChild(nodeOld[0]).unlink()
		else:
			# try also old writing rule - instead of _:
			try:
				nodeOld=metanode.getElementsByTagName(re.sub('_','-',metaData))
			except:
				nodeOld=None
				
			if nodeOld:
				metanode.removeChild(nodeOld[0]).unlink()

		metanodeneu=dom.createElement(metaData)
		try:
			metanodetext=dom.createTextNode(unicode(metadict[metaData],"utf-8"))
		except:
			metanodetext=dom.createTextNode(metadict[metaData].encode('utf-8'))
		metanodeneu.appendChild(metanodetext)
		metanode.appendChild(metanodeneu)

	
	return dom.toxml().encode('utf-8')

	
	
def readMetadata(url):
    """Methode zum Auslesen der Metadateninformation zu einer Resource
    Vorerst noch Typ bib"""
    
    metadict={}
    try:
        geturl=""
        for line in urllib.urlopen(url).readlines():
            geturl=geturl+line
        
        
    except:
        return (None,"Cannot open: "+url)

    try:
        dom=xml.dom.minidom.parseString(geturl)
    except:
        return (None,"Cannot parse: "+url+"<br>"+geturl)

    metanode=dom.getElementsByTagName('bib')
    metadict['bib_type']='Book'
    if len(metanode)==0:
        metanode=dom.getElementsByTagName('archimedes')
        metadict['bib_type']='Archimedes'
        
        
    if not len(metanode)==0:    
        metacontent=metanode[0].childNodes
    
        try:
            metadict['bib_type']=getText(dom.getElementsByTagName('bib')[0].attributes['type'].childNodes)
        except:
            """nothing"""
        
        for node in metacontent:
            try:
		    metadict[re.sub('-','_',node.tagName.lower())]=urllib.unquote(getText(node.childNodes))
            except:
                """nothing"""


    return metadict,""
    

def setECHO_collectionInformation(self,title,label,description,contentType,responsible,credits,weight,coordstrs,viewClassification=""):

        """Allegemeine Informationen zu einer ECHO Collection"""

        self.viewClassification=viewClassification

        self.label = label
        self.title=title
        self.description=description
        self.contentType=contentType
        self.responsible=responsible
        self.credits=toList(credits)
        self.weight=weight

        coords=[]
        #coordinates of for rectangles

        
        if coordstrs:
            for coordstr in coordstrs:
        
                try:
                    temco=coordstr.split(",")
                except:
                    temco=[]
        
                coords.append(temco)


        self.coords=coords[0:]
            

class scientificClassification(SimpleItem,Persistent,Implicit):
    """outdated will be deleeted in the next versions: subclass"""
    security=ClassSecurityInfo()
    
    def __init__(self,context,science,practice):
        self.context=context
        self.science=science
        self.practice=practice
        self.id="scientific_Classification"
        
    security.declarePublic('get_context')
    def get_context(self):
        return self.context
    
    security.declarePublic('get_science')
    def get_science(self):
        return self.science
        
    security.declarePublic('get_practice')
    def get_practice(self):
        return self.practice
    
                
class scientificInformation(Folder,Persistent,Implicit):
    """outdated will be deleted in the next versions: subclass scientificInformation"""
    security=ClassSecurityInfo()
    
    
    
    def __init__(self,source_type,period):

        self.id="scientific_Information"
        self.source_type=source_type
        self.period=period
        


    security.declarePublic('get_source_type')
    def get_source_type(self):
        return self.source_type
    
    security.declarePublic('get_period')
    def get_period(self):
        return self.period

class ECHO_layoutTemplate(ZopePageTemplate):
    """Create a layout Template for different purposes"""

    meta_type="ECHO_layoutTemplate"

    def __init__(self, id, text=None, content_type=None,EchoType=None):
        self.id = str(id)



        self.ZBindings_edit(self._default_bindings)
        if text is None:
            self._default_content_fn = os.path.join(package_home(globals()),
                                               'zpt/ECHO_%s_template_standard.zpt'%EchoType)
            text = open(self._default_content_fn).read()
        self.pt_edit(text, content_type)

    
        """change form"""


def manage_addECHO_layoutTemplateForm(self):
    """Form for adding"""
    pt=PageTemplateFile('Products/ECHO_content/zpt/AddECHO_layoutTemplate.zpt').__of__(self)
    return pt()

from urllib import quote


def manage_addECHO_layoutTemplate(self, EchoType,title=None,REQUEST=None):
    "Add a Page Template with optional file content."
    if type(EchoType)==StringType:
        EchoTypes=[EchoType]
    else:
        EchoTypes=EchoType
        
    for singleType in EchoTypes:

        id = str(singleType)+"_template"
        if REQUEST is None:
            self._setObject(id, ECHO_layoutTemplate(id, text,EchoType=singleType))
            ob = getattr(self, id)
            
            if title:
                ob.pt_setTitle(title)
            return ob
        else:
            file = REQUEST.form.get('file')
            headers = getattr(file, 'headers', None)
            if headers is None or not file.filename:
                zpt = ECHO_layoutTemplate(id,EchoType=singleType)
            else:
                zpt = ECHO_layoutTemplate(id, file, headers.get('content_type'))

            self._setObject(id, zpt)
            ob = getattr(self, id)
            if title:
                ob.pt_setTitle(title)

            try:
                u = self.DestinationURL()
            except AttributeError:
                u = REQUEST['URL1']

            
    REQUEST.RESPONSE.redirect(u+'/manage_main')
    return ''

class ECHO_resource(Folder,Persistent):
    """ECHO Ressource"""
    meta_type='ECHO_resource'

    viewClassificationList=viewClassificationListMaster

    getSubCols = ECHO_helpers.getSubCols
    def getTitle(self):
	"""title"""
	return self.title.encode('utf-8') 

    def getLabel(self):
	"""title"""
	return self.label.encode('utf-8') 

    def content_html(self):
        """template fuer content"""
        return content_html(self,'resource')
    
    def getViewClassification(self):
        if hasattr(self,'viewClassification'):
            return self.viewClassification
        else:
            return ""

    def getFullTextXML(self,noredirect=None):
	    """getFullTextXML; gives the FullText as an XML Document, and <error></error> if somthing goes wrong."""
	    try:
		    fh=urllib.urlopen(self.metalink)
		    dom=xml.dom.minidom.parse(fh)
		    texttools=dom.getElementsByTagName('texttool')
		    text=texttools[0].getElementsByTagName('text')
		    texturl=getText(text[0].childNodes)
		    self.REQUEST.RESPONSE.setHeader('Content-Type','text/xml')
		    if not noredirect:
			    self.REQUEST.RESPONSE.redirect(texturl)
		    else:
			    return texturl
	    except:

		    if not noredirect:
			    self.REQUEST.RESPONSE.setHeader('Content-Type','text/xml')
			    self.REQUEST.RESPONSE.write("<error>no fulltext available</error>")
		    else:
			    return "<error>no fulltext available</error>"
    
    def getCredits(self):
        """Ausgabe der credits"""
        if self.credits:
            return self.credits
        else:
            return []
    
    def __init__(self,id,link,metalink,resourceID,title,label,description,contentType,renderingType,responsible,credits,weight,coords):

        self.id = id
        """Festlegen der ID"""
        
        self.label = label
        self.link= link
        self.metalink=metalink
        self.title=title
        self.weight=weight
        self.credits=toList(credits)
        self.description=description
        self.contentType=contentType
	self.renderingType=renderingType
        self.responsible=responsible
        self.resourceID=resourceID
	
        if coords:
            coordsnew=[ string.split(x,",") for x in coords]
        else:
            coordsnew=[]
        
        self.coords=coordsnew


    def getCoords(self):
	    """gibt coordinaten als String zurück und löscht zugleich einträge die keine Koordinaten sind, letzteres zur korrektur der Eingabe der alten version"""
	    retList=[]
	    if hasattr(self,'coords'):
		    for x in self.coords:
			if len(x)>1:
				retList.append(string.join(x,","))
	    return retList

    

    def getContentType(self):
	    try:
		    return self.contentType
	    except:
		    return ""

    def getCopyrightType(self):
	    try:
		    return self.copyrightType
	    except:
		    return ""

    def getRenderingType(self):
	    try:
		    return self.renderingType
	    except:
		    return ""

    def ECHO_resource_config(self):
        """Main configuration"""

        if not hasattr(self,'weight'):
            self.weight=""

        pt=PageTemplateFile('Products/ECHO_content/zpt/ChangeECHO_resource.zpt').__of__(self)
        return pt()
    

    def ECHO_resource_config_main(self):
        """Main configuration"""

        if not hasattr(self,'weight'):
            self.weight=""

        pt=PageTemplateFile('Products/ECHO_content/zpt/ChangeECHO_resource_main.zpt').__of__(self)
        return pt()

    def ECHO_resource_config_coords(self):
        """Coords configuration """

        pt=PageTemplateFile('Products/ECHO_content/zpt/ChangeECHO_resource_coords.zpt').__of__(self)
        return pt()

    def ECHO_resource_config_credits(self):
        """Main configuration"""

        pt=PageTemplateFile('Products/ECHO_content/zpt/ChangeECHO_resource_credits.zpt').__of__(self)
        return pt()

    def ECHO_resource_config_metadata(self):
        """Main configuration"""

	if (hasattr(self,'metadata')) and not (hasattr(self,'metaDataHash')):
		self.metaDataHash={}
		self.contentType=self.bib_type
		for data in self.metadata:
			data_neu=re.sub('-','_',data)
			self.metaDataHash[data_neu]=getattr(self,data)

	
        pt=PageTemplateFile('Products/ECHO_content/zpt/ChangeECHO_resource_metadata.zpt').__of__(self)
        return pt()


    

    def changeECHO_resource_main(self,metalink,link,title,label,description,contentType,renderingType,weight,resourceID,RESPONSE=None):
        """Änderung der Properties"""
	self.resourceID=resourceID
	self.title=title
	self.label=label
	self.description=description

	self.contentType=contentType
	self.renderingType=renderingType
	self.weight=weight
	
        self.link=link
        self.metalink=metalink
        
        if RESPONSE is not None:
            RESPONSE.redirect('manage_main')


    def changeECHO_resource_coords(self,coords,viewClassification,RESPONSE=None):
        """Änderung der Properties - coords"""

	if type(coords)==StringType:
        	coords=[coords]

       	try:        
        	coordsnew=[ string.split(x,",") for x in coords]
        except:
		coordsnew=[]	

	self.coords=coordsnew[0:]
	self.viewClassification=viewClassification
        
        if RESPONSE is not None:
            RESPONSE.redirect('manage_main')

    def changeECHO_resource_credits(self,credits,responsible,copyrightType,RESPONSE=None):
        """Änderung der Properties"""
	self.credits=credits
	self.responsible=responsible
	self.copyrightType=copyrightType
        
        if RESPONSE is not None:
            RESPONSE.redirect('manage_main')


    def changeECHO_resource_metadata_local(self,RESPONSE=None):
	    """change metadata"""
	    tags=self.findTagsFromMapping(self.contentType)
	    for field in tags[1]:
		    self.metaDataHash[self.getFieldTag(tags,field)]=self.REQUEST.form[self.getFieldTag(tags,field)]
			

	    	    
	    if RESPONSE is not None:
		    RESPONSE.redirect('manage_main')

    def changeECHO_resource_metadata(self,RESPONSE=None):
	    """change metadata"""
	    tags=self.findTagsFromMapping(self.contentType)
	    self.OSAS_meta={}
	    for field in tags[1]:
		    try:
			    self.metaDataHash[self.getFieldTag(tags,field)]=self.REQUEST.form[self.getFieldTag(tags,field)]
			    self.OSAS_meta[self.getFieldTag(tags,field)]=self.REQUEST.form['OSAS_%s'%self.getFieldTag(tags,field)]
		    except:
			    """nothing"""

	    return urllib.urlopen('http://xserve02.mpiwg-berlin.mpg.de:18880/echo_nav/storage/downloadExternalXML?index_meta_url=%s&xml_url=%s'%(self.metalink,self.absolute_url()+'/newMetaXML')).read()
	    
	    if RESPONSE is not None:
		    RESPONSE.redirect('manage_main')


    def getMDValue(self,fieldName):
	    return self.metaDataHash.get(fieldName,'!!NOT USED HERE in Type: %s'%self.contentType)
					 
    def newMetaXML(self):
	    """new index.meta"""
	    self.REQUEST.RESPONSE.setHeader('Content-Type','text/xml')
	    return writeMetadata(self.metalink,self.OSAS_meta)


    def getMetaDataXML(self):
	    """prints out metadata as stored in the echo environment, format is the index.meta format"""
	    self.REQUEST.RESPONSE.setHeader('Content-Type','text/xml')
	    return writeMetadata(self.metalink,self.metaDataHash)

    def changeECHO_resource(self,metalink,link,title,label,description,contentType,responsible,weight,viewClassification="",coords=None,credits=None,RESPONSE=None):
        """Änderung der Properties"""
        
	try:        
        	coordsnew=[ string.split(x,",") for x in coords]
        except:
		coordsnew=[]	
        
        setECHO_collectionInformation(self,title,label,description,contentType,responsible,credits,weight,coordsnew)
	self.viewClassification=viewClassification
        self.coords=coordsnew[0:]
        self.link=link
        self.metalink=metalink
        
        if RESPONSE is not None:
            RESPONSE.redirect('manage_main')
            
            
    manage_options = Folder.manage_options+(
        {'label':'Main Config','action':'ECHO_resource_config_main'},
	{'label':'Change Credits & Copyright','action':'ECHO_resource_config_credits'},
	{'label':'Change Metadata','action':'ECHO_resource_config_metadata'},
	{'label':'Change Coords','action':'ECHO_resource_config_coords'},
	{'label':'Add coords','action':'ECHO_graphicEntry'},
        {'label':'Sync Metadata','action':'ECHO_getResourceMD'},
	)

    def getOverview(self):
        """overview graphics"""
        
        return self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['overview'])[0][1]

    def ECHO_graphicEntry(self):
        """DO nothing"""
        overview = self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['overview'])
        if overview: 
            pt=PageTemplateFile('Products/ECHO_content/zpt/ECHO_draw.zpt').__of__(self)
            return pt()
        else:
            return "NO OVERVIEW GRAPHICS"

    def ECHO_enterCoords(self,coordstr,angle="",RESPONSE=None):
        """Enter coords"""
        coords=self.coords
        temco=coordstr.split(",")
        temco.append(angle)
        coords.append(temco)
        
        self.coords=coords[0:]

        if RESPONSE is not None:
            RESPONSE.redirect('ECHO_graphicEntry')


    def isDefinedInThisSet(self,fields,field):
	    """checks if field is defined in fields"""
	    if (fields[0].has_key(field)) and not (fields[0][field]==""):
		    return 1
	    else:
		  
		    return 0
	    
    def getFieldLabel(self,fields,field):
        """get labels"""
        try:
            ret =fields[0][field]
            if ret == "":
                return field
            else:
                return ret
        except:
            return field



    def getFieldTag(self,fields,field):
        """get labels"""
        try:
            ret =fields[0][field]
            if ret == "":
                return field
            else:
                return ret
        except:
            return field

    
        
    def getFieldValue(self,field):
        """get value"""
	
        try:
	
            ret=self.metaDataHash[field]
            if ret == "":
                return None
            else:
                return ret
        except:
            return None

    def getMetaDataHash(self):
	    """md hash"""
	    return self.metaDataHash
    
    def setFieldValue(self,field,value):
        """get value"""
	
	if not hasattr(self,'metaDataHash'):
		setattr(self,'metaDataHash',{})
	self.metaDataHash[field]=value[0:]
	


    def findLabelsFromMapping(self,referenceType):
        """gib hash mit label -> generic zurueck"""
	#return {},[]

        temp=self.ZopeFind(self.standardMD)

	if referenceType=="":
		referenceType="book"
	
	
        bibdata={}
        retdata={}
	fields=[]
        fieldlist=self.standardMD.fieldList
        
	for referenceTypeF in self.referencetypes:

		if referenceTypeF[1].title.lower() == referenceType.lower():

			try:
				bibdata[referenceTypeF[1].title]=referenceTypeF[1].fields
				referenceType=referenceTypeF[1].title
			except:
				bibdata[referenceType]=referenceTypeF[1].fields
		

			bibdata['data']=referenceTypeF[1]
			fields=bibdata[referenceType]
                        for field in fieldlist:
                            retdata[field]=referenceTypeF[1].getValue(field)[1]

        return retdata,fieldlist,temp,fields

    def findTagsFromMapping(self,referenceType):
        """gib hash mit label -> generic zurueck"""
	

	if referenceType=="":
		referenceType="book"
	
	temp =  self.ZopeFind(self.standardMD)[0:]

	
	#self.referencetypes=temp[0:]
	
	
	

	

        bibdata={}
        retdata={}
        fieldlist=self.standardMD.fieldList
        
	for referenceTypeF in temp:
	
		if referenceTypeF[1].title.lower() == referenceType.lower(): 
			try:
				bibdata[referenceTypeF[1].title]=referenceTypeF[1].fields
				referenceType=referenceTypeF[1].title
			except:
				bibdata[referenceType]=referenceTypeF[1].fields
			bibdata['data']=referenceTypeF[1]
			fields=bibdata[referenceType]
                        for field in fieldlist:
                            retdata[field]=referenceTypeF[1].getValue(field)[0]
	
        return retdata,fieldlist,temp,fields

    

    def copyIndex_meta2echo_resource(self,RESPONSE=None):
	    """copy MD von Index_meta to the echo_resource"""

	    (metadict, error)=readMetadata(self.metalink)
	    
	    self.metaDataHash={}
	    if not error=="": #Fehler beim Auslesen des Metafiles
		    return "ERROR:",error
	    fields=self.findTagsFromMapping(self.contentType)
	    #fields=self.findLabelsFromMapping(self.contentType)
	    for field in fields[1]:
		    if self.isDefinedInThisSet(fields,field):
			    self.setFieldValue(self.getFieldTag(fields,field),metadict.get(self.getFieldTag(fields,field),''))

	    
	    
	    if RESPONSE:
		    return RESPONSE.redirect('manage_main')
	    
    def ECHO_getResourceMD(self,template="yes"):
        """Einlesen der Metadaten und Anlegen dieser Metadaten als Informationen zur Resource"""
        (metadict, error)=readMetadata(self.metalink)

	

        if not error=="": #Fehler beim Auslesen des Metafiles
		return "ERROR:",error
	

	if not (metadict['bib_type'].lower()==self.contentType.lower()):
		self.REQUEST.SESSION['contentStorage']=metadict['bib_type']
		self.REQUEST.SESSION['contentZope']=self.contentType

		return PageTemplateFile('Products/ECHO_content/zpt/ECHO_getResourceMDErrorContentType.zpt').__of__(self)()

	self.REQUEST.SESSION['metadict']=metadict

	
	
	self.REQUEST.SESSION['diffs']=checkDiffs(self,self.REQUEST.SESSION['metadict'])
	

		
        if template=="yes":
		pt=PageTemplateFile('Products/ECHO_content/zpt/ECHO_resourceMD.zpt').__of__(self)
		return pt()

	

    
    
    def ECHO_getMD(self,item):
        """Ausgabe der MD"""
        return getattr(self,item)
        
    def index_html(self):
        """standard page"""
        
        return self.REQUEST.RESPONSE.redirect(self.link)

    def startpage_html(self):
	    """prints out a startpage for a resource for use e.g. in the BVE"""

	    # suche ob startpage.html in dem Ordner vorhanden ist, dann wir diese angezeigt

	    sp=self.ZopeFind(self,obj_ids=['startpage.html'])

	    if sp:
		    return sp[1]()

            #prüfen ob irgendwo ein template
	    if hasattr(self,'startpage_index_template'): 
		    return self.startpage_index_template()

	    #generisches template ausgeben
	    
	    pt=PageTemplateFile('Products/ECHO_content/zpt/ECHO_startpage_index_template_standard.zpt').__of__(self)
	    pt.content_type="text/html"
	    return pt()

    def toc_html(self):
	    
	    sp=self.ZopeFind(self,obj_ids=['toc.html'])
		    
	    if sp:
		    return sp[0][1]()


		    
    def generate_label(self):
        """Erzeugt_standard_Label aus Template"""
        pt=getattr(self,"label_template_"+self.bib_type)

        return pt()

    def generate_title(self,RESPONSE=None):
        """Erzeugt_standard_Label aus Template"""
        pt=getattr(self,"label_template_"+self.contentType)

	self.title=pt()
	
        return pt()

def manage_addECHO_resourceForm(self):
        """Form for adding a ressource"""
        pt=PageTemplateFile('Products/ECHO_content/zpt/AddECHO_resourceForm.zpt').__of__(self)
        return pt()



def manage_addECHO_resource(self,id,title,label,description,responsible,link,metalink,weight,resourceID=None,contentType=None,renderingType=None,credits=None,coords=None,RESPONSE=None):
    """addaresource"""

    newObj=ECHO_resource(id,link,metalink,resourceID,title,label,description,contentType,renderingType,responsible,credits,weight,coords)

    self._setObject(id,newObj)

    if RESPONSE is not None:
        RESPONSE.redirect('manage_main')
 

class ECHO_externalLink(Folder):
    """Link zu einer externen Ressource"""
    security=ClassSecurityInfo()
    meta_type='ECHO_externalLink'

    def getTitle(self):
	"""title"""
	return self.title.encode('utf-8') 

    def getLabel(self):
	"""title"""
	return self.label.encode('utf-8') 

    def content_html(self):
        """template fuer content"""
        return content_html(self,'externalLink')
    
    def __init__(self,id,link,title,label,description,contentType,responsible,credits,weight,coords):

        self.id = id
        """Festlegen der ID"""

        self.credits=toList(credits)
        self.label = label
        self.link= link
        self.title=title
        self.weight=weight
        self.description=description
        self.contentType=contentType
        self.responsible=responsible
        coordsnew=[ string.split(x,",") for x in coords]
        self.coords=coordsnew

    def ECHO_externalLink_config(self):
        """Main configuration"""

        if not hasattr(self,'weight'):
            self.weight=""
        if not hasattr(self,'coords'):
            
            self.coords=['']


        pt=PageTemplateFile('Products/ECHO_content/zpt/ChangeECHO_externalLink.zpt').__of__(self)
        return pt()
    

    def changeECHO_externalLink(self,link,title,label,description,contentType,responsible,weight,coords=None,credits=None,RESPONSE=None):

        """Änderung der Properties"""
	try:
		coordsnew=[ string.split(x,",") for x in coords]
	except:
		coordsnew=[]

        setECHO_collectionInformation(self,title,label,description,contentType,responsible,credits,weight,coords)

        self.coords=coordsnew[0:]
        self.link=link
        if RESPONSE is not None:
            RESPONSE.redirect('manage_main')
            
            
    manage_options = Folder.manage_options+(
        {'label':'Main Config','action':'ECHO_externalLink_config'},
        )

    def getCredits(self):
        """Ausgabe der credits"""
        if self.credits:
            return self.credits
        else:
            return []
        
    def index_html(self):
        """standard page"""
        
        return self.REQUEST.RESPONSE.redirect(self.link)

def manage_addECHO_externalLinkForm(self):
        """Form for external Links"""
        pt=PageTemplateFile('Products/ECHO_content/zpt/AddECHO_externalLinkForm.zpt').__of__(self)
        return pt()


def manage_addECHO_externalLink(self,id,title,label,description,contentType,responsible,link,weight,coords=None,credits=None,RESPONSE=None):
    """Add an external Link"""

    newObj=ECHO_externalLink(id,link,title,label,description,contentType,responsible,credits,weight,coords)

    self._setObject(id,newObj)

    if RESPONSE is not None:
        RESPONSE.redirect('manage_main')
 

class ECHO_link(ECHO_externalLink):
	"""external_link"""

	meta_type="ECHO_link"
	

	def content_html(self):
		"""template fuer link"""
		if hasattr(self,"link_template"):
			return content_html(self,'link')
		else:
			return content_html(self,'collection')
	
def manage_addECHO_linkForm(self):
        """Form for external Links"""
        pt=PageTemplateFile('Products/ECHO_content/zpt/AddECHO_linkForm.zpt').__of__(self)
        return pt()


def manage_addECHO_link(self,id,title,label,description,contentType,responsible,link,weight,coords=None,credits=None,RESPONSE=None):
    """Add an external Link"""

    newObj=ECHO_link(id,link,title,label,description,contentType,responsible,credits,weight,coords)

    self._setObject(id,newObj)

    if RESPONSE is not None:
        RESPONSE.redirect('manage_main')
	

class ECHO_collection(Folder, Persistent, Implicit):
    """ECHO Collection"""

    security=ClassSecurityInfo()
    meta_type='ECHO_collection'
    viewClassificationList=viewClassificationListMaster
    displayTypes=displayTypes

    def getViewClassification(self):
        if hasattr(self,'viewClassification'):
            return self.viewClassification
        else:
            return ""

    def getTitle(self):
	"""title"""
	return self.title.encode('utf-8') 

    def getLabel(self):
	"""title"""
	return self.label.encode('utf-8') 

    
	    
    def createRessourcesFromXMLForm(self):
	    """form"""
	    pt=PageTemplateFile('Products/ECHO_content/zpt/createRessourcesFromXMLForm.zpt').__of__(self)
	    return pt()

    def createRessourcesFromXML(self,fileupload):
	    """read an XML file for generating resources"""
	    dom=xml.dom.minidom.parse(fileupload)
	    ret="<h2>Added</h2>"
	    for resource in dom.getElementsByTagName('resource'):
		    link=getText(resource.getElementsByTagName('link')[0].childNodes)
		    label=getText(resource.getElementsByTagName('label')[0].childNodes)
		    #splitted=link.split("?")[0].split("/")
		    #id=splitted[len(splitted)-1].encode('ascii')
		    id=re.sub(" ","_",label).encode('ascii')
		    
		    ret+="<p>"+label+"</p>"
		    manage_addECHO_resource(self,id,label.encode('ascii'),label.encode('ascii'),"","","",link.encode('ascii'),"","")
	    return ret
    def getImageTag(self):
        """GetTag"""
        try:
            return self.imageTag
        except:
            return ""

    def addResource(self,id,title,label,description,contentType,responsible,link,metalink,weight,credits=None,coords=None,RESPONSE=None):
        """SSS"""
        try:
            manage_addECHO_resource(self,id,title,label,description,contentType,responsible,link,metalink,weight,credits=None,coords=None,RESPONSE=None)
            return "done"
        except:
            return None

    def getSecondaryLink(self):
        """secondary link"""
        try:
            return self.secondaryLink
        except:
            return ""

    def getSecondaryLinkTitle(self):
        """secondary link"""
        try:
            return self.secondaryLinkTitle
        except:
            return ""
        
    def getCollectionTreeXML(self):
        """Tree as XML"""

        def getCollection(object,depth=0):
            depth+=1
            collections=""
            for entry in object.__dict__.keys():
                element=getattr(object,entry)
                try:
                    if element.meta_type in ["ECHO_collection","ECHO_group"]:
                        collections+="<element name=\""+quote(element.title)+"\" url=\""+element.absolute_url()+"\">"
                        collections+=getCollection(element,depth)+"</element>\n"
                except:
                    """nothing"""
            return collections
        
	ret="""<?xml version="1.0" encoding="utf-8" ?>"""
        return ret+"<collection>"+getCollection(self)+"</collection>"
    
    def createJavaScript(self):
        """OLD CreateJava"""
        ret=javaScriptMain

        dynamical="\n"
        for ob in self.getGraphicCoords():
	    if ob[4][4] == "":	
	        dynamical+="""Coords.push(new Coord('%s', Img, %s));\n"""%(ob[1],ob[0])
	    else:
		dynamical+="""Coords.push(new Coord('%s', Img, %s));//%s\n"""%(ob[1],ob[0],ob[4][4])
		dynamical+="ShowArrow(new getObj('i.%s'),Img,%s);\n"%(ob[1],ob[0])
	ret+=javaHandler%dynamical
        return ret

    def createJSAreas(self):
        """create area calls for JavaScript"""
        dynamical="\n"
        for ob in self.getGraphicCoords():
	    if ob[5] == "area":
	        dynamical+="""addArea('%s', 'overview', %s, 'area');\n"""%(ob[1],ob[0])
	    else:
	        dynamical+="""addArea('%s', 'overview', %s, 'arrow');\n"""%(ob[1],ob[0])
        return dynamical

    def createMapHead(self):
        """create javascript include and script tags for head"""
        pt=PageTemplateFile(os.path.join(package_home(globals()), 'zpt/ECHO_content_map_frag_js')).__of__(self)
        return pt()

    def createMapImg(self):
	"""generate img-tag for map"""
	bt = BrowserCheck(self)
	tag = ""
	src = self.REQUEST['URL1'] + "/overview"
	if bt.isN4:
	    tag += '<ilayer id="overview" visibility="show"><img src="%s"></ilayer>'%src
	else:
	    tag += '<img id="overview" src="%s" />'%src
	return tag
        
    def createMapLink(self, ob, text=None):
	"""generate map link"""
	bt = BrowserCheck(self)
	id = ob[1]
	link = ob[1]
	if text == None:
	    text = ob[2]
	tag = ""
	if bt.isN4:
	    tag += '<ilayer id="a.%s"><a onmouseover="highlightPair(\'%s\', true)" onmouseout="highlightPair(\'%s\', false)" href="%s" target="_blank"'%(id,id,id,link)
	    tag += ">" + text + "</a></ilayer>"
	else:
	    tag = '<a id="a.%s" onmouseover="highlightPair(\'%s\', true)" onmouseout="highlightPair(\'%s\', false)" href="%s" target="_blank"'%(id,id,id,link)
	    if ob[3].contentType == 'text-popup':
		tag += ' title="%s"'%ob[3].description
	    tag += ">" + text + "</a>"
	return tag

    def createMapAux(self, ob, arrowsrc="http://nausikaa2.rz-berlin.mpg.de/digitallibrary/servlet/Scaler/?dw=15&fn=icons/pfeil"):
	"""generate map link image, text and other stuff"""
	id = ob[1]
	link = ob[1]
	vtype = ob[5]
	ctype = ob[3].contentType
	bt = BrowserCheck(self)
	tag = ""

	if bt.isN4:
	    tag += '<layer id="i.%s" onmouseover="highlightPair(\'%s\', true)" onmouseout="highlightPair(\'%s\', false)">'%(id,id,id)
	    if vtype == "view point":
	        rot = ob[4][4]
		tag += '<a href="%s"><img border="0" src="%s&rot=%s" /></a>'%(link,arrowsrc,rot)
	    else:
		tag += '<a href="%s"><img border="0" width="1000" height="1000" src="trans_img"'%(link)
		if ctype == "text-popup":
		    desc = ob[3].description
		    tag += ' alt="%s"'%desc
		tag += ' /></a>'
	    tag += '</layer>'
	else:
	    tag = '<a id="b.%s" onmouseover="highlightPair(\'%s\', true)" onmouseout="highlightPair(\'%s\', false)" href="%s" target="_blank">'%(id,id,id,link)
	    if vtype == "view point":
		rot = ob[4][4]
		if bt.isIEWin and bt.versIE > 5:
		    tag += '<span id="i.%s" style="position:absolute; top:-100px; left:-100px; border-style:none; border-width=1px; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'%s&rot=%s\');"><img style="visibility:hidden" src="%s&rot=%s" /></span>'%(id,arrowsrc,rot,arrowsrc,rot)
		else:
		    tag += '<img id="i.%s" src="%s&rot=%s" border="1" style="position:absolute; top:-100px; left:-100px; border-style:none;" />'%(id,arrowsrc,rot)
	    else:
		if bt.isIEWin:
		    tag += '<div id="i.%s" style="position:absolute; top:-100px; left:-100px;background:url(area_img)"'%(id)
		else:
		    tag += '<div id="i.%s" style="position:absolute; top:-100px; left:-100px;"'%(id)
		if ctype == "text-popup":
		    desc = ob[3].description
		    tag += ' title="%s"'%desc
		tag += '> </div>'
	    tag += '</a>'
	return tag

    
    security.declarePublic('getCreditObject')
    def getCreditObject(self,name):
        """credit id to credititem"""
        try:
            return getattr(self.partners,name)
        except:
            return ""

    security.declarePublic('ECHO_generateNavBar')
    def ECHO_generateNavBar(self):
        """Erzeuge Navigationsbar"""
        link=""
        object="self"
        ret=[]
        path=self.getPhysicalPath()
        for element in path:
            
           
            if not element=="":
                object+="."+element
                
                label=eval(object).label
                link+="/"+element
                if not label=="":
                    ret.append((label,link))
        return ret
    
    security.declarePublic('ECHO_rerenderLinksMD')

    def ECHO_rerenderLinksMD(self,obj=None):
        """Rerender all Links"""
        if not obj:
            obj = self
            
        entries=obj.ZopeFind(obj,obj_metatypes=['ECHO_resource','ECHO_collection'])

        for entry in entries:
		if entry[1].meta_type == 'ECHO_resource':
			entry[1].ECHO_getResourceMD(template="no")

		else:
		   self.ECHO_rerenderLinksMD(entry[1])

                
                
        return "Rerenderd all links to resources in: "+self.title

    security.declarePublic('ECHO_newViewerLink')
    

    def getCoords(self):
        try:
            
            x=  [string.join(x,",") for x in self.coords]  
            return x

        except:

            return []
        
    def __init__(self,id,title,label,description,contentType,responsible,credits,weight,sortfield,coords,secondaryLinkTitle,secondaryLink,imageTag="",bgcolour=""):


        self.id = id
        """Festlegen der ID"""
        self.credits=toList(credits)
        self.label = label
        self.title=title
        self.description=description
        self.contentType=contentType
        self.responsible=responsible
        self.imageTag=imageTag
        self.weight=weight
        self.sortfield=sortfield
        coordsnew=[ string.split(x,",") for x in coords]
        self.coords=coordsnew
        self.secondaryLinkTitle=secondaryLinkTitle
        self.secondaryLink=secondaryLink
	self.bgcolour=bgcolour
        

    manage_options = Folder.manage_options+(
        {'label':'Main Config','action':'ECHO_collection_config'},
        {'label':'Rerender Links','action':'ECHO_rerenderLinksMD'},
        {'label':'Graphics','action':'ECHO_graphicEntry'},
	{'label':'create resources from XML','action':'createRessourcesFromXMLForm'},

        )

    def getOverview(self):
        """overview graphics"""
        
        return self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['overview'])[0][1]
    
    
    def ECHO_graphicEntry(self):
        """DO nothing"""
        overview = self.aq_parent.ZopeFind(self.aq_parent,obj_ids=['overview'])
        
    
        if overview:
            pt=PageTemplateFile('Products/ECHO_content/zpt/ECHO_draw.zpt').__of__(self)
            return pt()
        else:
            return "NO OVERVIEW GRAPHICS"

    def ECHO_enterCoords(self,coordstr,angle="",RESPONSE=None):
        """Enter coords"""
        coords=self.coords
        temco=coordstr.split(",")
        temco.append(angle)
        coords.append(temco)
        self.coords=coords[0:]

        if RESPONSE is not None:
            RESPONSE.redirect('ECHO_graphicEntry')

    
    security.declarePublic('ECHO_collection_config')
    def ECHO_collection_config(self):
        """Main configuration"""

        if not hasattr(self,'weight'):
            self.weight=""

        if not hasattr(self,'sortfield'):
            self.sortfield="weight"
  
        if not hasattr(self,'coords'):
            self.coords=[]

        pt=PageTemplateFile('Products/ECHO_content/zpt/ChangeECHO_collection.zpt').__of__(self)
        return pt()


    security.declarePublic('changeECHO_collection')


    def getBgcolour(self):
	    """colour"""
	    if hasattr(self,'bgcolour') and not (self.bgcolour==""):
		    return self.bgcolour
	    else:
		    return "#dddddd"
	    
    def changeECHO_collection(self,title,label,description,contentType,responsible,weight,secondaryLink,secondaryLinkTitle,credits=None,sortfield="weight",coords=None,RESPONSE=None,imageTag="",bgcolour="",viewClassification=None):
        """Aenderung der Properties"""

        self.secondaryLink=secondaryLink
        self.secondaryLinkTitle=secondaryLinkTitle
        self.imageTag=imageTag
	self.bgcolour=bgcolour
        self.viewClassification=viewClassification
	
        if coords:
            coordsnew=[ string.split(x,",") for x in coords]
            self.coords=coordsnew[0:]
        else:
            coordsnew=None
            self.coords=None
            
        setECHO_collectionInformation(self,title,label,description,contentType,responsible,credits,weight,coordsnew)
	try:
		self.coords=coordsnew[0:] # HACK fehler in setECHO_collection
        except:
		"""none"""
		
        self.sortfield=sortfield

        if RESPONSE is not None:
            RESPONSE.redirect('manage_main')
            

    def showOverview(self):
        """overview"""
        if 'ECHO_overview.html' in self.__dict__.keys():
            return getattr(self,'ECHO_overview.html')()
        pt=PageTemplateFile('Products/ECHO_content/zpt/ECHO_content_overview.zpt').__of__(self)
        return pt()

    security.declareProtected('View','index_html')
    
    def index_html(self):
        """standard page"""
        
        if 'index.html' in self.__dict__.keys():
            return getattr(self,'index.html')()
        
        elif 'overview' in self.__dict__.keys():
            return self.showOverview()
        elif hasattr(self,'collection_index_template'):
            return self.collection_index_template()    
        elif hasattr(self,'main_index_template'):
            return self.main_index_template()    
        
        pt=PageTemplateFile('Products/ECHO_content/zpt/ECHO_main_index_template_standard.zpt').__of__(self)
        pt.content_type="text/html"
        return pt()

    def content_html(self):
        """template fuer content"""
        return content_html(self,'collection')
    
    def getCredits(self):
        """Ausgabe der credits"""
        if self.credits:
            return self.credits
        else:
            return []

    def area_img(self):
        """area image"""
	bt = BrowserCheck(self)
	if bt.isIE or bt.isN4:
	    return sendFile(self, 'images/red.gif', 'image/gif')
	else:
	    return sendFile(self, 'images/reda.png', 'image/png')

    def trans_img(self):
        """empty image"""
        return sendFile(self, 'images/trans.gif', 'image/gif')

    def hl_lib_js(self):
        """javascript"""
        return sendFile(self, 'js/hl_lib.js', 'text/plain')

    def js_lib_js(self):
        """javascript"""
        return sendFile(self, 'js/js_lib.js', 'text/plain')

    def getGraphicCoords(self):
        """Give list of coordinates"""
        subColTypes=['ECHO_collection','ECHO_resource']
        ids=[]
        for entrySearch in self.ZopeFind(self,obj_metatypes=subColTypes):
            object=entrySearch[1]
            if hasattr(object,'coords'):
                for coordtemp in object.coords:
                    if len(coordtemp)>3:
                        coord=coordtemp[0:4]
                        label=""
			vc=""
                        if hasattr(object,'label') and not object.label=="":
                            label=object.label
                        elif hasattr(object,'title') and not object.title=="":
                            label=object.title
                        else:
                            label=object.getId()
			if object.viewClassification != "":
			    vc=object.viewClassification
			else:
			    if len(coordtemp) > 4 and coordtemp[4] != "":
				vc="view point"
			    else:
				vc="area"
                        ids.append([string.join(coord,", "),object.getId(),label,object,coordtemp,vc])
        return ids
    



    getSubCols = ECHO_helpers.getSubCols

Globals.InitializeClass(ECHO_collection)
    
def manage_addECHO_collectionForm(self):
        """Add collection form"""
        pt=PageTemplateFile('Products/ECHO_content/zpt/AddECHO_collectionForm.zpt').__of__(self)
        return pt()


def manage_addECHO_collection(self,id,title,label,description,contentType,responsible,weight,sortfield,coords="",secondaryLinkTitle="",secondaryLink="",credits=None,RESPONSE=None,imageTag="",bgcolour=""):
    """add a echo collection"""
    

    newObj=ECHO_collection(id,title,label,description,contentType,responsible,credits,weight,sortfield,coords,secondaryLinkTitle=secondaryLinkTitle,secondaryLink=secondaryLink,imageTag=imageTag,bgcolour="")

    self._setObject(id,newObj)

    if RESPONSE is not None:
        RESPONSE.redirect('manage_main')

class ECHO_group(ECHO_collection):
	"""ECHO Gruppe"""
	security=ClassSecurityInfo()
	meta_type="ECHO_group"

	manage_options = Folder.manage_options+(
		{'label':'Main Config','action':'ECHO_group_config'},
		{'label':'Rerender Links','action':'ECHO_rerenderLinksMD'},
		{'label':'Graphics','action':'ECHO_graphicEntry'},
		)
	
	security.declareProtected('View','index_html')
	def index_html(self):
		"""standard page"""
		displayedObjects=self.ZopeFind(self,obj_metatypes=displayTypes)
		#if (len(displayedObjects)==1) and (displayedObjects[0][1].meta_type=="ECHO_collection"): # nur ein Object dann redirect auf dieses Object
		#	return self.REQUEST.RESPONSE.redirect(displayedObjects[0][1].absolute_url())
		
		if 'index.html' in self.__dict__.keys():
			return getattr(self,'index.html')()
		
		elif 'overview' in self.__dict__.keys():
			return self.showOverview()
		elif hasattr(self,'group_index_template'):
			return self.group_index_template()
		elif hasattr(self,'collection_index_template'):
			return self.collection_index_template()    
		elif hasattr(self,'main_index_template'):
		    return self.main_index_template()    

		pt=PageTemplateFile('Products/ECHO_content/zpt/ECHO_main_index_template_standard.zpt').__of__(self)
		pt.content_type="text/html"
		return pt()

	def ECHO_group_config(self):
		"""Main configuration"""
		
		if not hasattr(self,'weight'):
			self.weight=""
			
		if not hasattr(self,'sortfield'):
			self.sortfield="weight"
				
		if not hasattr(self,'coords'):
			self.coords=[]

		pt=PageTemplateFile('Products/ECHO_content/zpt/ChangeECHO_group.zpt').__of__(self)
		return pt()

	def changeECHO_group(self,title,label,description,contentType,responsible,weight,secondaryLink,secondaryLinkTitle,credits=None,sortfield="weight",coords=None,RESPONSE=None,imageTag="",bgcolour="",logo=""):
		"""Änderung der Properties"""

		self.secondaryLink=secondaryLink
		self.secondaryLinkTitle=secondaryLinkTitle
		self.imageTag=imageTag
		self.bgcolour=bgcolour
                self.logo=logo
                
		if coords:
		    coordsnew=[ string.split(x,",") for x in coords]
		    self.coords=coordsnew[0:]
		else:
		    coordsnew=None
		    self.coords=None

		setECHO_collectionInformation(self,title,label,description,contentType,responsible,credits,weight,coordsnew)



		self.sortfield=sortfield

		if RESPONSE is not None:
		    RESPONSE.redirect('manage_main')

	def getLogo(self):    
		"""logo ausgeben"""
                try:
                    return self.logo
                except:
                    return "ECHO_groups"

	def content_html(self):
		"""template fuer content"""
		return content_html(self,'group')
    


def manage_addECHO_groupForm(self):
        """Add group form"""
        pt=PageTemplateFile('Products/ECHO_content/zpt/AddECHO_groupForm.zpt').__of__(self)
        return pt()


def manage_addECHO_group(self,id,title,label,description,contentType,responsible,weight,sortfield,coords="",secondaryLinkTitle="",secondaryLink="",credits=None,RESPONSE=None,imageTag="",bgcolour="",logo=""):
    """add a echo group"""
    

    newObj=ECHO_group(id,title,label,description,contentType,responsible,credits,weight,sortfield,coords,secondaryLinkTitle=secondaryLinkTitle,secondaryLink=secondaryLink,imageTag=imageTag,bgcolour="")

    setattr(newObj,'logo',logo)
    self._setObject(id,newObj)
    
    if RESPONSE is not None:
        RESPONSE.redirect('manage_main')

Globals.InitializeClass(ECHO_group)


class ECHO_userFolder(UserFolder):
	"""User folder for Intranet"""
	_domain_auth_mode=1 # Identification via domain
	meta_type="ECHO_userFolder"
	
	def authenticate(self, name, password, request):
		emergency = self._emergency_user
		if name is None:
		    return None
		if emergency and name==emergency.getUserName():
		    user = emergency
		else:
		    user = self.getUser(name)
		if user is not None and user.authenticate(password, request):
		    return user
		else:
		    return None

	def domainSpecMatch(self,spec, request):
	    host=''
	    addr=''

	    # Fast exit for the match-all case
	    if len(spec) == 1 and spec[0] == '*':
		return 1

	    if request.has_key('REMOTE_HOST'):
		host=request['REMOTE_HOST']

	    if request.has_key('REMOTE_ADDR'):
		addr=request['REMOTE_ADDR']

	    if request.has_key('HTTP_X_FORWARDED_FOR'):
		addr=request['HTTP_X_FORWARDED_FOR']

	    
	    if not host and not addr:
		return 0

	    if not host:
		try:    host=socket.gethostbyaddr(addr)[0]
		except: pass
	    if not addr:
		try:    addr=socket.gethostbyname(host)
		except: pass


	    _host=host.split('.')
	    _addr=addr.split('.')
	    _hlen=len(_host)
	    _alen=len(_addr)

	    for ob in spec:
		sz=len(ob)
		_ob=ob.split('.')
		_sz=len(_ob)

		mo = addr_match(ob)
		if mo is not None:
		    if mo.end(0)==sz:
			fail=0
			for i in range(_sz):
			    a=_addr[i]
			    o=_ob[i]
			    if (o != a) and (o != '*'):
				fail=1
				break
			if fail:
			    continue
			return 1

		mo = host_match(ob)
		if mo is not None:
		    if mo.end(0)==sz:
			if _hlen < _sz:
			    continue
			elif _hlen > _sz:
			    _item=_host[-_sz:]
			else:
			    _item=_host
			fail=0
			for i in range(_sz):
			    h=_item[i]
			    o=_ob[i]
			    if (o != h) and (o != '*'):
				fail=1
				break
			if fail:
			    continue
			return 1
	    return 0

Globals.default__class_init__(ECHO_userFolder)



def manage_addECHO_userFolder(self,dtself=None,REQUEST=None,**ignored):
    """add a user folder """
    f=ECHO_userFolder()
    self=self.this()
    try:    self._setObject('acl_users', f)
    except: return MessageDialog(
                   title  ='Item Exists',
                   message='This object already contains a User Folder',
                   action ='%s/manage_main' % REQUEST['URL1'])
    self.__allow_groups__=f
    if REQUEST is not None:
        REQUEST['RESPONSE'].redirect(self.absolute_url()+'/manage_main')

def manage_addECHO_userFolderForm(self):
	"""add a user folder form"""
	return manage_addECHO_userFolder(self)

class ECHO_root(Folder,Persistent,Implicit):
    """ECHO Root Folder"""

    security=ClassSecurityInfo()
    
    meta_type="ECHO_root"


    def getBibTag(self,tag,content):
	    """get field tag für index-meta-generation"""
	    if not content or content=="":
		    return ""
	    ret="<%s>"%tag
	    ret+=urllib.quote(content)
	    ret+="</%s>"%tag
	    return ret

    def getValueFromClass(self,field,found):
	    """retattribute falss existing"""
	    try:
		    return getattr(found,field)
	    except:
		    return ""
    
    def getImageTag(self):
	    """needed by main_template"""
	    return ""
    secondaryLink="" #needed by main_template
    secondaryLinkTitle="" #needed by main_template
    
    def getBgcolour(self):
	"""hack"""
	return "#dddddd"

    def contentTypeSelector_HTML(self,selected=None):
        """give type selector"""
        if not selected:
            retStr="<option selected>\n"
        else:
            retStr="<option>\n"
            
        try: # erste version contentTypes exists
            for contentType in self.ZopeFind(self.contentTypes,obj_metatypes=["ECHO_contentType","OSAS_MetadataMapping"]):
                if selected and (contentType[0]==selected):
                    retStr+="""<option selected value="%s">%s\n"""%(contentType[0],contentType[0])
                else:                
                    retStr+="""<option value="%s">%s\n"""%(contentType[0],contentType[0])
        except:
		try:
			for contentType in self.ZopeFind(self.standardMD,obj_metatypes=["OSAS_MetadataMapping"]):
				if selected and (contentType[0]==selected):
					retStr+="""<option selected value="%s">%s\n"""%(contentType[0],contentType[0])
				else:                
					retStr+="""<option value="%s">%s\n"""%(contentType[0],contentType[0])
		except:
			"""nothing"""
			    
	return retStr

    def renderingTypeSelector_HTML(self,selected=None):
         """give type selector"""
	 if not selected:
		 retStr="<option selected>\n"
	 else:
		 retStr="<option>\n"
		 
	 try: # erste version renderingTypes exists
		 for renderingType in self.ZopeFind(self.renderingTypes,obj_metatypes=["ECHO_renderingType"]):
			 if selected and (renderingType[0]==selected):
				 retStr+="""<option selected value="%s">%s\n"""%(renderingType[0],renderingType[0])
			 else:                
				 retStr+="""<option value="%s">%s\n"""%(renderingType[0],renderingType[0])
	 except:
		 """nothing"""
	 return retStr

    def renderingTypeSelector_HTML(self,selected=None):
         """give type selector"""
	 if not selected:
		 retStr="<option selected>\n"
	 else:
		 retStr="<option>\n"
		 
	 try: # erste version renderingTypes exists
		 for renderingType in self.ZopeFind(self.renderingTypes,obj_metatypes=["ECHO_renderingType"]):
			 if selected and (renderingType[0]==selected):
				 retStr+="""<option selected value="%s">%s\n"""%(renderingType[0],renderingType[0])
			 else:                
				 retStr+="""<option value="%s">%s\n"""%(renderingType[0],renderingType[0])
	 except:
		 """nothing"""
	 return retStr


    def copyrightTypeSelector_HTML(self,selected=None):
         """give type selector"""
	 if not selected:
		 retStr="<option selected>\n"
	 else:
		 retStr="<option>\n"
		 
	 try: # erste version copyrightTypes exists
		 for copyrightType in self.ZopeFind(self.copyrightTypes,obj_metatypes=["ECHO_copyrightType"]):
			 if selected and (copyrightType[0]==selected):
				 retStr+="""<option selected value="%s">%s\n"""%(copyrightType[0],copyrightType[0])
			 else:                
				 retStr+="""<option value="%s">%s\n"""%(copyrightType[0],copyrightType[0])
	 except:
		 """nothing"""
	 return retStr

            
    def patchContentType(self,obj=None):
        """austauschen content_type with contentType (patch bei umstieg von alter Version)"""
    

        if not obj:
            obj = self
            
        entries=obj.ZopeFind(obj,obj_metatypes=['ECHO_resource','ECHO_collection','ECHO_externalLink','ECHO_pageTemplate'])

        for entry in entries:
                setattr(entry[1],'contentType',entry[1].content_type)
                #entry[1].contentType == entry[1].content_type

                if entry[1].meta_type == 'ECHO_collection':
                    entry[1].patchContentType(entry[1])    

                
        return "changed all contenttypes in: "+self.title


    def patchViewClassification(self,obj=None):
        """setze viewClassification heuristisch"""

	def checkIfArrow(obj):
		if hasattr(obj,'coords'):
			for coordtemp in obj.coords:

				if (len(coordtemp)>4) and not (coordtemp[4]==''):
					return 4
			return None
		return None
	
        if not obj:
            obj = self
            
        entries=obj.ZopeFind(obj,obj_metatypes=['ECHO_resource','ECHO_collection','ECHO_group'])

        for entry in entries:
		
		if checkIfArrow(entry[1]):
			setattr(entry[1],'viewClassification','view point')
		else:
			setattr(entry[1],'viewClassification','area')

                #entry[1].contentType == entry[1].content_type

                if entry[1].meta_type in ['ECHO_collection','ECHO_group']:
                    entry[1].patchViewClassification(entry[1])    

                
        return "changed all contenttypes in: "+self.title

    def ECHO_newViewerLink(self,obj=None):
        """change links (:86 faellt weg)"""

        if not obj:
            obj = self
            
        entries=obj.ZopeFind(obj,obj_metatypes=['ECHO_resource','ECHO_collection'])

        for entry in entries:
                
                if entry[1].meta_type == 'ECHO_resource':
                    
                    entry[1].link=re.sub('\:86','',entry[1].link)

                else:
                    
                    entry[1].ECHO_newViewerLink(entry[1])
                
        return "Rerenderd all links to resources in: "+self.title

    def __init__(self,id,title):
        """init"""
        self.id = id
        self.title=title

    def deleteSpace(self,str):
        """delete space at the end of a line"""
        if str[len(str)-1]==" ":
            return str[0:len(str)-1]
        else:
            return str
        
    

    # zusaetliche methoden fuer das vlp muessen in ein eigenes produkt

    def formatAscii(self,str,url=None):
        """ersetze ascii umbrueche durch <br>"""
        #url=None
        if url:
            
            retStr=""
            words=str.split("\n")
            
            for word in words:
                strUrl=url%word

                retStr+="""<a href="%s">%s</a><br/>"""%(strUrl,word)
            str=retStr
        if str:
            return re.sub(r"[\n]","<br/>",str)
        else:
            return ""
        
    def link2html(self,str):
        """link2html fuer VLP muss hier noch raus"""
        if str:

            str=re.sub("\&","&amp;",str)
            dom=xml.dom.minidom.parseString("<?xml version='1.0' ?><txt>"+str+"</txt>")
            links=dom.getElementsByTagName("link")
            

            for link in links:
                link.tagName="a"
                ref=link.getAttribute("ref")
                if self.checkRef(ref):
                    link.setAttribute("href",self.aq_parent.absolute_url()+"/vlp_coll?id="+ref)

            return dom.toxml('utf-8')
        return ""


    def checkRef(self,ref):
        dbs={'vl_literature':'AND CD LIKE \'%lise%\'','vl_technology':'','vl_people':''}
        res=None
        for db in dbs.keys():

            res=res or self.search(var=str("select reference from %s where reference =\'%s\' %s"%(db,ref,dbs[db])))
        return res
                                    
    #Ende Methode fuer vlp

    def PgQuoteString(self,string):
        """Quote string"""

        return libpq.PgQuoteString(string)
        
    def getPartners(self):
        """Get list of Partners. Presently only from a subfolder partners"""
                    
        return [ item[1] for item in self.partners.ZopeFind(self.partners,obj_metatypes=['ECHO_partner'])]
                
                
                   

    
    def getPartnersXML(self):
        """partner liste als xml""" 
        partners=self.getPartners()
        ret="""<?xml version="1.0" encoding="utf-8" ?>
	<partners>"""
        
	for partner in partners:
            ret+="""<partner id="%s" title="%s"/>\n"""%(partner.getId(),unicode(partner.title,'utf-8','replace'))

        return ret+"\n</partners>"
    
    def getCollectionTree(self):
        """get the collection tree (list of triples (parent,child, depth)"""

        def getCollection(object,depth=0):
            depth+=1
            collections=[]
            for entry in object.__dict__.keys():
                element=getattr(object,entry)
                try:
                    if element.meta_type=="ECHO_collection":
                        collections.append((object,element,depth))
                        collections+=getCollection(element,depth)
                except:
                    """nothing"""
            return collections
        

        return getCollection(self)
    
    def getCollectionTreeIds(self):
        """Show the IDs of the Tree"""
        ret=[]
        for collection in self.getCollectionTree():
            ret.append((collection[0].getId(),collection[1].getId(),collection[2]))
        return ret

    def getResourcesHTML(self,viewerType=None,filter=None):
	    """gebe all ressourcen aus"""

	    def sortHTML(x,y):
		    return cmp(x[1].title,y[1].title)
	    
	    ret="""<html><body><h2>Resources in ECHO</h3>"""
	    
	    resources = self.ZopeFind(self,obj_metatypes=['ECHO_resource'],search_sub=1)
	    ret+="""<h3>Found %i resources</h3>"""%len(resources)
	    resources.sort(sortHTML)
	    for resource in resources:
		    echo_url=resource[1].absolute_url()
		    
		    if hasattr(resource[1],'title'):
			    title=resource[1].title
		    else:
			    title="None"
		    if filter:
			    if re.search(filter,title):
				    ret+="""\n<p><a href="%s">%s</a></p>"""%(echo_url,title)
		    else:
			    ret+="""\n<p><a href="%s">%s</a></p>"""%(echo_url,title)

	    ret +="""\n</body></html>"""
	    
	    #self.REQUEST.RESPONSE.setHeader("Content-Type", "text/html")
	    #self.REQUEST.RESPONSE.write(ret)
    	    return ret
    
    def getResourcesXML(self,viewerType=None,filter=None):
	    """gebe all ressourcen aus"""
	    ret="""<?xml version="1.0" ?>
	             <index>"""
	    for resource in self.ZopeFind(self,obj_metatypes=['ECHO_resource'],search_sub=1):

		    echo_url=resource[1].absolute_url()
		    if hasattr(resource[1],'link'):
			    viewer_url=resource[1].link
		    else:
			    viewer_url="NO URL"
		    if filter:
			    if re.search(filter,viewer_url):
				    ret+="""\n<resource echoLink="%s" viewerLink="%s"/>"""%(urllib.quote(echo_url,safe='/:?'),urllib.quote(viewer_url,safe='/:?'))
		    else:
			    ret+="""\n<resource echoLink="%s" viewerLink="%s"/>"""%(urllib.quote(echo_url,safe='/:?'),urllib.quote(viewer_url,safe='/:?'))
	    ret +="""\n</index>"""
	    
	    self.REQUEST.RESPONSE.setHeader("Content-Type", "text/xml")
	    self.REQUEST.RESPONSE.write(ret)

    def getFullTextsXML(self,viewerType=None,filter=None):
	    """gebe all ressourcen aus"""
	    ret="""<?xml version="1.0" ?>
	             <index>"""
	    for resource in self.ZopeFind(self,obj_metatypes=['ECHO_resource'],search_sub=1):

		    echo_url=resource[1].absolute_url()
		    if resource[1].getFullTextXML(noredirect="yes"):
			    if hasattr(resource[1],'link'):
				    viewer_url=echo_url+"/getFullTextXML"
			    else:
				    viewer_url="NO URL"
			    if filter:
				    if re.search(filter,viewer_url):
					    ret+="""\n<resource echoLink="%s" viewerLink="%s"/>"""%(urllib.quote(echo_url,safe='/:?'),urllib.quote(viewer_url,safe='/:?'))
			    else:
				    ret+="""\n<resource echoLink="%s" viewerLink="%s"/>"""%(urllib.quote(echo_url,safe='/:?'),urllib.quote(viewer_url,safe='/:?'))
	    ret +="""\n</index>"""
	    
	    
	    self.REQUEST.RESPONSE.setHeader("Content-Type", "text/xml")
	    self.REQUEST.RESPONSE.write(ret)
        
def manage_addECHO_root(self,id,title,RESPONSE=None):
    """Add an ECHO_root"""
    self._setObject(id,ECHO_root(id,title))
    
    if RESPONSE is not None:
        RESPONSE.redirect('manage_main')

def manage_addECHO_rootForm(self):
        """Nothing yet"""
        pt=PageTemplateFile('Products/ECHO_content/zpt/AddECHO_root.zpt').__of__(self)
        return pt()
 
class ECHO_partner(Image,Persistent):
    """ECHO Partner"""

    meta_type="ECHO_partner"

    def __init__(self, id, title,url, file, content_type='', precondition=''):
        self.__name__=id
        self.title=title
        self.url=url
        self.precondition=precondition

        data, size = self._read_data(file)
        content_type=self._get_content_type(file, data, id, content_type)
        self.update_data(data, content_type, size)

    manage_options = Image.manage_options+(
        {'label':'Partner Information','action':'ECHO_partner_config'},
        )

    def changeECHO_partner(self,url,RESPONSE=None):
        """Change main information"""
        self.url=url
        if RESPONSE is not None:
            RESPONSE.redirect('manage_main')
            
            

    def ECHO_partner_config(self):
        """Main configuration"""
        if not hasattr(self,'url'):
            self.url=""
        pt=PageTemplateFile('Products/ECHO_content/zpt/ChangeECHO_partner.zpt').__of__(self)
        return pt()

        
manage_addECHO_partnerForm=DTMLFile('dtml/ECHO_partnerAdd',globals(),
                             Kind='ECHO_partner',kind='ECHO_partner')



def manage_addECHO_partner(self, id, file,url, title='', precondition='', content_type='',
                    REQUEST=None):
    """
    Add a new ECHO_partner object.

    Creates a new ECHO_partner object 'id' with the contents of 'file'.
    Based on Image.manage_addImage
    """

    id=str(id)
    title=str(title)
    content_type=str(content_type)
    precondition=str(precondition)

    id, title = OFS.Image.cookId(id, title, file)

    self=self.this()

    # First, we create the image without data:
    self._setObject(id, ECHO_partner(id,title,url,'',content_type, precondition))

    # Now we "upload" the data.  By doing this in two steps, we
    # can use a database trick to make the upload more efficient.
    if file:
        self._getOb(id).manage_upload(file)
    if content_type:
        self._getOb(id).content_type=content_type

    if REQUEST is not None:
        try:    url=self.DestinationURL()
        except: url=REQUEST['URL1']
        REQUEST.RESPONSE.redirect('%s/manage_main' % url)
    return id



FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>