File:  [Repository] / lise / lise.py
Revision 1.3: download - view: text, annotated - select for diffs - revision graph
Fri Apr 23 16:25:09 2004 UTC (20 years ago) by wischi
Branches: MAIN
CVS tags: HEAD
new version

import xml.parsers.expat
import re
import OFS.Image
from types import *
from OFS.Image import Image
from OFS.Folder import Folder
from OFS.SimpleItem import SimpleItem
from OFS.Image import manage_addFile
from OFS.Image import File
from OFS.DTMLDocument import addDTMLDocument
from Globals import DTMLFile, MessageDialog, package_home
from Products.ExternalMethod.ExternalMethod import manage_addExternalMethod
from Products.PageTemplates.ZopePageTemplate import manage_addPageTemplate
import os
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
from Products.PageTemplates.PageTemplate import PageTemplate
from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate
import string
import urllib
import xml.dom.minidom
from urllib import quote


###   G L O B A L S   ###
allobjects = []
pagearray = []
objindex = 0
currobj = 0
currchapter = 0
tagstr = ""
counter = 1      # counts pages/pictures
counterid = 1    # counts IDs

onpage = 0
onpagename = 0
onpageindex = 0
onpageurl = 0
onchapter = 0
onchaptername = 0
onstart = 0
onstartname = 0
onstartindex = 0
onstarturl = 0
onend = 0
onendname = 0
onendindex = 0
onendurl = 0
gbaseurl = ''
gpictpath = ''
errstr = ''



class lise(Folder):
	"The class lise"
	
	meta_type = 'lise'
	
	manage_options=(
		{'label': 'Contents', 'action': 'manage_main'},
		{'label': 'Welcome', 'action': 'index_html'},
		{'label': 'Schedule', 'action': 'schedule_html'},
		{'label': 'Edit Schedule', 'action': 'manage_editScheduleForm'},
	)

	def __init__(self, id, title):
		"Initialize a new instance of lise class"
		self.id = id
		self.title = title
		self.freetext = 'hoho'
		self.schedule = 'schedule'
		self.xml = 'xml'
		self.xmlpath = 'xmlpath'
		self.xmlfilename = 'xmlfilename'
		self.link = ''
			
	def manage_editSchedule(self, title, schedule, RESPONSE=None):
		"Change attributes of a lise instance"
		self.title = title
		self.schedule = schedule
		if RESPONSE is not None:
			return MessageDialog(
				title='Edited',
				message='<strong>%s</strong> has been edited.'%self.id,
				action='./schedule_html'
			)

	schedule_html = DTMLFile('dtml/schedule_html', globals())
	manage_editScheduleForm = DTMLFile('dtml/manage_editScheduleForm', globals())

		
# ZOPE interface
manage_addliseForm = DTMLFile('dtml/manage_addliseForm', globals())


class MAIN_layoutTemplate(ZopePageTemplate):
    """Create a layout Template"""

    meta_type="MAIN_layoutTemplate"

    def __init__(self, id, text=None, content_type=None, MainType=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()),
                                               'dtml/main.zpt')
            text = open(self._default_content_fn).read()
        self.pt_edit(text, content_type)

    
        """change form"""
        
        
def manage_addNAIN_layoutTemplateForm(self):
    """Form for adding"""
    pt = PageTemplateFile('Products/lise/dtml/main.zpt').__of__(self)
    return pt()


def manage_addlise(self, id, title, pictpath, baseurl, file, RESPONSE = None):
	"add a lise instance in a folder."
	global allobjects
	global objindex
	global currchapter
	global currobj
	global tagstr
	global onpage
	global onpagename
	global onpageindex
	global onpageurl
	global onchapter
	global onchaptername
	global onstart
	global onstartname
	global onstartindex
	global onstarturl
	global onend
	global onendname
	global onendindex
	global onendurl
	global pagearray
	global errstr
	global counterid
	global gbaseurl
	global gpictpath
	
	allobjects = []
	pagearray = []
	filenames = []
	fnames = []
	id = str(id)
	title = str(title)

	gpictpath = str(pictpath)

	thelen = len(gpictpath)
	if thelen > 0:
		fnames = os.listdir(gpictpath)
		thelen = len(filenames)
		j = 0
		for i in fnames:
			if i[0] <> '.':
				normalize_whitespace(i)
#				filenames.append('file://' + gpictpath + '/' + i)
				if gpictpath[-1] == '/':
					filenames.append('file://' + gpictpath + i)
				else:
					filenames.append('file://' + gpictpath + '/' + i)
	else:
		filenames.append('no_fuckingPicture')

	newObj = lise(id, title) # create new lise object
	self._setObject(id, newObj) # put it into zope
	if RESPONSE is not None:
		RESPONSE.redirect('manage_main')
	link = self.absolute_url() + '/' + id # path of new lise object
	object = getattr(self, id) # get the new lise object
	RESPONSE.redirect(link) # set path to new lise object
	
	errid = 'standard_error_message'
	error_html = DTMLFile('dtml/standard_error_message',globals())
	addDTMLDocument(object, errid, '', error_html)
	errobj = getattr(object, errid) # reference this object
	
	lisescript = manage_addExternalMethod(object, 'liseScript','liseScript','lise.liseScript','liseScript')
	
	id2 = id + '.xml'
	manage_addFile(object, id2, file, title, 'text/xml') # create new xml file
	object2 = getattr(object, id2) # reference this object
	link2 = self.absolute_url() + '/' + id + '/' + id + '.xml' # path of xml file

	objarr = []
	retval = ''
	thelen = 42
	newObj.xmlpath = str(thelen)
	
	p = xml.parsers.expat.ParserCreate()
	taghandler = TagHandler()
	p.StartElementHandler = taghandler.expat_start_element
	p.EndElementHandler = taghandler.expat_endElement
	p.CharacterDataHandler = taghandler.characters
	p.Parse(str(object2.data))
	
	if IsStr(baseurl):
		gbaseurl = str(baseurl)

	#### lšschen nicht vergessen ###
#	gbaseurl = 'http://nausikaa2.mpiwg-berlin.mpg.de/digitallibrary/servlet/Scaler?fn=permanent/shipbuilding/bougu_traite_1746&dw=400&dh=400&pn='

	for i in allobjects:
		if hasattr(i, 'typestr'):
			if i.typestr == 'chapter':
				i.parseobjects()

	counterid = 1
	for i in allobjects:
		if hasattr(i, 'typestr'):
			if i.typestr == 'chapter':
				i.CreateChapter()
			if i.typestr == 'page':
				i.CreatePage(i.chapterindex)
		

	pacount = 0
	for i in pagearray:
		if i.type == 'C':
			i.picturelink = 'this_is the_no_fucking_picture_error'
			i.pictindex = 0
			for j in range(pacount, len(pagearray)):
				if pagearray[j].type == 'P':
					if len(pagearray[j].picturelink) > 0:
						i.picturelink = pagearray[j].picturelink
						break
					if IsInt(pagearray[j].pictindex):
						i.pictindex = pagearray[j].pictindex
						break
		pacount = pacount + 1
	
	mainid = 'main'
	main_html = PageTemplateFile('dtml/main.zpt',globals()).__of__(self)
	manage_addPageTemplate(object, mainid, '', main_html)
#	addDTMLDocument(object, mainid, '', main_html)
	mainobj = getattr(object, mainid) # reference this object
	setattr(mainobj, 'pagelist', pagearray)
	setattr(mainobj, 'filenames', filenames)
	if IsStr(pagearray[0].picturelink):
		setattr(mainobj, 'currpict', pagearray[0].picturelink)
	else:
		setattr(mainobj, 'currpict', filenames[int(pagearray[0].id)])
	
#	sdmid = 'sdm'
#	sdm = SessionDataManager(sdmid)
#	object._setObject(sdmid, sdm) # put it into lise folder
	
	if(len(errstr) > 0):
		newObj.freetext = self.absolute_url() + '/' + id + '/standard_error_message'
		errobj.error_message = errstr + '<br><br><h3>by babes</h3>'
		RESPONSE.redirect(self.absolute_url() + '/' + id + '/standard_error_message')
	else:
		RESPONSE.redirect(self.absolute_url() + '/' + id + '/main?theid=1')



########################################################################################
class Error_DTML(SimpleItem):
	"the ERROR message"
	meta_type = 'error_message'
	
	def __init__(self, id):
		self.id = id


########################################################################################
class TagHandler:
	def __init__(self):
		self.tags={}
		self.name=""
		self.index = ""
		self.url = ""
		self.startname = ""
		self.startindex = 0
		self.starturl = ""
		self.endname = ""
		self.endindex = 0
		self.endurl = ""
		self.chapterindex = 0
		self.currentchapter = 0


	def expat_start_element(self, name, attrs):
		global allobjects
		global objindex
		global currchapter
		global currobj
		global tagstr
		global onpage
		global onpagename
		global onpageindex
		global onpageurl
		global onchapter
		global onchaptername
		global onstart
		global onstartname
		global onstartindex
		global onstarturl
		global onend
		global onendname
		global onendindex
		global onendurl
		global errstr
		
		if name == 'page':
			onstart = False
			onpage = True
			currobj = PageObject()
			if onchapter:
				thelen = len(currchapter.chapterobjects)
				if thelen > 0:
					currobj.prevref = currchapter.chapterobjects[thelen - 1]
					currchapter.chapterobjects[thelen - 1].nextref = currobj
				currchapter.chapterobjects.append(currobj)
				currobj.chapterindex = currchapter.chapterindex
			else:
				thelen = len(allobjects)
				if thelen > 0:
					currobj.prevref = allobjects[thelen - 1]
					allobjects[thelen - 1].nextref = currobj
				allobjects.append(currobj)
		
		if name == 'chapter':
			onstart = False
			onend = False
			currobj = ChapterObject(objindex)
			objindex += 1
			if onchapter:
				currobj.upref = currchapter
				thelen = len(currchapter.chapterobjects)
				if thelen > 0:
					currobj.prevref = currchapter.chapterobjects[thelen - 1]
					currchapter.chapterobjects[thelen - 1].nextref = currobj
				currchapter.chapterobjects.append(currobj)
			else:
				allobjects.append(currobj)
				onchapter = True
			currchapter = currobj
		
		if name == 'name':
			tagstr = ""
			if onpage:
				onpagename = True
			else:
				if onchapter:
					if (not onstart) and (not onend):
						onchaptername = True
					else:
						if onstart:
							onstartname = True
						if onend:
							onendname = True
				else:
					errstr = errstr + 'ERROR in XML file: \"&lt;name&gt; tag outside &lt;page&gt; or &lt;chapter&gt;\"<br>'
			
		if name == 'index':
			tagstr = ""
			if onpage:
				onpageindex = True
			else:
				if onchapter:
					if onstart:
						if not onend:
							onstartindex = True
						else:
							onendindex = True
					else:
						errstr = errstr + 'ERROR in XML file: \"&lt;index&gt; tag inside chapter but outside &lt;start&gt; or &lt;end>\"<br>'
				else:
					errstr = errstr + 'ERROR in XML file: \"&lt;index&gt; tag outside &lt;page&gt; or &lt;chapter&gt;\"<br>'
			
		if name == 'url':
			tagstr = ""
			if onpage:
				onpageurl = True
			else:
				if onchapter:
					if onstart:
						if not onend:
							onstarturl = True
						else:
							onendurl = True
					else:
						errstr = errstr + 'ERROR in XML file: \"&lt;url&gt; tag inside chapter but outside &lt;start&gt; or &lt;end&gt;\"<br>'
				else:
					errstr = errstr + 'ERROR in XML file: \"&lt;url&gt; tag outside &lt;page&gt; or &lt;chapter&gt;\"<br>'
		
		if name == 'start':
			if onchapter:
				onstart = True
				currobj = StartEndObject()
				thelen = len(currchapter.chapterobjects)
				if thelen > 0:
					currobj.prevref = currchapter.chapterobjects[thelen - 1]
					currchapter.chapterobjects[thelen - 1].nextref = currobj
				currchapter.chapterobjects.append(currobj)
			else:
				errstr = errstr + 'ERROR in XML file: \"&lt;start&gt; tag outside &lt;chapter&gt;\"<br>'
			
		if name == 'end':
			if onchapter:
				if onstart:
					onend = True
				else:
					errstr = errstr + 'ERROR in XML file: \"&lt;end&gt; tag without &lt;start&gt;\"<br>'
			else:
				errstr = errstr + 'ERROR in XML file: \"&lt;end&gt; tag outside &lt;chapter&gt;\"<br>'
	
	
	def characters(self, ch):
		global tagstr
		tagstr += ch


	def expat_endElement(self, name):
		global allobjects
		global objindex
		global currchapter
		global currobj
		global tagstr
		global onpage
		global onpagename
		global onpageindex
		global onpageurl
		global onchapter
		global onchaptername
		global onstart
		global onstartname
		global onstartindex
		global onstarturl
		global onend
		global onendname
		global onendindex
		global onendurl
		global errstr
		
#		errstr = errstr + 'end: ' + name + ':<br>'
		if name == 'page':
			onpage = False
			
		if name == 'chapter':
			objindex -= 1
			if objindex <= 0:
				onchapter = False
				currchapter = 0
			else:
				currchapter = currchapter.upref
			
		if name == 'name':
			tagstr = normalize_whitespace(tagstr)
			if onpagename:
				onpagename = False
				currobj.name = tagstr
			if onchaptername:
				if currobj.typestr == 'chapter':
					currobj.name = tagstr
				onchaptername = False
			if onstartname:
				if currobj.typestr == 'start':
					currobj.startname = tagstr
				onstartname = False
			if onendname:
				if currobj.typestr == 'start':
					currobj.endname = tagstr
				onendname = False
			
		if name == 'index':
			tagstr = normalize_whitespace(tagstr)
			if onpageindex:
				if IsInt(tagstr):
					currobj.index = int(tagstr) - 1
				else:
					errstr = errstr + 'ERRRRROR: cannot extract number from page index.<br>'
				onpageindex = False
				
			if onstartindex:
				if IsInt(tagstr):
					currobj.startindex = int(tagstr) - 1
				else:
					errstr = errstr + 'ERRRRROR: cannot extract startnumber from startindex.<br>'
				onstartindex = False
				
			if onendindex:
				if IsInt(tagstr):
					currobj.endindex = int(tagstr) - 1
				else:
					errstr = errstr + 'ERRRRROR: cannot extract endnumber from endindex.<br>'
				onendindex = False
			
		if name == 'url':
			tagstr = normalize_whitespace(tagstr)
			if onpageurl:
				currobj.url = tagstr
				onpageurl = False
			if onstarturl:
				currobj.starturl = tagstr
				onstarturl = False
			if onendurl:
				currobj.endurl = tagstr
				onendurl = False
			
		if name == 'end':
			onstart = False
			onend = False


########################################################################################
def normalize_whitespace(text):
    "Remove redundant whitespace from a string"
    return ' '.join(text.split())


########################################################################################
def IsInt(str):
	""" Is the given string an Integer? """
	try: int(str)
	except ValueError:
		return 0
	else:
		return 1

########################################################################################
def IsStr(str):
	""" Is the given string really a string? """
	try: str + ''
	except: return 0
	else: return 1

########################################################################################
class PageObject:
	def __init__(self):
		self.name = ""
		self.index = 0
		self.pictindex = 0
		self.url = ""
		self.isselected = False
		self.typestr = "page"
		self.chapterindex = 0
		self.prevref = 0
		self.nextref = 0
		self.chapref = 0
		
	def CreatePage(self, level):
		global counter
		global counterid
		global gbaseurl
		global gpicpath
		global pagearray
		global errstr
		
		self.chapterindex = level
		pageelement = PageElement()
		pageelement.id = str(counterid)
		pageelement.type = "P"
		pageelement.name = self.name
		if IsStr(self.url):
			if len(self.url) > 0:
				if IsStr(gbaseurl):
					if len(gbaseurl) > 0:
						if gbaseurl[-1] == '/':
							pageelement.picturelink = gbaseurl + self.url
						else:
							pageelement.picturelink = gbaseurl + '/' + self.url
				else:
					pageelement.picturelink = self.url
			else:
				if IsStr(gbaseurl):
					pageelement.picturelink = gbaseurl
		else:
			pageelement.picturelink = gbaseurl
			
		pageelement.level = self.chapterindex

		if IsInt(self.index):
			if int(self.index) >= 0:
				pageelement.pictindex = int(self.index)
				if IsStr(pageelement.picturelink):
					if len(pageelement.picturelink) > 0:
						pageelement.picturelink = pageelement.picturelink + str(self.index + 1)
				
			else:
				pageelement.pictindex = '9999'
		else:
			pageelement.pictindex = '9999'

		if pageelement.level == 0:
			pageelement.open = 1
		else:
			pageelement.open = 0
			
		pagearray.append(pageelement)
		counter = counter + 1
		counterid = counterid + 1


########################################################################################
class ChapterObject:
	def __init__(self, chapterindex):
		self.name = ""
		self.typestr = "chapter"
		self.chapterindex = chapterindex
		self.isselected = False
		self.isopen = False
		self.prevref = 0
		self.nextref = 0
		self.upref = 0
		self.chapterobjects = []
		self.pages_subchapters = []
		
	def parseobjects(self):
		thelen = len(self.chapterobjects)
		if hasattr(self, 'chapterobjects'):
			count = 0
			for i in self.chapterobjects:
				count += 1
				if hasattr(self, 'typestr'):
					if i.typestr == 'page':
						self.pages_subchapters.append(i)
					if i.typestr == 'chapter':
						i.parseobjects()
					if i.typestr == 'start':
						i.startindex = int(i.startindex)
						if i.startindex > 0:
							i.endindex = int(i.endindex)
							if i.endindex > 0:
								if i.endindex < i.startindex:
									errstr = errstr + 'ERROR in XML file: \"&lt;start&gt; index bigger then &lt;end&gt; index.\"<br>'
							else:
								startfound = False
								for j in range(count, len(self.chapterobjects)):
									if self.chapterobjects[j].typestr == 'start':
										startfound = True
										i.endindex = self.chapterobjects[j].startindex - 1
										break
									if self.chapterobjects[j].typestr == 'page':
										i.endindex = self.chapterobjects[j].index - 1	
										startfound = True
										break
										
								if not startfound:
									errstr = errstr + 'ERROR in XML file: \"&lt;start&gt; tag in chapter has no end-tag.\"<br>'
#						print ' startname: ', i.startname
#						print 'startindex: ', i.startindex
#						print '    endurl: ', i.starturl
#						print '   endname: ', i.endname
#						print '  endindex: ', i.endindex
#						print '    endurl: ', i.endurl, '\n'

	def CreateChapter(self):
		global counter
		global counterid
		global gbaseurl
		global pagearray
		global errstr

		thelen = len(self.chapterobjects)
		chapelement = PageElement()
		chapelement.name = self.name
		chapelement.id = counterid
		chapelement.type = "C"
		chapelement.level = self.chapterindex
		chapelement.open = 0
		chapelement.picturelink = ''
		chapelement.pictindex = 9999;
		pagearray.append(chapelement)
		counterid = counterid + 1
		if hasattr(self, 'chapterobjects'):
			count = 0
			for i in self.chapterobjects:
				count += 1
				if hasattr(self, 'typestr'):
					if i.typestr == 'page':
						i.CreatePage(self.chapterindex + 1)
					if i.typestr == 'chapter':
						i.CreateChapter()
					if i.typestr == 'start':
						namenumber = counter
						nameprev = ""
						urlstart = 0
						urlend = 0
						if i.startname != '':
							t = re.search(r'\d*$', i.startname)
							if not IsInt(t.group(0)):
								t = re.sub('(\..*$)', '', s)
								t = re.search(r'\d*$', t)
								if IsInt(t.group(0)):
									namenumber = int(t.group(0))
									nameprev = re.sub(r'\d*$', '', i.startname)
								else:
									errstr = errstr + 'ERRRRROR: cannot extract startnumber.<br>'
							else:
								namenumber = int(t.group(0))
								nameprev = re.sub(r'\d*$', '', i.startname)

						if ( (i.startindex > 0) and (i.endindex > 0) and (i.endindex > i.startindex) ):
							currcount = 0
							for j in range(i.startindex, i.endindex + 1):
								currnumber = namenumber + currcount
								pageelement = PageElement()
								pageelement.name = nameprev + str(currnumber)
								pageelement.level = self.chapterindex + 1
								pageelement.id = counterid
								pageelement.type = "P"
								pageelement.open = 0
								pageelement.pictindex = j
								pageelement.picturelink = gbaseurl + str(j)
								pagearray.append(pageelement)
								currlen = len(pagearray)
								if pagearray[currlen - 2].type == 'C':
									pagearray[currlen - 2].pictindex = j
									pagearray[currlen - 2].picturelink = gbaseurl + str(j)
								counter = counter + 1
								counterid = counterid + 1
								currcount = currcount + 1
						else:
							t = re.search(r'\d*$', i.starturl)
							if not IsInt(t.group(0)):
								t = re.sub('(\..*$)', '', s)
								t = re.search(r'\d*$', t)
								if IsInt(t.group(0)):
									urlstart = int(t.group(0))
								else:
									errstr = errstr + 'ERRRRROR: cannot extract number from starturl.<br>'
							else:
								urlstart = int(t.group(0))
							t = re.search(r'\d*$', i.endurl)
							if not IsInt(t.group(0)):
								t = re.sub('(\..*$)', '', s)
								t = re.search(r'\d*$', t)
								if IsInt(t.group(0)):
									urlend = int(t.group(0))
								else:
									errstr = errstr + 'ERRRRROR: cannot extract from endnumber.<br>'
							else:
								urlend = int(t.group(0))
							if ( (urlstart > 0) and (urlend > 0) and (urlend > urlstart) ):
								for j in range(urlstart, urlend):
									pageelement = PageElement()
									currnumber = namenumber + j
									pageelement.name = nameprev + str(currnumber)
									pageelement.level = self.chapterindex + 1
									pageelement.id = counterid
									pageelement.type = "P"
									pageelement.open = 0
									pageelement.pictindex = j
									pageelement.picturelink = gbaseurl + str(j)
									pagearray.append(pageelement)

									counter = counter + 1
									counterid = counterid + 1
		

########################################################################################
class StartEndObject:
	def __init__(self):
		self.startname = ""
		self.startindex = 0
		self.starturl = ""
		self.endname = ""
		self.endindex = 0
		self.endurl = ""
		self.typestr = "start"
		self.prevref = 0
		self.nextref = 0
		self.chapref = 0
		

########################################################################################
class PageElement:
	def __init__(self):
		self.id = ""
		self.type = ""
		self.name = ""
		self.picturelink = ""
		self.pictindex = 0
		self.level = 0
		self.open = 0

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