Diff for /ECHO_content/VLPExtension.py between versions 1.40 and 1.65

version 1.40, 2005/02/28 14:09:55 version 1.65, 2007/10/04 18:45:33
Line 16  import xml.dom.minidom Line 16  import xml.dom.minidom
 import urllib  import urllib
 import xmlrpclib  import xmlrpclib
 import vlp_xmlhelpers  import vlp_xmlhelpers
   import sys
   import os
   from stat import *
 from types import *  from types import *
 from Globals import package_home  from Globals import package_home
   import transaction
   
   
 def lemmatize(str):  def lemmatize(str):
Line 142  def manage_addSendMailForm(self, id, toA Line 145  def manage_addSendMailForm(self, id, toA
   
           
 class VLP_essay(Folder):  class VLP_essay(Folder):
     """classe für VLP essays"""      """classe fr VLP essays"""
   
     meta_type="VLP_essay"      meta_type="VLP_essay"
   
Line 227  class VLP_essay(Folder): Line 230  class VLP_essay(Folder):
                           
         pages.sort(sortFind)          pages.sort(sortFind)
         #print str(pages[int(pagenum)][1]())          #print str(pages[int(pagenum)][1]())
           
         if pages[int(pagenum)-1][1].meta_type=='File':          if pages[int(pagenum)-1][1].meta_type=='File':
                   
         #return makeXML(str(pages[int(pagenum)-1][1]))          #return makeXML(str(pages[int(pagenum)-1][1]))
Line 259  class VLP_essay(Folder): Line 263  class VLP_essay(Folder):
             retstr=url+"?p="+str(int(pagenum)+1)              retstr=url+"?p="+str(int(pagenum)+1)
             return retstr              return retstr
                   
       def lastURL(self,pagenum,url):
           # teste ob performance ok, sonst in variable
           pages=len(self.ZopeFind(self,obj_metatypes=['DTML Document','File'])) 
           
           return url+"?p="+str(pages)
               
     def previousURL(self,pagenum,url):      def previousURL(self,pagenum,url):
                   
         if int(pagenum)-1 > 0:          if int(pagenum)-1 > 0:
Line 338  def manage_addVLP_encyc(self, id,title,l Line 348  def manage_addVLP_encyc(self, id,title,l
     if RESPONSE is not None:      if RESPONSE is not None:
         RESPONSE.redirect('manage_main')          RESPONSE.redirect('manage_main')
           
   class VLP_subcollection(ECHO_collection):
           """ subcollection of elements"""
   
           meta_type="VLP_subcollection"
           
           def getVLPSubcollectionToc(self,type):
               
               #different ordering depending on the type
               if(type == "(Collection)"):
                  sort= "shortreference"
               else:
                  sort = "startpages"
              
              #content of journals also displayed if not online
              
               if (type == "(JournalVolume)"):
                  online =""
               else:
                  online ="AND online = 1"
               sort=self.collectionSort(type)
           
               item = [x for x in self.ZSQLSimpleSearch("""SELECT * FROM vl_literature 
                                    WHERE volumeid ~ '%s\\\\M' """%self.getId()
                                    + """ %s AND not referenceType='%s' """%(online,type)
                                    + """ORDER BY """ + sort)]
           
               tocItem = [x for x in self.ZSQLSimpleSearch("""SELECT * FROM vl_literature 
                                    WHERE reference = '%s' """%self.getId()
                                    + """AND online = 1 AND referenceType='%s' """%type
                                    + """ORDER BY """ + sort)]
               
               
   
               return tocItem+item
               
           def checkForFrontMatter(self,item):
                   """Teste ob Frontmatter exists"""
                   if not item==self.getId():
                           return False
                   
                   if self.ZopeFind(self,obj_ids=[self.getId()]):
                           return True
                   else:
                           return False
                   
           def generateSubCollectionFromDB(self):
                   """erzeuge subcollection"""
                   for item in self.ZSQLSimpleSearch("select * from vl_literature where volumeid like '%s'"%self.id):
                           manage_addECHO_link(self,item.reference,item.titlerefdisplay,item.titlerefdisplay)
   
   
           def index_html(self):
                   """erzeuge darstellung"""
                   
                   if hasattr(self,'subCollection_template.html'):
                           return getattr(self,'subCollection_template.html')()
   
                   pt=zptFile(self, 'vlp/subCollection_template.zpt')
                   return pt()
   
   
   def manage_addVLP_subCollection(self,id,title,label,RESPONSE=None):
   
           self._setObject(id,VLP_subcollection(id,title,label))
   
           if RESPONSE is not None:
                   RESPONSE.redirect('manage_main')
   
   
 class VLP_collection(ECHO_collection):  class VLP_collection(ECHO_collection):
     """VLP spezifische Erweiterung der Collection"""      """VLP spezifische Erweiterung der Collection"""
   
       
     meta_type="VLP_collection"      meta_type="VLP_collection"
     manage_options=ECHO_collection.manage_options+(      manage_options=ECHO_collection.manage_options+(
         {'label':'Change Path','action':'VLP_path_configForm'},          {'label':'Change Path','action':'VLP_path_configForm'},
Line 349  class VLP_collection(ECHO_collection): Line 428  class VLP_collection(ECHO_collection):
         {'label':'Update Metadata','action':'updateCollectionMD'},          {'label':'Update Metadata','action':'updateCollectionMD'},
         )          )
   
   
   
       def generateSubCollections(self,errorsTXT="",forceUpdate=False,RESPONSE=None):
           """erzeuge subcollectionen"""
           logging.debug("generateSubCollections")
           founds=self.ZSQLSimpleSearch("select * from vl_literature where referencetype in ('(Edited Book)','(Book)','(Collection)','(JournalVolume)','(Generic Container)')")
           
           if RESPONSE is not None:
               RESPONSE.setHeader('Content-Type','text/html')
               self.REQUEST.RESPONSE.write("<h2>Create Subcollections</h2>\n")
           for found in founds:
               try:
                   litid = str(found.reference)
                   foundCol=self.ZopeFind(self,obj_ids=[litid])
                   if foundCol:
                       col = foundCol[0][1]
                       logging.debug("generateSubCollections: subcollection %s exists (%s)"%(col.getId(),found.reference))
                       if (col.title != found.titlerefdisplay) or (col.label != found.titlerefdisplay):
                           # subcollection seems to have changed    
                           logging.debug("generateSubCollections: subcollection has changed, recreating!")
                           self.manage_delObjects([foundCol[0][0]])
                           manage_addVLP_subCollection(self,litid,found.titlerefdisplay,found.titlerefdisplay)
                   else:
                       logging.debug("generateSubCollections: creating new subcollection %s"%found.reference)
                       manage_addVLP_subCollection(self,litid,found.titlerefdisplay,found.titlerefdisplay)
                   
                   #teste ob es Images auf dem Server gibt mit gleichem Namen (frontmatter)
                   if os.path.exists(os.path.join(self.vlp_basis,litid)):
                       logging.debug("generateSubCollections: found frontmatter in %s"%litid)
                       obj=getattr(self,litid)
                       if not self.ZopeFind(obj,obj_ids=[litid]):
                           metalink=self.REQUEST['URL1']+"/"+litid+"/"+litid+"/index_meta"
                           newObj=VLP_resource(litid,'',metalink,litid,litid,litid,'generated','book','','','','','','')
                           obj._setObject(litid,newObj)
                           
                       genObj=getattr(obj,litid)
                       genObj.createIndexFile(forceUpdate=forceUpdate)
   
                   if RESPONSE is not None:
                       self.REQUEST.RESPONSE.write("<p>%s</p>\n"%litid)
   
               except:
                   error=sys.exc_info()[0:2]
                   logging.error("generateSubCollections: ERROR in %s"%litid)
                   if RESPONSE is not None:
                       RESPONSE.write("<p>(ERROR (%s): %s %s)</p>\n"%(litid,error[0],error[1]))
                   #logging.error("generateSubCollections: %s %s"%error)
                   #self.REQUEST.RESPONSE.write("(ERROR (%s): %s %s)\n"%(litid,repr(error[0]),repr(error[1])))
                   errorsTXT+="<p>ERROR: No subcollection of %s (ERROR: %s %s)</p>\n"%(litid,error[0],error[1])
                   #errorsTXT+="<p>No subcollection of %s  "%litid+"(ERROR: %s %s)</p>"%error
                   
           return errorsTXT
               
     def VLP_path_configForm(self):      def VLP_path_configForm(self):
         """change pt"""          """change pt"""
         path=PageTemplateFile(os.path.join(package_home(globals()),'vlp','ChangeVLPPath.zpt')).__of__(self)          pt=PageTemplateFile(os.path.join(package_home(globals()),'vlp','ChangeVLPPath.zpt')).__of__(self)
         return pt()          return pt()
   
     def VLP_path_config(self,path,RESPONSE=None):      def VLP_path_config(self,path,RESPONSE=None):
         """config"""          """config"""
         self.path=path          self.vlp_basis=path
         if RESPONSE is not None:          if RESPONSE is not None:
             RESPONSE.redirect('manage_main')              RESPONSE.redirect('manage_main')
   
     def updateCollection(self,RESPONSE=None):      def updateCollection(self,forceUpdate=False,RESPONSE=None):
         """liest verzeichnisse aus dem pfad und legt sie dann als objekte in den ordner"""          """liest verzeichnisse aus dem pfad und legt sie dann als objekte in den ordner"""
         files=os.listdir(self.path)          errorsTXT="<h2>Errors</h2>"
         for fileName in files:          if RESPONSE is not None:
               RESPONSE.setHeader('Content-Type','text/html')
               RESPONSE.write("<html><body>")
                           
           files=os.listdir(self.vlp_basis)
           for fileName in files:
             if fileName[0:3]=="lit":              if fileName[0:3]=="lit":
                   
                 metalink=self.REQUEST['URL1']+"/"+fileName+"/index_meta"                  metalink=self.REQUEST['URL1']+"/"+fileName+"/index_meta"
                   try:
         if not hasattr(self,fileName):          if not hasattr(self,fileName):
                           # create new resource
                           logging.debug("updateCollection: new %s"%fileName)
                           if RESPONSE is not None:
                               RESPONSE.write("<p>new: %s</p>\n"%fileName)
             newObj=VLP_resource(fileName,'',metalink,fileName,fileName,fileName,'generated','book','','','','','','')              newObj=VLP_resource(fileName,'',metalink,fileName,fileName,fileName,'generated','book','','','','','','')
             self._setObject(fileName,newObj)              self._setObject(fileName,newObj)
                 RESPONSE.write("got: %s\n"%fileName)                  
                       if RESPONSE is not None:
                           RESPONSE.write("<p>got: %s "%fileName)
                 genObj=getattr(self,fileName)                  genObj=getattr(self,fileName)
                 genObj.createIndexFile()                      logging.debug("updateCollection: inspecting %s"%fileName)
                       # create index
                       if hasattr(genObj,'createIndexFile'):
                           try:
                               logging.debug("updateCollection: creating index for %s"%fileName)
                               msg = genObj.createIndexFile(forceUpdate=forceUpdate)
                               if msg and RESPONSE is not None:
                                   RESPONSE.write(msg)
                           except:
                               error=sys.exc_info()[0:2]
                               if RESPONSE is not None:
                                   RESPONSE.write("(ERROR (%s): %s %s) "%(fileName,error[0],error[1]))
                               errorsTXT+="<p>ERROR creating index for %s "%fileName+"(ERROR: %s %s)</p>\n"%error
   
                       # update pageSizeSum for subcollections
                       if genObj.meta_type=="VLP_subcollection":
         if RESPONSE is not None:          if RESPONSE is not None:
             RESPONSE.redirect('manage_main')                              RESPONSE.write(" is subcollection")
                           logging.debug("updateCollection: %s is subcollection"%fileName)
                           genObj.pageSizeSum=getattr(genObj,fileName).getPageSizeSum()
                       else:
                           genObj.pageSizeSum=genObj.getPageSizeSum()
   
                       if RESPONSE is not None:
                           RESPONSE.write("</p>\n")
                          
                   except:
                       error=sys.exc_info()[0:2]
                       logging.error("updateCollection: ERROR in %s (%s %s)"%(fileName,error[0],error[1]))
                       if RESPONSE is not None:
                           RESPONSE.write("<p>(ERROR (%s): %s %s)</p>\n"%(fileName,error[0],error[1]))
                       errorsTXT+="<p>File not created:%s  (ERROR: %s %s)</p>\n"%(fileName,error[0],error[1])
                               
           # update subcollections    
           errorsTXT+=self.generateSubCollections(forceUpdate=forceUpdate,RESPONSE=RESPONSE)
           errorsTXT+="\n"
           if RESPONSE is not None:
               RESPONSE.write(errorsTXT)
               RESPONSE.write("</body></html>")
   
     def updateCollectionMD(self,RESPONSE=None):      def updateCollectionMD(self,RESPONSE=None):
         """updateMD"""          """updateMD"""
         files=os.listdir(self.path)          files=os.listdir(self.vlp_basis)
         for fileName in files:          for fileName in files:
             if fileName[0:3]=="lit":              if fileName[0:3]=="lit":
                 genObj=getattr(self,fileName)                  genObj=getattr(self,fileName)
Line 433  class VLP_resource(ECHO_resource,Cacheab Line 610  class VLP_resource(ECHO_resource,Cacheab
   
     meta_type="VLP_resource"      meta_type="VLP_resource"
   
     vlp_basis="/mpiwg/online/permanent/vlp"      #vlp_basis="/mpiwg/online/permanent/vlp"
   
           
     referencetypes=[]      referencetypes=[]
Line 448  class VLP_resource(ECHO_resource,Cacheab Line 625  class VLP_resource(ECHO_resource,Cacheab
   
     def getImagePath(self):      def getImagePath(self):
         """Pfad zu den Images"""          """Pfad zu den Images"""
               
         if os.path.isdir(os.path.join(self.vlp_basis,self.resourceID,'pageimg')):          if os.path.isdir(os.path.join(self.vlp_basis,self.resourceID,'pageimg')):
             return os.path.join(self.vlp_basis,self.resourceID,'pageimg')              return os.path.join(self.vlp_basis,self.resourceID,'pageimg')
         elif os.path.isdir(os.path.join(self.vlp_basis,self.resourceID,'pagesHi')):          elif os.path.isdir(os.path.join(self.vlp_basis,self.resourceID,'pagesHi')):
Line 579  class VLP_resource(ECHO_resource,Cacheab Line 757  class VLP_resource(ECHO_resource,Cacheab
                           
         return 0          return 0
           
       def getPageSizeSum(self):
               """generate average page size"""
   
               #size of hi resolution
               files=[]
               try:
                       pathHi=os.path.join(self.vlp_basis,self.resourceID,'pagesHi')
                       files=os.listdir(pathHi)
                       hi=0
                       for f in files:
                               hi+=os.stat(os.path.join(pathHi,f))[ST_SIZE]
   
               except:
                       hi=0
   
               #size of hi resolution
               try:
                       pathHi=os.path.join(self.vlp_basis,self.resourceID,'pagesLo')
                       files=os.listdir(pathHi)
                       lo=0
                       for f in files:
                               lo+=os.stat(os.path.join(pathHi,f))[ST_SIZE]
   
               except:
                       lo=0
   
               
               return (hi,lo,len(files))
                       
   
       def getPageWeights(self):
               """average Page sizes in kBytes"""
       
               res=getattr(self,'pageSizeSum',(0,0,1))
               return (res[0]/(1024*res[2]),res[1]/(1024*res[2]))
                               
               
               
     def dir2index(self):      def dir2index(self):
         """dir to index"""          """dir to index"""
   
           excludeNames=['Icon']
                   
           
         def calculateName(str):          def calculateName(str):
         name=os.path.splitext(str[1:])[0]          name=os.path.splitext(str[1:])[0]
             ret="%s: %s"%(str[0],name)              ret="%s: %s"%(str[0],name)
Line 596  class VLP_resource(ECHO_resource,Cacheab Line 815  class VLP_resource(ECHO_resource,Cacheab
         temp=[]          temp=[]
     ret.sort()      ret.sort()
         for x in ret:          for x in ret:
             if not (x[0]=="."):              if (not (x[0] in ('.',':'))) and (not x[0:4] in excludeNames):
                   
                 temp.append((calculateName(x),os.path.splitext(x)[0]))                  temp.append((calculateName(x),os.path.splitext(x)[0]))
         return temp          return temp
   
Line 666  class VLP_resource(ECHO_resource,Cacheab Line 884  class VLP_resource(ECHO_resource,Cacheab
     def readIndexFile(self,url=None):      def readIndexFile(self,url=None):
         """reads the indexfile. presently url not None isn't implemented. In the future url can be defined."""          """reads the indexfile. presently url not None isn't implemented. In the future url can be defined."""
     if not url:      if not url:
             url=self.absolute_url()+"/index.xml"              urlTmp=self.absolute_url()+"/index.xml"
   
     if self.ZCacheable_isCachingEnabled():      if self.ZCacheable_isCachingEnabled():
                           
             result = self.ZCacheable_get(view_name=url)              result = self.ZCacheable_get(view_name=urlTmp)
             if result is not None:              if result is not None:
                 # Got a cached value.                  # Got a cached value.
                 return result                  return result
   
         pagelist=[]          pagelist=[]
         
         fh=ECHO_helpers.urlopen(url)          if not url:
   
               xmlTxt=getattr(self,'index.xml')()
               dom=xml.dom.minidom.parseString(xmlTxt)
           else:            
               fh=ECHO_helpers.urlopen(urlTmp)
         dom=xml.dom.minidom.parse(fh)          dom=xml.dom.minidom.parse(fh)
                   
                   
Line 687  class VLP_resource(ECHO_resource,Cacheab Line 910  class VLP_resource(ECHO_resource,Cacheab
         fileName=page.getAttribute('file')          fileName=page.getAttribute('file')
             pagelist.append((pageNum,text,fileName))              pagelist.append((pageNum,text,fileName))
   
     self.ZCacheable_set(pagelist,view_name=url)          self.ZCacheable_set(pagelist,view_name=urlTmp)
         return pagelist           return pagelist 
   
     def getFileName(self):      def getFileName(self):
Line 699  class VLP_resource(ECHO_resource,Cacheab Line 922  class VLP_resource(ECHO_resource,Cacheab
        pageinfo=self.readIndexFile()[pn-1]         pageinfo=self.readIndexFile()[pn-1]
        return pageinfo[2]         return pageinfo[2]
         
     def createIndexFile(self,RESPONSE=None):      def createIndexFile(self,forceUpdate=False,RESPONSE=None):
         """create index file"""          """create index file"""
           logging.debug("createindexfile of %s"%self.id)
   
           if hasattr(self,'index.xml'):
               # index exists
               zt=getattr(self,'index.xml')
               if not forceUpdate:
                   # check if directory is newer (self.imagePath sould be set by now)
                   imgdir = os.path.join(self.vlp_basis, self.resourceID, self.imagePath)
                   dirtime = os.path.getmtime(imgdir)
                   zttime = zt.bobobase_modification_time()
                   logging.debug("createindexfile: dir %s of %s index of %s"%(imgdir,dirtime,zttime))
                   if dirtime < zttime:
                       # nothing to do
                       logging.debug("createindexfile: dir %s older than index"%(imgdir))
                       return "index is up to date"
                   
         pt=PageTemplateFile(os.path.join(package_home(globals()),'vlp','index_template.zpt')).__of__(self)()          else:
               # create new index template
   
           
         if not hasattr(self,'index.xml'):  
             zt=ZopePageTemplate('index.xml')              zt=ZopePageTemplate('index.xml')
             self._setObject('index.xml',zt)              self._setObject('index.xml',zt)
         else:  
             zt=getattr(self,'index.xml')  
               
                           
           # fill index template
           pt=PageTemplateFile(os.path.join(package_home(globals()),'vlp','index_template.zpt')).__of__(self)()
           #logging.debug("createindexfile uses %s"%pt)
         zt.pt_edit(pt, 'text/xml')          zt.pt_edit(pt, 'text/xml')
           transaction.get().commit()
   
         if RESPONSE is not None:          if RESPONSE is not None:
             RESPONSE.redirect('manage_main')              RESPONSE.redirect('manage_main')

Removed from v.1.40  
changed lines
  Added in v.1.65


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