/
queryparser.py
264 lines (208 loc) · 7.05 KB
/
queryparser.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
from collections import namedtuple
import logging
from Acquisition import aq_parent
from DateTime import DateTime
from plone.app.layout.navigation.interfaces import INavigationRoot
from plone.registry.interfaces import IRegistry
from Products.CMFCore.utils import getToolByName
from Products.CMFPlone.browser.navtree import getNavigationRoot
from Products.CMFPlone.utils import base_hasattr
from zope.component import getUtility
from zope.dottedname.resolve import resolve
logger = logging.getLogger('plone.app.querystring')
Row = namedtuple('Row', ['index', 'operator', 'values'])
def parseFormquery(context, formquery, sort_on=None, sort_order=None):
if not formquery:
return {}
reg = getUtility(IRegistry)
# Make sure the things in formquery are dictionaries
formquery = map(dict, formquery)
query = {}
for row in formquery:
operator = row.get('o', None)
function_path = reg["%s.operation" % operator]
# The functions expect this pattern of object, so lets give it to
# them in a named tuple instead of jamming things onto the request
row = Row(index=row.get('i', None),
operator=function_path,
values=row.get('v', None))
kwargs = {}
parser = resolve(row.operator)
kwargs = parser(context, row)
# Special path handling - since multipath queries are possible
if 'path' in query and 'path' in kwargs:
query['path']['query'].extend(kwargs['path']['query'])
else:
query.update(kwargs)
if not query:
# If the query is empty fall back onto the equality query
query = _equal(context, row)
# Check for valid indexes
catalog = getToolByName(context, 'portal_catalog')
valid_indexes = [index for index in query if index in catalog.indexes()]
# We'll ignore any invalid index, but will return an empty set if none of
# the indexes are valid.
if not valid_indexes:
logger.warning(
"Using empty query because there are no valid indexes used.")
return {}
# Add sorting (sort_on and sort_order) to the query
if sort_on:
query['sort_on'] = sort_on
if sort_order:
query['sort_order'] = sort_order
return query
# Query operators
def _contains(context, row):
return _equal(context, row)
def _equal(context, row):
return {row.index: {'query': row.values, }}
def _isTrue(context, row):
return {row.index: {'query': True, }}
def _isFalse(context, row):
return {row.index: {'query': False, }}
def _between(context, row):
tmp = {row.index: {
'query': sorted(row.values),
'range': 'minmax',
},
}
return tmp
def _largerThan(context, row):
tmp = {row.index: {
'query': row.values,
'range': 'min',
},
}
return tmp
def _lessThan(context, row):
tmp = {row.index: {
'query': row.values,
'range': 'max',
},
}
return tmp
def _currentUser(context, row):
"""Current user lookup"""
mt = getToolByName(context, 'portal_membership')
user = mt.getAuthenticatedMember()
return {row.index: {
'query': user.getUserName(),
},
}
def _lessThanRelativeDate(context, row):
""" "Between now and N days from now." """
# INFO: Values is the number of days
try:
values = int(row.values)
except ValueError:
values = 0
now = DateTime()
start_date = now.earliestTime()
end_date = now + values
end_date = end_date.latestTime()
row = Row(index=row.index,
operator=row.operator,
values=(start_date, end_date))
return _between(context, row)
def _moreThanRelativeDate(context, row):
""" "Between now and N days ago." """
# INFO: Values is the number of days
try:
values = int(row.values)
except ValueError:
values = 0
now = DateTime()
start_date = now - values
start_date = start_date.earliestTime()
end_date = now.latestTime()
row = Row(index=row.index,
operator=row.operator,
values=(start_date, end_date))
return _between(context, row)
def _betweenDates(context, row):
try:
start_date = DateTime(row.values[0])
except DateTime.DateTimeError:
start_date = DateTime(0)
try:
end_date = DateTime(row.values[1])
except DateTime.DateTimeError:
row = Row(index=row.index,
operator=row.operator,
values=start_date)
return _largerThan(context, row)
else:
row = Row(index=row.index,
operator=row.operator,
values=(start_date, end_date))
return _between(context, row)
def _today(context, row):
now = DateTime()
start_date = now.earliestTime()
end_date = now.latestTime()
row = Row(index=row.index,
operator=row.operator,
values=(start_date, end_date))
return _between(context, row)
def _afterToday(context, row):
row = Row(index=row.index,
operator=row.operator,
values=DateTime())
return _largerThan(context, row)
def _beforeToday(context, row):
row = Row(index=row.index,
operator=row.operator,
values=DateTime())
return _lessThan(context, row)
def _path(context, row):
values = row.values
depth = None
if '::' in values:
values, _depth = values.split('::', 1)
try:
depth = int(_depth)
except ValueError:
pass
if not '/' in values:
# It must be a UID
values = '/'.join(getPathByUID(context, values))
# take care of absolute paths without nav_root
nav_root = getNavigationRoot(context)
if not values.startswith(nav_root):
values = nav_root + values
query = {}
if depth is not None:
query['depth'] = depth
# when a depth value is specified, a trailing slash matters on the
# query
values = values.rstrip('/')
query['query'] = [values]
return {row.index: query}
def _relativePath(context, row):
# Walk through the tree
obj = context
for x in [r for r in row.values.split('/') if r]:
if x == "..":
if INavigationRoot.providedBy(obj):
break
parent = aq_parent(obj)
if parent:
obj = parent
else:
if base_hasattr(obj, x):
child = getattr(obj, x, None)
if child and base_hasattr(child, "getPhysicalPath"):
obj = child
row = Row(index=row.index,
operator=row.operator,
values='/'.join(obj.getPhysicalPath()))
return _path(context, row)
# Helper functions
def getPathByUID(context, uid):
"""Returns the path of an object specified by UID"""
catalog = getToolByName(context, 'portal_catalog')
brains = catalog.unrestrictedSearchResults(dict(UID=uid))
if brains:
return brains[0].getPath()
return ''