Diff for /ZSQLExtend/ZSQLExtend.py between versions 1.56 and 1.72

version 1.56, 2005/01/25 19:30:11 version 1.72, 2005/11/09 10:47:09
Line 7  import string Line 7  import string
 import sys  import sys
 #from pyPgSQL import libpq  #from pyPgSQL import libpq
 from AccessControl import getSecurityManager  from AccessControl import getSecurityManager
   from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate
 from Products.PageTemplates.PageTemplateFile import PageTemplateFile  from Products.PageTemplates.PageTemplateFile import PageTemplateFile
   
 from Products.ZSQLMethods.SQL import SQLConnectionIDs  from Products.ZSQLMethods.SQL import SQLConnectionIDs
   from xml.sax.saxutils import escape
   from types import *
 import Shared.DC.ZRDB.DA  import Shared.DC.ZRDB.DA
 import zLOG  import zLOG
 import os.path  import os.path
 import os  import os
   from OFS.SimpleItem import SimpleItem
   
 def analyseIntSearch(word):  def analyseIntSearch(word):
     #analyse integer searches      #analyse integer searches
Line 39  def sql_quote(v): Line 42  def sql_quote(v):
     quote_dict = {"\'": "''", "\\": "\\\\"}      quote_dict = {"\'": "''", "\\": "\\\\"}
     for dkey in quote_dict.keys():      for dkey in quote_dict.keys():
         if string.find(v, dkey) >= 0:          if string.find(v, dkey) >= 0:
             v=join(split(v,dkey),quote_dict[dkey])              v=string.join(string.split(v,dkey),quote_dict[dkey])
     return "'%s'" % v      return "'%s'" % v
   
 def showSQLConnectionIDs(self):  def showSQLConnectionIDs(self):
     return SQLConnectionIDs(self)      return SQLConnectionIDs(self)
   
   class ZSQLIndex(SimpleItem):
       """index"""
       meta_type="ZSQLIndex"
       
       def __init__(self,index,id,table=''):
           self.index=[x for x in index]
           self.id=id
           self.table=table
           
       def setIndex(self,index):
           self.index=[x for x in index]
           
       def getIndex(self):
           return self.index
   
 class ZSQLExtendFolder(Folder,Persistent, Implicit):  class ZSQLExtendFolder(Folder,Persistent, Implicit):
     """Folder"""      """Folder"""
     meta_type="ZSQLExtendFolder"      meta_type="ZSQLExtendFolder"
   
       def importXMLFile(self,table,containerTagName,file,identify=None,RESPONSE=None):
           #TODO: finish importXMLFile
           '''
           Import XML file into the table
           @param table: name of the table the xml shall be imported into
           @param containerTagName: XML-Tag which describes a dataset
           @param file: xmlfile handle
           @param identify: (optional) field res. tag which identifies a entry uniquely for updating purposes.
           @param RESPONSE: (optional)
           '''
           from xml.dom.pulldom import parseString
   
           doc=parseString(file.read())
           while 1:
               node=doc.getEvent()
           
               if node is None:
                   break;
               else:
                   if node[1].nodeName==containerTagName:
                       doc.expandNode(node[1])
                   #fn=node[1].getAttribute("xml:id")
                   #nf=file("xtf/"+fn+".xtf",'w')
                   #nf.write("""<texts xmlns="http://emegir.info/xtf" xmlns:lem="http://emegir.info/lemma" >"""+node[1].toxml()+"</texts>")
                   #print "wrote: %s"%fn
                   
           
       def generateIndex(self,field,index_name,table,RESPONSE=None):
           """erzeuge index aus feld"""
           index={}
           founds=self.ZSQLSimpleSearch("""SELECT %s,oid FROM %s LIMIT 2000"""%(field,table))
   
           for found in founds:
               tmp=getattr(found,field,None)
               if tmp:
                   strings=tmp.split(" ")
                   for string in strings:
                       if index.get(string):
                           index[string].append(found.oid)
                       else:
                           index[string]=[found.oid]
                       RESPONSE.write(string+"\n")
               
           if not hasattr(self,index_name):
               obj=ZSQLIndex(index,index_name,table)
               self._setObject(index_name,obj)
                       
           self._getOb(index_name).setIndex(index)
           
       def getIndex(self,index_name):
           """getIndex"""
           founds=self.ZopeFind(self,obj_ids=[index_name])
           
           return founds[0][1].getIndex()
       
               
     def testneu(self):      def testneu(self):
         """test"""          """test"""
         relStatement="""period like '%s%%'"""          relStatement="""period like '%s%%'"""
Line 60  class ZSQLExtendFolder(Folder,Persistent Line 134  class ZSQLExtendFolder(Folder,Persistent
     def URLquote(self,txt):      def URLquote(self,txt):
         """urlquote"""          """urlquote"""
         return urllib.quote(txt)          return urllib.quote(txt)
       
     def searchRel(self,relStatement,statement,wherePart,classes):      def searchRel(self,relStatement,statement,wherePart,classes):
         """suche relative haufigkeiten"""          """suche relative haufigkeiten"""
         ret={}          ret={}
Line 201  class ZSQLExtendFolder(Folder,Persistent Line 276  class ZSQLExtendFolder(Folder,Persistent
         return ret          return ret
   
     def ZSQLSelectionFromCRList(self,fieldname,listField,boxType="checkbox",checked=None):      def ZSQLSelectionFromCRList(self,fieldname,listField,boxType="checkbox",checked=None):
         """generate select oprions form a cr seperated list"""          """generate select options from a cr seperated list"""
         fields=listField.split("\n")          fields=listField.split("\n")
         ret=""          ret=""
         for field in fields:          for field in fields:
Line 211  class ZSQLExtendFolder(Folder,Persistent Line 286  class ZSQLExtendFolder(Folder,Persistent
                 ret+="""<input name="%s" type="%s" value="%s">%s"""%(fieldname,boxType,field.encode('utf-8'),field.encode('utf-8'))                  ret+="""<input name="%s" type="%s" value="%s">%s"""%(fieldname,boxType,field.encode('utf-8'),field.encode('utf-8'))
         return ret          return ret
   
       def ZSQLSelectionFromSearchList(self,fieldname,results,fieldnameResult,boxType="checkbox",checked=None):
           """generate select options from a cr seperated list"""
   
     def ZSQLOptionsFromCRList(self,fieldname,listField, multiple=''):          ret=""
           if not results: return ""
           
           for result in results:
               field=getattr(result,fieldnameResult)
               if field:
                   if checked and (getattr(result,fieldnameResult) in checked.split("\n")):
                       ret+="""<input name="%s" type="%s" value="%s" checked>%s"""%(fieldname,boxType,field.encode('utf-8'),field.encode('utf-8'))
                   else:
                       ret+="""<input name="%s" type="%s" value="%s">%s"""%(fieldname,boxType,field.encode('utf-8'),field.encode('utf-8'))
           return ret
   
   
       def ZSQLOptionsFromCRList(self,fieldname,listField, multiple='',start=None,startValue=None,size=None,selected=None):
         """generate select oprions form a cr seperated list"""          """generate select oprions form a cr seperated list"""
         fields=listField.split("\n")          fields=listField.split("\n")
           if size:
               ret="""<select name="%s" %s size="%s" >
               """%(fieldname,multiple,size)
   
           else:
         ret="""<select name="%s" %s>          ret="""<select name="%s" %s>
             """%(fieldname,multiple)              """%(fieldname,multiple)
           if start:
           if start==' ':
           start=''
                   if not startValue:
                       startValue=start
                       
               ret+="""<option value="%s" >%s</option>"""%(startValue,start)
         for field in fields:          for field in fields:
               if selected and (field in selected.split("\n")):
                    ret+="""<option selected value="%s">%s</option>"""%(field.encode('utf-8'),field.encode('utf-8'))
               else:
             ret+="""<option value="%s">%s</option>"""%(field.encode('utf-8'),field.encode('utf-8'))              ret+="""<option value="%s">%s</option>"""%(field.encode('utf-8'),field.encode('utf-8'))
         ret+="""</select>"""          ret+="""</select>"""
         return ret          return ret
   
     def ZSQLOptionsFromSearchList(self,fieldname,results,fieldName,valueName=None,start=None, multiple='',startValue=None,additionalSelect=""):      def ZSQLOptionsFromSearchList(self,fieldname,results,fieldName,valueName=None,start=None, multiple='',startValue=None,additionalSelect="",size=None,linelen=None):
         """generate select options form a search list          """generate select options form a search list
         es wird          es wird
         <select name=fieldname mutiple>          <select name=fieldname mutiple>
Line 239  class ZSQLExtendFolder(Folder,Persistent Line 344  class ZSQLExtendFolder(Folder,Persistent
         """          """
         if not valueName:          if not valueName:
             valueName=fieldName              valueName=fieldName
                       if size:
               ret="""<select name="%s" %s size="%s" %s>
               """%(fieldname,multiple,size,additionalSelect)
           else:
         ret="""<select name="%s" %s %s>          ret="""<select name="%s" %s %s>
             """%(fieldname,multiple,additionalSelect)              """%(fieldname,multiple,additionalSelect)
         if start:          if start:
Line 253  class ZSQLExtendFolder(Folder,Persistent Line 361  class ZSQLExtendFolder(Folder,Persistent
             field=getattr(result,fieldName)              field=getattr(result,fieldName)
             fieldValue=getattr(result,valueName)              fieldValue=getattr(result,valueName)
             if fieldValue:              if fieldValue:
                   if not linelen:
                 ret+="""<option value="%s">%s</option>"""%(field,fieldValue)                  ret+="""<option value="%s">%s</option>"""%(field,fieldValue)
                   else:
                       mist = """%s"""%(fieldValue)
                       if len(mist) > string.atoi(linelen):
                           mist = mist[:string.atoi(linelen)]
                       ret+="""<option value="%s">%s</option>"""%(field,mist)
         ret+="""</select>"""          ret+="""</select>"""
         return ret          return ret
   
Line 305  class ZSQLExtendFolder(Folder,Persistent Line 419  class ZSQLExtendFolder(Folder,Persistent
         """inlinesearch"""          """inlinesearch"""
         qs=[]          qs=[]
                   
       
           
         #print "INLINE:",query          #print "INLINE:",query
         return self.ZSQLSimpleSearch(query)          return self.ZSQLSimpleSearch(query)
                   
     def ZSQLSimpleSearch(self,query=None):      
       def ZSQLSimpleSearch(self,query=None,max_rows=1000000):
         """simple search"""          """simple search"""
           
         if not query:          if not query:
             query=self.query              query=self.query
                   
         if (hasattr(self,"_v_searchSQL") and (self._v_searchSQL == None)) or (not hasattr(self,"_v_searchSQL")):          if (hasattr(self,"_v_searchSQL") and (self._v_searchSQL == None)) or (not hasattr(self,"_v_searchSQL")):
             self._v_searchSQL=Shared.DC.ZRDB.DA.DA("_v_searchSQL","_v_searchSQL",self.connection_id,"var","<dtml-var var>")  
   
               self._v_searchSQL=Shared.DC.ZRDB.DA.DA("_v_searchSQL","_v_searchSQL",self.getConnectionObj().getId(),"var","<dtml-var var>")
               
               self._v_searchSQL.max_rows_=max_rows
             try:              try:
                   
                 return self._v_searchSQL.__call__(var=query)                  return self._v_searchSQL.__call__(var=query)
             except :              except :
                 if sys.exc_info()[0]=="Database Error":                  if sys.exc_info()[0]=="Database Error":
                     try:                      try:
                         getattr(self,self.connection_id).manage_open_connection()                          self.getConnectionObj().manage_open_connection()
                     except: pass                      except:
                           zLOG.LOG("ZSQLSimpleSearch",zLOG.ERROR, '%s %s'%sys.exc_info()[:2])
         else:          else:
             try:              try:
                   self._v_searchSQL.max_rows_=max_rows
                   
                 return self._v_searchSQL.__call__(var=query)                  return self._v_searchSQL.__call__(var=query)
             except :              except :
                 if sys.exc_info()[0]=="Database Error":                  if sys.exc_info()[0]=="Database Error":
                     try:                      try:
                         getattr(self,self.connection_id).manage_open_connection()                          self.getConnectionObj().manage_open_connection()
                     except: pass                      except:
                           zLOG.LOG("ZSQLSimpleSearch",zLOG.ERROR, '%s %s'%sys.exc_info()[:2])
   
       def getConnectionObj(self):
           if hasattr(self,'connection_id'):
               return getattr(self,self.connection_id)
          
                                           
     def ZSQLSimpleSearch2(self,query=None):      def ZSQLSimpleSearch2(self,query=None):
         """ returrn SQLSearch"""          """ returrn SQLSearch"""
         #print "hi",query         
         if not query:          if not query:
             query=self.query              query=self.query
         if getattr(self,'_v_search',None):          if getattr(self,'_v_search',None):
Line 360  class ZSQLExtendFolder(Folder,Persistent Line 486  class ZSQLExtendFolder(Folder,Persistent
           
                   
                   
     def ZSQLAdd(self):      def ZSQLAdd(self,format=None,RESPONSE=None,**argv):
         """Neuer Eintrag"""          """Neuer Eintrag"""
         qs=self.REQUEST['QUERY_STRING']              
           qs_temp=[]
       
           for a in self.REQUEST.form.keys():
               qs_temp.append(a+"="+urllib.quote(str(self.REQUEST.form[a])))
   
           qs=string.join(qs_temp,",")
           
           for field in argv.keys():
                      if field[0]=="_":
                          fieldTmp="-"+field[1:]
                      else:
                          fieldTmp=field
                          
                      qs+=",%s=%s"%(fieldTmp,argv[field])
           
           
         addList={}          addList={}
         for q in qs.split("&"):          for q in qs.split(","):
             name=re.sub("r'+'"," ",q.split("=")[0].lower())              name=re.sub("r'+'"," ",q.split("=")[0].lower())
             value=q.split("=")[1]              value=q.split("=")[1]
         value=re.sub(r'\+'," ",value)          value=re.sub(r'\+'," ",value)
Line 373  class ZSQLExtendFolder(Folder,Persistent Line 515  class ZSQLExtendFolder(Folder,Persistent
                 table=urllib.unquote(value)                  table=urllib.unquote(value)
             elif name=="-format":              elif name=="-format":
                 format=urllib.unquote(value)                  format=urllib.unquote(value)
             elif (not name[0]=="-") and (not len(value)==0):              elif (not (name[0]=="-" or name[0]=="_")) and (not len(value)==0):
                 addList[urllib.unquote(name)]=urllib.unquote(value)                  addList[urllib.unquote(name)]=urllib.unquote(value)
   
         keyList=[]          keyList=[]
Line 386  class ZSQLExtendFolder(Folder,Persistent Line 528  class ZSQLExtendFolder(Folder,Persistent
         valueString=string.join(valueList,",")          valueString=string.join(valueList,",")
                   
         queryString="INSERT INTO %s (%s) VALUES (%s)"%(table,keyString,valueString)          queryString="INSERT INTO %s (%s) VALUES (%s)"%(table,keyString,valueString)
   
         self.ZSQLSimpleSearch(queryString)          self.ZSQLSimpleSearch(queryString)
         return self.REQUEST.RESPONSE.redirect(format)  
                   
     def ZSQLChange(self,**argv):          if RESPONSE and format:
               return RESPONSE.redirect(format)
           else:
               return True
           
       def ZSQLChange(self,format=None,RESPONSE=None,USE_FORM=None,**argv):
         """change entries"""          """change entries"""
         #qs=self.REQUEST['QUERY_STRING']          #qs=self.REQUEST['QUERY_STRING']
         # very bad hack          # very bad hack
         qs_temp=[]  
           
           qs_temp=[]
           if USE_FORM or RESPONSE:
         for a in self.REQUEST.form.keys():          for a in self.REQUEST.form.keys():
             qs_temp.append(a+"="+urllib.quote(str(self.REQUEST.form[a])))              qs_temp.append(a+"="+urllib.quote(str(self.REQUEST.form[a])))
   
         qs=string.join(qs_temp,"&")  
   
           
         #print "CHANGE QS",self.REQUEST          for field in argv.keys():
         #return self.REQUEST                  
                      if field[0]=="_":
                          fieldTmp="-"+field[1:]
                      else:
                          fieldTmp=field
                          
                      qs_temp.append("%s=%s"%(fieldTmp,argv[field]))
           
           
         changeList=[]          changeList=[]
         for q in qs.split("&"):          
           for q in qs_temp:
               
             name=urllib.unquote(re.sub("r'+'"," ",q.split("=")[0].lower()))              name=urllib.unquote(re.sub("r'+'"," ",q.split("=")[0].lower()))
             value=q.split("=")[1]              value="=".join(q.split("=")[1:])
             value=re.sub(r'\+'," ",value)              value=re.sub(r'\+'," ",value)
         value=urllib.unquote(value)          value=urllib.unquote(value)
           
         if name=="-table":          if name=="-table":
                 table=urllib.unquote(value)                  table=urllib.unquote(value)
             elif name=="-identify":              elif name=="-identify":
Line 416  class ZSQLExtendFolder(Folder,Persistent Line 574  class ZSQLExtendFolder(Folder,Persistent
                 identify=identify.split("=")[0]+"="+sql_quote(identify.split("=")[1])                  identify=identify.split("=")[0]+"="+sql_quote(identify.split("=")[1])
             elif name=="-format":              elif name=="-format":
                 format=urllib.unquote(value)                  format=urllib.unquote(value)
             elif (not name[0]=="-") and (not len(value)==0):              elif (not (name[0]=="-" or name[0]=="_")) and (not len(value)==0):
                 changeList.append("\""+name+"\"="+sql_quote(urllib.unquote(value)))                  changeList.append("\""+name+"\"="+sql_quote(urllib.unquote(value)))
                   
         changeString=string.join(changeList,",")          changeString=string.join(changeList,",")
         queryString="UPDATE %s SET %s WHERE %s"%(table,changeString,identify)          queryString="UPDATE %s SET %s WHERE %s"%(table,changeString,identify)
           
         self.ZSQLSimpleSearch(queryString)          self.ZSQLSimpleSearch(queryString)
         return self.REQUEST.RESPONSE.redirect(format)  
   
         
           if RESPONSE and format:
               return RESPONSE.redirect(format)
           else:
               return True
      
   
       def ZSQLFindIndexed(self,qs="",select="oid,*",storename=None,indexedFields=['data_line'],restrictField='id_text',**argv):
           """find2"""
           
           for index in self.ZopeFind(self,obj_ids=indexedFields):
               txt=argv.get(index[0],None)
               if txt:
                   oids=index[1].getIndex()[txt]
                   
           search1= self.ZSQLFind(qs=qs,select=select,storename=storename,tableExt=tableList[1],restrictField=restrictField,NoQuery='yes',NoLimit='yes',**argv)
        
           search2 = self.ZSQLFind(tableExt=tableList[0],qs=qs,select=select,storename=storename,restrictConnect=(tableList[0]+"."+restrictField,search1),**argv)
           return search2
   
     def ZSQLFind2(self,qs="",select="oid,*",storename=None,tableList=['cdli_translit','cdli_cat'],restrictField='id_text',**argv):      def ZSQLFind2(self,qs="",select="oid,*",storename=None,tableList=['cdli_translit','cdli_cat'],restrictField='id_text',**argv):
         """find2"""          """find2"""
Line 436  class ZSQLExtendFolder(Folder,Persistent Line 613  class ZSQLExtendFolder(Folder,Persistent
               
           
     def ZSQLFind(self,qs="",select="oid,*",storename=None,tableExt=None,NoQuery=None,NoLimit=None,restrictField=None,restrictConnect=None,filter=None,**argv):      def ZSQLFind(self,qs="",select="oid,*",storename=None,tableExt=None,NoQuery=None,NoLimit=None,restrictField=None,restrictConnect=None,filter=None,**argv):
         """Find"""          """search in database"""
   
         def delEmpty(list):          def delEmpty(list):
               """"loesche leere elemente aus der liste"""
             ret=[]              ret=[]
             for x in list:              for x in list:
                 splitted=x.split("=")                  splitted=x.split("=")
Line 446  class ZSQLExtendFolder(Folder,Persistent Line 624  class ZSQLExtendFolder(Folder,Persistent
                     ret.append(x)                      ret.append(x)
             return ret              return ret
   
   
   
         #self.REQUEST.SESSION['come_from_search']="no" # zuruecksetzen  
         if qs=="":          if qs=="":
                         #kein querystring ubergeben 
            if self.REQUEST['QUERY_STRING']:             if self.REQUEST['QUERY_STRING']:
                qs=self.REQUEST['QUERY_STRING']                 qs=self.REQUEST['QUERY_STRING']
   
                  
                qs=string.join(qs.split("&"),",")                 qs=string.join(qs.split("&"),",")
   
                for field in argv.keys():                 for field in argv.keys():
Line 486  class ZSQLExtendFolder(Folder,Persistent Line 660  class ZSQLExtendFolder(Folder,Persistent
                           
                   
                   
         qs=re.sub("\\+"," ",qs)# Austauschen da Leerzeichen bei http-get durch + ersetzt wird, generell sollte alles auf post umgeschrieben werden. vom search formular.          qs=re.sub("\\+"," ",qs)#TODO: Austauschen da Leerzeichen bei http-get durch + ersetzt wird, generell sollte alles auf post umgeschrieben werden. vom search formular.
   
         qs=string.join(delEmpty(qs.split(",")),",")          qs=string.join(delEmpty(qs.split(",")),",")
   
Line 614  class ZSQLExtendFolder(Folder,Persistent Line 788  class ZSQLExtendFolder(Folder,Persistent
         """analysieren den QueryString"""          """analysieren den QueryString"""
                   
                   
           #setzte generische werte
           
         lop="AND" # standardsuche mit and          lop="AND" # standardsuche mit and
         max="ALL" #standard alle auswaehlen          max="ALL" #standard alle auswaehlen
         maxstr=""          maxstr=""
Line 629  class ZSQLExtendFolder(Folder,Persistent Line 805  class ZSQLExtendFolder(Folder,Persistent
         limit=0          limit=0
         searchFields={}          searchFields={}
         searchFieldsOnly={}          searchFieldsOnly={}
           queryTemplate=[]
           
         if not select:          if not select:
             select="oid,*"              select="oid,*"
         #print "Q",nostore,qs  
         #check for op   
   
   
   
                   
           #check for op 
     splitted=qs.split(",")      splitted=qs.split(",")
   
         if tableExt:          if tableExt:
             table=tableExt              table=tableExt
   
         if restrictField:          if restrictField:
                     select=restrictField                      select=restrictField
                           
           
           #erster durchgang suche operatoren    
         for q in splitted:          for q in splitted:
                                   
                 name=re.sub("r'+'"," ",q.split("=")[0].lower())                  name=re.sub("r'+'"," ",q.split("=")[0].lower())
Line 675  class ZSQLExtendFolder(Folder,Persistent Line 852  class ZSQLExtendFolder(Folder,Persistent
                     else:                      else:
                         sortfields[field]=value                          sortfields[field]=value
                                           
                     #print "HI",op,field          #zweiter durchgang analysiere felder
     #print opfieldsa  
         #now analyse the querystring  
          
         for q in qs.split(","):          for q in qs.split(","):
                 
                           
             #try:  
   
             name=re.sub("r'+'"," ",q.split("=")[0].lower())              name=re.sub("r'+'"," ",q.split("=")[0].lower())
             try:              try:
Line 690  class ZSQLExtendFolder(Folder,Persistent Line 863  class ZSQLExtendFolder(Folder,Persistent
             except:              except:
                 value=""                  value=""
                           
             #value=sql_quote(value)              punktsplit=name.split(".")   #sonderfall feld mit punkten(tabelle.suchFeld.ausgewaehltesFeld,feldinoriginal), d.h. suche in anderer tabelle:                      
               
   
               #analysiere alle anderen faelle
             if name==iCT+"lop":              if name==iCT+"lop":
                 lop=value                  lop=value
             elif name==iCT+"table":              elif name==iCT+"table":
Line 734  class ZSQLExtendFolder(Folder,Persistent Line 907  class ZSQLExtendFolder(Folder,Persistent
   
   
   
               elif (not name[0]==iCT) and len(punktsplit)==4:
                   if opfields.has_key(name):
                       op=opfields[name]
                   else:
                       op="ct"
                   namealt=name
                   name="LOWER("+punktsplit[1]+")" 
   
                   if op=="ct":
                       tmp=(name+" LIKE "+sql_quote("%"+value+"%"))
                   elif op=="gt":
                       tmp=(name+">"+sql_quote(value))
                   elif op=="lt":
                       tmp=(name+"<"+sql_quote(value))
                   elif op=="eq":
                       tmp=(name+"="+sql_quote(value))
                   elif op=="bw":
                       tmp=(name+" LIKE "+sql_quote(value+"%"))
                   elif op=="ew":
                       tmp=(name+" LIKE "+sql_quote("%"+value))
                   elif op=="all":
                       tmps=[]
                       for word in value.split(" "):
                           tmps.append(name+" LIKE "+sql_quote("%"+word+"%"))
                           
                       tmp=string.join(tmps,' AND ')
   
                   elif op=="numerical":
                       term=analyseIntSearch(value)
                       tmp=(name+" "+term)
                   elif op=="grep":
                       tmp=(name+" ~* "+sql_quote(value))
                   elif op=="one":
                       tmps=[]
                       for word in value.split(" "):
                           tmps.append(name+" LIKE "+sql_quote("%"+word+"%"))
                           
                       tmp=string.join(tmps,' OR ')
   
                   op="all"
   
   
                   searchTmp="""%s in (select %s from %s where %s)"""%(punktsplit[3],punktsplit[2],punktsplit[0],tmp)
   
                   queryTemplate.append(searchTmp)
                   
             elif (not name[0]==iCT) and (not len(value)==0):              elif (not name[0]==iCT) and (not len(value)==0):
   
         #print "OP",op,name          #print "OP",op,name
Line 788  class ZSQLExtendFolder(Folder,Persistent Line 1007  class ZSQLExtendFolder(Folder,Persistent
   
   
         whereList=["("+searchFields[x]+")" for x in searchFields.keys()]          whereList=["("+searchFields[x]+")" for x in searchFields.keys()]
           whereList+=queryTemplate
                   
         if len(whereList)>0:          if len(whereList)>0:
             if filter:              if filter:
Line 831  class ZSQLExtendFolder(Folder,Persistent Line 1051  class ZSQLExtendFolder(Folder,Persistent
                 if not self.REQUEST.SESSION[storename]['queryString2']==query2:                  if not self.REQUEST.SESSION[storename]['queryString2']==query2:
                     #print "HOOOOO",storename                      #print "HOOOOO",storename
                     self.REQUEST.SESSION[storename]['queryString2']=query2                      self.REQUEST.SESSION[storename]['queryString2']=query2
                       try:
                     self.REQUEST.SESSION[storename]['count']=self.ZSQLSimpleSearch(query2)[0].count                      self.REQUEST.SESSION[storename]['count']=self.ZSQLSimpleSearch(query2)[0].count
                       except:
                           self.REQUEST.SESSION[storename]['count']=0
                     #print "QUERY",query2,"::::",self.REQUEST.SESSION[storename]['queryString2']                      #print "QUERY",query2,"::::",self.REQUEST.SESSION[storename]['queryString2']
                                   
             else:              else:
   
                 self.REQUEST.SESSION[storename]['queryString2']=query2                  self.REQUEST.SESSION[storename]['queryString2']=query2
                   if self.ZSQLSimpleSearch(query2):
                 self.REQUEST.SESSION[storename]['count']=self.ZSQLSimpleSearch(query2)[0].count                  self.REQUEST.SESSION[storename]['count']=self.ZSQLSimpleSearch(query2)[0].count
                   else:
                       self.REQUEST.SESSION[storename]['count']=0
                 #print "QUERYNEW",self.REQUEST.SESSION[storename]['queryString2']                  #print "QUERYNEW",self.REQUEST.SESSION[storename]['queryString2']
                           
                           
Line 870  class ZSQLExtendFolder(Folder,Persistent Line 1095  class ZSQLExtendFolder(Folder,Persistent
         else:          else:
             return value              return value
                   
     def ZSQLQuery(self,query):      def ZSQLQuery(self,query,debug=None):
         """query"""          """query"""
           if debug:
               zLOG.LOG("ZSQLQuery", zLOG.INFO, query)
   
         return self.ZSQLSimpleSearch(query)          return self.ZSQLSimpleSearch(query)
   
           
     def ZSQLSearch(self):      def ZSQLSearch(self):
         """To be done"""          """To be done"""
         rq=self.REQUEST['QUERY_STRING']  
   
         querys=rq.split("&")  
           
                   
         formatfile=self.REQUEST['URL1'] #generisch redirect zur gleichen url          formatfile=self.REQUEST['URL1'] #generisch redirect zur gleichen url
                   
         for querytemp in querys:          #zerlege querystring in key value paare
             query=querytemp.split("=")          #TODO: check if this is really necessary, use argv**
               
               
   
           rq=self.REQUEST['QUERY_STRING']
           querys=rq.split("&")
           for querytemp in querys: #zerg
               query=querytemp.split("=")
                           
             try:              try:
                 if query[0].lower()=="-format":                  if query[0].lower()=="-format":
                     formatfile=query[1]                      formatfile=query[1]
             except:              except:
                 """nothing"""                  pass
   
                   
         #print formatfile  
           
                   
           #sichern
         self.REQUEST.SESSION['query']=string.join(self.REQUEST['QUERY_STRING'].split("&"),",")          self.REQUEST.SESSION['query']=string.join(self.REQUEST['QUERY_STRING'].split("&"),",")
         self.REQUEST.SESSION['come_from_search']="yes"          self.REQUEST.SESSION['come_from_search']="yes"
                   
Line 1173  class ZSQLBibliography(Folder,ZSQLExtend Line 1395  class ZSQLBibliography(Folder,ZSQLExtend
             pt.content_type="text/html"              pt.content_type="text/html"
             return pt()              return pt()
   
     def changeZSQLBibliography(self,tableName,label,description,REQUEST=None):      def changeZSQLBibliography(self,tableName,label,description,connection_id=None,REQUEST=None):
         """change it"""          """change it"""
           self.connection_id=connection_id
         self.tableName=tableName          self.tableName=tableName
         self.label=label          self.label=label
         self.description=description          self.description=description
Line 1184  class ZSQLBibliography(Folder,ZSQLExtend Line 1407  class ZSQLBibliography(Folder,ZSQLExtend
   
     manage_options=Folder.manage_options+(      manage_options=Folder.manage_options+(
         {'label':'Main Config','action':'changeZSQLBibliographyForm'},          {'label':'Main Config','action':'changeZSQLBibliographyForm'},
           {'label':'Generate RDF Template','action':'generateRDFTemplate'},
           {'label':'Generate XML Template','action':'generateXMLTemplate'},
        )         )
   
   
Line 1248  class ZSQLBibliography(Folder,ZSQLExtend Line 1473  class ZSQLBibliography(Folder,ZSQLExtend
   
         return retdata,fieldlist          return retdata,fieldlist
   
     def createRDFTag(self,tag,content):      def createRDFTag(self,tag,content,namespace="cdli"):
         """create RDF"""          """create RDF"""
         if content:          if content:
             ret=""" <cdli:%s>%s</cdli:%s>"""%(tag,content,tag)              tag=namespace+":"+tag
               if (type(content) is StringType) or (type(content) is UnicodeType):
                   ret=""" <%s>%s</%s>"""%(tag,escape(content),tag)
               else:
                   ret=""" <%s>%s</%s>"""%(tag,content,tag)
             return ret.decode('latin-1')              return ret.decode('latin-1')
         else:          else:
             return ""              return ""
           
     def createIndexTag(self,tag,content):      def createIndexTag(self,tag,content):
         """create tag"""          """create tag"""
           
         if content:          if content:
               if (type(content) is StringType) or (type(content) is UnicodeType):
                   ret=""" <%s>%s</%s>"""%(tag,escape(content),tag)
               else:
             ret="""<%s>%s</%s>"""%(tag,content,tag)              ret="""<%s>%s</%s>"""%(tag,content,tag)
             return ret              return ret.decode('latin-1')
   
         else:          else:
             return ""              return ""
           
     def getMetaDataXML2(self):      def getXML2(self):
         """crate index meta"""          """crate index meta"""
   
         fn=os.path.splitext(self.REQUEST['fn'])[0]+"."          fn=os.path.splitext(self.REQUEST['fn'])[0]+"."
Line 1274  class ZSQLBibliography(Folder,ZSQLExtend Line 1508  class ZSQLBibliography(Folder,ZSQLExtend
         pt.content_type="text/xml"          pt.content_type="text/xml"
         return pt()          return pt()
   
   
       def generateRDFTemplate(self,REQUEST=None):
           """generateRDFtemplate"""
           zt=ZopePageTemplate('record.rdf')
           self._setObject('record.rdf',zt)
           default_content_fn = os.path.join(package_home(globals()),
                                             'zpt','record.rdf')
           text = open(default_content_fn).read()
           zt.pt_edit(text, 'text/xml')
   
   
           if REQUEST is not None:
               return self.manage_main(self, REQUEST)
   
       def generateXMLTemplate(self,REQUEST=None):
           """generateXMLtemplate"""
           zt=ZopePageTemplate('record.xml')
           self._setObject('record.xml',zt)
           default_content_fn = os.path.join(package_home(globals()),
                                             'zpt','record.xml')
           text = open(default_content_fn).read()
           zt.pt_edit(text, 'text/xml')
   
   
           if REQUEST is not None:
               return self.manage_main(self, REQUEST)
     def getMetaDataRDF(self):      def getMetaDataRDF(self):
         """crate index meta"""          """crate index meta"""
           find=self.ZopeFind(self,obj_ids=["record.rdf"])
           if not find:
         pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','record.rdf')).__of__(self)          pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','record.rdf')).__of__(self)
         pt.content_type="text/xml"          pt.content_type="text/xml"
         return pt()          return pt()
           else:
               return find[0][1]()
   
     def getMetaDataXML(self):      def getMetaDataXML(self):
         """crate index meta"""          """crate index meta"""
Line 1290  class ZSQLBibliography(Folder,ZSQLExtend Line 1554  class ZSQLBibliography(Folder,ZSQLExtend
         else:          else:
             return find[0][1]()              return find[0][1]()
   
     def createVLMAtripels(self):  
         """index"""  
         # check if the request's host part was OK  
         http_host = self.REQUEST['HTTP_HOST']  
         host_port = self.REQUEST['SERVER_PORT']  
         fix_host = None  
         if http_host and http_host.rfind(host_port) == -1:  
             print "HTTP_HOST needs fixing!"  
             fix_host = http_host + ":" + host_port  
           
         ret=""  
         for found in self.ZSQLSimpleSearch("select id_text from %s limit ALL"%'cdli_cat'):  
             base_url = self.absolute_url()  
             if fix_host:  
                 #print "replacing ", http_host, " by ", fix_host  
                 base_url = string.replace(base_url, http_host, fix_host, 1)  
   
             #found2=self.ZSQLInlineSearchU(_table="cdli_imglist",id_text=found.id_text)  
             #create collectionobject info  
             subject="http://xserve02.mpiwg-berlin.mpg.de:8880/cdlineu/cdli_coll/cdli2/cdli_templates/cdli_templates/textdisplay.html?-table=cdli_cat&id_text=%s"%found.id_text  
             object="http://xserve02:8880/cdlidata/images/getMetaDataRDF?id_text=%s"%found.id_text  
             predicate="metadata"  
             ret+="%s\t%s\t%s\n"%(subject,object,predicate)  
             #create image  
             subject="http://xserve02.mpiwg-berlin.mpg.de:8880/cdlineu/cdli_coll/cdli2/cdli_templates/cdli_templates/textdisplay.html?-table=cdli_cat&id_text=%s"%found.id_text  
             object="http://nausikaa2.mpiwg-berlin.mpg.de/digitallibrary/servlet/Scaler?fn=/experimental/cdli/dl/photo/%s&mo=rawfile"%found.id_text  
             predicate="image"  
               
             ret+="%s\t%s\t%s\n"%(subject,object,predicate)  
   
             #create thumb  
             subject="http://nausikaa2.mpiwg-berlin.mpg.de/digitallibrary/servlet/Scaler?fn=/experimental/cdli/dl/photo/%s&mo=rawfile"%found.id_text  
             object="http://nausikaa2.mpiwg-berlin.mpg.de/digitallibrary/servlet/Scaler?fn=/experimental/cdli/dl/photo/%s&dw=100&dh=100"%found.id_text  
             predicate="thumb"  
               
             ret+="%s\t%s\t%s\n"%(subject,object,predicate)  
       
         return ret  
   
   
     def getMetaDatasXML(self):      def getMetaDatasXML(self):
         """index"""          """index"""
Line 1361  manage_addZSQLBibliographyForm=DTMLFile( Line 1586  manage_addZSQLBibliographyForm=DTMLFile(
 def manage_addZSQLBibliography(self, id, tableName,label,description,title='',  def manage_addZSQLBibliography(self, id, tableName,label,description,title='',
                      createPublic=0,                       createPublic=0,
                      createUserF=0,                       createUserF=0,
                        connection_id=None,
                      REQUEST=None):                       REQUEST=None):
     """Add a new Folder object with id *id*.      """Add a new Folder object with id *id*.
   
Line 1378  def manage_addZSQLBibliography(self, id, Line 1604  def manage_addZSQLBibliography(self, id,
     setattr(ob,'tableName',tableName)      setattr(ob,'tableName',tableName)
     setattr(ob,'label',label)      setattr(ob,'label',label)
     setattr(ob,'description',description)      setattr(ob,'description',description)
       setattr(ob,'connection_id',connection_id)
           
     checkPermission=getSecurityManager().checkPermission      checkPermission=getSecurityManager().checkPermission
   

Removed from v.1.56  
changed lines
  Added in v.1.72


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