Back to index

plone3  3.1.7
referencebrowser_queryCatalog.py
Go to the documentation of this file.
00001 ## Script (Python) "referencebrowser_queryCatalog"
00002 ##bind container=container
00003 ##bind context=context
00004 ##bind namespace=
00005 ##bind script=script
00006 ##bind subpath=traverse_subpath
00007 ##parameters=REQUEST=None,show_all=0,quote_logic=0,quote_logic_indexes=['SearchableText'],search_catalog=None
00008 ##title=wraps the portal_catalog with a rules qualified query
00009 ##
00010 from ZODB.POSException import ConflictError
00011 from Products.ZCTextIndex.ParseTree import ParseError
00012 
00013 results=[]
00014 if not search_catalog: search_catalog = 'portal_catalog'
00015 catalog=getattr(context, search_catalog, context.portal_catalog)
00016 if not hasattr(catalog, 'searchResults'):
00017     catalog= context.portal_catalog
00018 
00019 indexes=catalog.indexes()
00020 query={}
00021 show_query=show_all
00022 second_pass = {}
00023 
00024 if REQUEST is None:
00025     REQUEST = context.REQUEST
00026 
00027 def quotestring(s):
00028     return '"%s"' % s
00029 
00030 def quotequery(s):
00031     if not s:
00032         return s
00033     try:
00034         terms = s.split()
00035     except ConflictError:
00036         raise
00037     except:
00038         return s
00039     tokens = ('OR', 'AND', 'NOT')
00040     s_tokens = ('OR', 'AND')
00041     check = (0, -1)
00042     for idx in check:
00043         if terms[idx].upper() in tokens:
00044             terms[idx] = quotestring(terms[idx])
00045     for idx in range(1, len(terms)):
00046         if (terms[idx].upper() in s_tokens and
00047             terms[idx-1].upper() in tokens):
00048             terms[idx] = quotestring(terms[idx])
00049     return ' '.join(terms)
00050 
00051 for k, v in REQUEST.items():
00052     if v and k in indexes:
00053         if quote_logic and k in quote_logic_indexes:
00054             v = quotequery(v)
00055         query.update({k:v})
00056         show_query=1
00057     elif k.endswith('_usage'):
00058         key = k[:-6]
00059         param, value = v.split(':')
00060         second_pass[key] = {param:value}
00061     elif k in ('sort_on', 'sort_order', 'sort_limit'):
00062         query.update({k:v})
00063 
00064 for k, v in second_pass.items():
00065     qs = query.get(k)
00066     if qs is None:
00067         continue
00068     query[k] = q = {'query':qs}
00069     q.update(v)
00070 
00071 # doesn't normal call catalog unless some field has been queried
00072 # against. if you want to call the catalog _regardless_ of whether
00073 # any items were found, then you can pass show_all=1.
00074 
00075 if show_query:
00076     try:
00077         results=catalog(query)
00078     except ParseError:
00079         pass
00080 
00081 return results