author | Sylvain Thénault <sylvain.thenault@logilab.fr> |
Fri, 03 Jul 2009 17:57:19 +0200 | |
branch | stable |
changeset 2255 | c346af0727ca |
parent 2245 | 7463e1a748dd |
child 2258 | 79bc598c6411 |
permissions | -rw-r--r-- |
0 | 1 |
"""abstract class for http request |
2 |
||
3 |
:organization: Logilab |
|
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1801
diff
changeset
|
4 |
:copyright: 2001-2009 LOGILAB S.A. (Paris, FRANCE), license is LGPL v2. |
0 | 5 |
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr |
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1801
diff
changeset
|
6 |
:license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses |
0 | 7 |
""" |
8 |
__docformat__ = "restructuredtext en" |
|
9 |
||
10 |
import Cookie |
|
11 |
import sha |
|
12 |
import time |
|
13 |
import random |
|
14 |
import base64 |
|
15 |
from urlparse import urlsplit |
|
16 |
from itertools import count |
|
17 |
||
18 |
from rql.utils import rqlvar_maker |
|
19 |
||
20 |
from logilab.common.decorators import cached |
|
1717
d2c4d3bd0602
correct wrong condition and missing import
Graziella Toutoungis <graziella.toutoungis@logilab.fr>
parents:
1716
diff
changeset
|
21 |
from logilab.common.deprecation import obsolete |
0 | 22 |
|
1801
672acc730ce5
ajax_replace_url becomes obsolete, req.build_ajax_replace_url should be used instead
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1718
diff
changeset
|
23 |
from logilab.mtconverter import html_escape |
672acc730ce5
ajax_replace_url becomes obsolete, req.build_ajax_replace_url should be used instead
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1718
diff
changeset
|
24 |
|
0 | 25 |
from cubicweb.dbapi import DBAPIRequest |
26 |
from cubicweb.common.mail import header |
|
27 |
from cubicweb.common.uilib import remove_html_tags |
|
940
15dcdc863965
fix imports : common.utils -> utils
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
890
diff
changeset
|
28 |
from cubicweb.utils import SizeConstrainedList, HTMLHead |
1801
672acc730ce5
ajax_replace_url becomes obsolete, req.build_ajax_replace_url should be used instead
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1718
diff
changeset
|
29 |
from cubicweb.web import (INTERNAL_FIELD_VALUE, LOGGER, NothingToEdit, |
672acc730ce5
ajax_replace_url becomes obsolete, req.build_ajax_replace_url should be used instead
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1718
diff
changeset
|
30 |
RequestError, StatusResponse) |
0 | 31 |
|
662
6f867ab70e3d
move _MARKER from appobject to web.request
sylvain.thenault@logilab.fr
parents:
610
diff
changeset
|
32 |
_MARKER = object() |
6f867ab70e3d
move _MARKER from appobject to web.request
sylvain.thenault@logilab.fr
parents:
610
diff
changeset
|
33 |
|
0 | 34 |
|
35 |
def list_form_param(form, param, pop=False): |
|
36 |
"""get param from form parameters and return its value as a list, |
|
37 |
skipping internal markers if any |
|
38 |
||
39 |
* if the parameter isn't defined, return an empty list |
|
40 |
* if the parameter is a single (unicode) value, return a list |
|
41 |
containing that value |
|
42 |
* if the parameter is already a list or tuple, just skip internal |
|
43 |
markers |
|
44 |
||
45 |
if pop is True, the parameter is removed from the form dictionnary |
|
46 |
""" |
|
47 |
if pop: |
|
48 |
try: |
|
49 |
value = form.pop(param) |
|
50 |
except KeyError: |
|
51 |
return [] |
|
52 |
else: |
|
53 |
value = form.get(param, ()) |
|
54 |
if value is None: |
|
55 |
value = () |
|
56 |
elif not isinstance(value, (list, tuple)): |
|
57 |
value = [value] |
|
58 |
return [v for v in value if v != INTERNAL_FIELD_VALUE] |
|
59 |
||
60 |
||
61 |
||
62 |
class CubicWebRequestBase(DBAPIRequest): |
|
1421
77ee26df178f
doc type handling refactoring: do the ext substitution at the module level
sylvain.thenault@logilab.fr
parents:
1173
diff
changeset
|
63 |
"""abstract HTTP request, should be extended according to the HTTP backend""" |
2255
c346af0727ca
more generic way to detect json requests (not yet perfect though)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2245
diff
changeset
|
64 |
json_request = False # to be set to True by json controllers |
1421
77ee26df178f
doc type handling refactoring: do the ext substitution at the module level
sylvain.thenault@logilab.fr
parents:
1173
diff
changeset
|
65 |
|
0 | 66 |
def __init__(self, vreg, https, form=None): |
67 |
super(CubicWebRequestBase, self).__init__(vreg) |
|
68 |
self.message = None |
|
69 |
self.authmode = vreg.config['auth-mode'] |
|
70 |
self.https = https |
|
71 |
# raw html headers that can be added from any view |
|
72 |
self.html_headers = HTMLHead() |
|
73 |
# form parameters |
|
74 |
self.setup_params(form) |
|
75 |
# dictionnary that may be used to store request data that has to be |
|
76 |
# shared among various components used to publish the request (views, |
|
77 |
# controller, application...) |
|
78 |
self.data = {} |
|
79 |
# search state: 'normal' or 'linksearch' (eg searching for an object |
|
80 |
# to create a relation with another) |
|
1426 | 81 |
self.search_state = ('normal',) |
0 | 82 |
# tabindex generator |
83 |
self.tabindexgen = count() |
|
84 |
self.next_tabindex = self.tabindexgen.next |
|
85 |
# page id, set by htmlheader template |
|
86 |
self.pageid = None |
|
87 |
self.varmaker = rqlvar_maker() |
|
88 |
self.datadir_url = self._datadir_url() |
|
89 |
||
90 |
def set_connection(self, cnx, user=None): |
|
91 |
"""method called by the session handler when the user is authenticated |
|
92 |
or an anonymous connection is open |
|
93 |
""" |
|
94 |
super(CubicWebRequestBase, self).set_connection(cnx, user) |
|
2245
7463e1a748dd
new set_session_props method exposed by the repository, use it to be sure session language is in sync the request language
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2202
diff
changeset
|
95 |
# set request language |
0 | 96 |
vreg = self.vreg |
97 |
if self.user: |
|
98 |
try: |
|
99 |
# 1. user specified language |
|
100 |
lang = vreg.typed_value('ui.language', |
|
101 |
self.user.properties['ui.language']) |
|
102 |
self.set_language(lang) |
|
103 |
return |
|
104 |
except KeyError, ex: |
|
105 |
pass |
|
106 |
if vreg.config['language-negociation']: |
|
107 |
# 2. http negociated language |
|
108 |
for lang in self.header_accept_language(): |
|
109 |
if lang in self.translations: |
|
110 |
self.set_language(lang) |
|
111 |
return |
|
112 |
# 3. default language |
|
113 |
self.set_default_language(vreg) |
|
1426 | 114 |
|
0 | 115 |
def set_language(self, lang): |
116 |
self._ = self.__ = self.translations[lang] |
|
117 |
self.lang = lang |
|
2245
7463e1a748dd
new set_session_props method exposed by the repository, use it to be sure session language is in sync the request language
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2202
diff
changeset
|
118 |
self.cnx.set_session_props(lang=lang) |
0 | 119 |
self.debug('request language: %s', lang) |
1426 | 120 |
|
0 | 121 |
# input form parameters management ######################################## |
1426 | 122 |
|
0 | 123 |
# common form parameters which should be protected against html values |
124 |
# XXX can't add 'eid' for instance since it may be multivalued |
|
125 |
# dont put rql as well, if query contains < and > it will be corrupted! |
|
1426 | 126 |
no_script_form_params = set(('vid', |
127 |
'etype', |
|
0 | 128 |
'vtitle', 'title', |
129 |
'__message', |
|
130 |
'__redirectvid', '__redirectrql')) |
|
1426 | 131 |
|
0 | 132 |
def setup_params(self, params): |
133 |
"""WARNING: we're intentionaly leaving INTERNAL_FIELD_VALUE here |
|
134 |
||
1426 | 135 |
subclasses should overrides to |
0 | 136 |
""" |
137 |
if params is None: |
|
138 |
params = {} |
|
139 |
self.form = params |
|
140 |
encoding = self.encoding |
|
141 |
for k, v in params.items(): |
|
142 |
if isinstance(v, (tuple, list)): |
|
143 |
v = [unicode(x, encoding) for x in v] |
|
144 |
if len(v) == 1: |
|
145 |
v = v[0] |
|
146 |
if k in self.no_script_form_params: |
|
147 |
v = self.no_script_form_param(k, value=v) |
|
148 |
if isinstance(v, str): |
|
149 |
v = unicode(v, encoding) |
|
150 |
if k == '__message': |
|
151 |
self.set_message(v) |
|
152 |
del self.form[k] |
|
153 |
else: |
|
154 |
self.form[k] = v |
|
2202
cb374512949f
link to created entity when redirected to another page
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
155 |
# special key for created entity, added in controller's reset method |
cb374512949f
link to created entity when redirected to another page
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
156 |
if '__createdpath' in params: |
cb374512949f
link to created entity when redirected to another page
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
157 |
self.message += ' (<a href="%s">%s</a>)' % ( |
cb374512949f
link to created entity when redirected to another page
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
158 |
self.build_url(params.pop('__createdpath')), |
cb374512949f
link to created entity when redirected to another page
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
159 |
self._('click here to see created entity')) |
1426 | 160 |
|
0 | 161 |
def no_script_form_param(self, param, default=None, value=None): |
162 |
"""ensure there is no script in a user form param |
|
163 |
||
164 |
by default return a cleaned string instead of raising a security |
|
165 |
exception |
|
166 |
||
167 |
this method should be called on every user input (form at least) fields |
|
168 |
that are at some point inserted in a generated html page to protect |
|
169 |
against script kiddies |
|
170 |
""" |
|
171 |
if value is None: |
|
172 |
value = self.form.get(param, default) |
|
173 |
if not value is default and value: |
|
174 |
# safety belt for strange urls like http://...?vtitle=yo&vtitle=yo |
|
175 |
if isinstance(value, (list, tuple)): |
|
176 |
self.error('no_script_form_param got a list (%s). Who generated the URL ?', |
|
177 |
repr(value)) |
|
178 |
value = value[0] |
|
179 |
return remove_html_tags(value) |
|
180 |
return value |
|
1426 | 181 |
|
0 | 182 |
def list_form_param(self, param, form=None, pop=False): |
183 |
"""get param from form parameters and return its value as a list, |
|
184 |
skipping internal markers if any |
|
1426 | 185 |
|
0 | 186 |
* if the parameter isn't defined, return an empty list |
187 |
* if the parameter is a single (unicode) value, return a list |
|
188 |
containing that value |
|
189 |
* if the parameter is already a list or tuple, just skip internal |
|
190 |
markers |
|
191 |
||
192 |
if pop is True, the parameter is removed from the form dictionnary |
|
193 |
""" |
|
194 |
if form is None: |
|
195 |
form = self.form |
|
1426 | 196 |
return list_form_param(form, param, pop) |
197 |
||
0 | 198 |
|
199 |
def reset_headers(self): |
|
200 |
"""used by AutomaticWebTest to clear html headers between tests on |
|
201 |
the same resultset |
|
202 |
""" |
|
203 |
self.html_headers = HTMLHead() |
|
204 |
return self |
|
205 |
||
206 |
# web state helpers ####################################################### |
|
1426 | 207 |
|
0 | 208 |
def set_message(self, msg): |
209 |
assert isinstance(msg, unicode) |
|
210 |
self.message = msg |
|
1426 | 211 |
|
0 | 212 |
def update_search_state(self): |
213 |
"""update the current search state""" |
|
214 |
searchstate = self.form.get('__mode') |
|
610
30cb5e29a416
take care, cnx may be None in which case we can't get/set session data
sylvain.thenault@logilab.fr
parents:
495
diff
changeset
|
215 |
if not searchstate and self.cnx is not None: |
0 | 216 |
searchstate = self.get_session_data('search_state', 'normal') |
217 |
self.set_search_state(searchstate) |
|
218 |
||
219 |
def set_search_state(self, searchstate): |
|
220 |
"""set a new search state""" |
|
221 |
if searchstate is None or searchstate == 'normal': |
|
222 |
self.search_state = (searchstate or 'normal',) |
|
223 |
else: |
|
224 |
self.search_state = ('linksearch', searchstate.split(':')) |
|
225 |
assert len(self.search_state[-1]) == 4 |
|
610
30cb5e29a416
take care, cnx may be None in which case we can't get/set session data
sylvain.thenault@logilab.fr
parents:
495
diff
changeset
|
226 |
if self.cnx is not None: |
30cb5e29a416
take care, cnx may be None in which case we can't get/set session data
sylvain.thenault@logilab.fr
parents:
495
diff
changeset
|
227 |
self.set_session_data('search_state', searchstate) |
0 | 228 |
|
1173
8f123fd081f4
forgot to add that expected method (was a function in view.__init__)
sylvain.thenault@logilab.fr
parents:
1013
diff
changeset
|
229 |
def match_search_state(self, rset): |
8f123fd081f4
forgot to add that expected method (was a function in view.__init__)
sylvain.thenault@logilab.fr
parents:
1013
diff
changeset
|
230 |
"""when searching an entity to create a relation, return True if entities in |
8f123fd081f4
forgot to add that expected method (was a function in view.__init__)
sylvain.thenault@logilab.fr
parents:
1013
diff
changeset
|
231 |
the given rset may be used as relation end |
8f123fd081f4
forgot to add that expected method (was a function in view.__init__)
sylvain.thenault@logilab.fr
parents:
1013
diff
changeset
|
232 |
""" |
8f123fd081f4
forgot to add that expected method (was a function in view.__init__)
sylvain.thenault@logilab.fr
parents:
1013
diff
changeset
|
233 |
try: |
8f123fd081f4
forgot to add that expected method (was a function in view.__init__)
sylvain.thenault@logilab.fr
parents:
1013
diff
changeset
|
234 |
searchedtype = self.search_state[1][-1] |
8f123fd081f4
forgot to add that expected method (was a function in view.__init__)
sylvain.thenault@logilab.fr
parents:
1013
diff
changeset
|
235 |
except IndexError: |
8f123fd081f4
forgot to add that expected method (was a function in view.__init__)
sylvain.thenault@logilab.fr
parents:
1013
diff
changeset
|
236 |
return False # no searching for association |
8f123fd081f4
forgot to add that expected method (was a function in view.__init__)
sylvain.thenault@logilab.fr
parents:
1013
diff
changeset
|
237 |
for etype in rset.column_types(0): |
8f123fd081f4
forgot to add that expected method (was a function in view.__init__)
sylvain.thenault@logilab.fr
parents:
1013
diff
changeset
|
238 |
if etype != searchedtype: |
8f123fd081f4
forgot to add that expected method (was a function in view.__init__)
sylvain.thenault@logilab.fr
parents:
1013
diff
changeset
|
239 |
return False |
8f123fd081f4
forgot to add that expected method (was a function in view.__init__)
sylvain.thenault@logilab.fr
parents:
1013
diff
changeset
|
240 |
return True |
8f123fd081f4
forgot to add that expected method (was a function in view.__init__)
sylvain.thenault@logilab.fr
parents:
1013
diff
changeset
|
241 |
|
0 | 242 |
def update_breadcrumbs(self): |
243 |
"""stores the last visisted page in session data""" |
|
244 |
searchstate = self.get_session_data('search_state') |
|
245 |
if searchstate == 'normal': |
|
246 |
breadcrumbs = self.get_session_data('breadcrumbs', None) |
|
247 |
if breadcrumbs is None: |
|
248 |
breadcrumbs = SizeConstrainedList(10) |
|
249 |
self.set_session_data('breadcrumbs', breadcrumbs) |
|
250 |
breadcrumbs.append(self.url()) |
|
251 |
||
252 |
def last_visited_page(self): |
|
253 |
breadcrumbs = self.get_session_data('breadcrumbs', None) |
|
254 |
if breadcrumbs: |
|
255 |
return breadcrumbs.pop() |
|
256 |
return self.base_url() |
|
257 |
||
258 |
def register_onetime_callback(self, func, *args): |
|
259 |
cbname = 'cb_%s' % ( |
|
260 |
sha.sha('%s%s%s%s' % (time.time(), func.__name__, |
|
1426 | 261 |
random.random(), |
0 | 262 |
self.user.login)).hexdigest()) |
263 |
def _cb(req): |
|
264 |
try: |
|
265 |
ret = func(req, *args) |
|
266 |
except TypeError: |
|
267 |
from warnings import warn |
|
268 |
warn('user callback should now take request as argument') |
|
1426 | 269 |
ret = func(*args) |
0 | 270 |
self.unregister_callback(self.pageid, cbname) |
271 |
return ret |
|
272 |
self.set_page_data(cbname, _cb) |
|
273 |
return cbname |
|
1426 | 274 |
|
0 | 275 |
def unregister_callback(self, pageid, cbname): |
276 |
assert pageid is not None |
|
277 |
assert cbname.startswith('cb_') |
|
278 |
self.info('unregistering callback %s for pageid %s', cbname, pageid) |
|
279 |
self.del_page_data(cbname) |
|
280 |
||
281 |
def clear_user_callbacks(self): |
|
282 |
if self.cnx is not None: |
|
283 |
sessdata = self.session_data() |
|
284 |
callbacks = [key for key in sessdata if key.startswith('cb_')] |
|
285 |
for callback in callbacks: |
|
286 |
self.del_session_data(callback) |
|
1426 | 287 |
|
0 | 288 |
# web edition helpers ##################################################### |
1426 | 289 |
|
0 | 290 |
@cached # so it's writed only once |
291 |
def fckeditor_config(self): |
|
890
3530baff9120
make fckeditor actually optional, fix its config, avoid needs for a link to fckeditor.js
sylvain.thenault@logilab.fr
parents:
662
diff
changeset
|
292 |
self.add_js('fckeditor/fckeditor.js') |
0 | 293 |
self.html_headers.define_var('fcklang', self.lang) |
294 |
self.html_headers.define_var('fckconfigpath', |
|
890
3530baff9120
make fckeditor actually optional, fix its config, avoid needs for a link to fckeditor.js
sylvain.thenault@logilab.fr
parents:
662
diff
changeset
|
295 |
self.build_url('data/cubicweb.fckcwconfig.js')) |
1013
948a3882c94a
add a use_fckeditor method on http request
sylvain.thenault@logilab.fr
parents:
940
diff
changeset
|
296 |
def use_fckeditor(self): |
948a3882c94a
add a use_fckeditor method on http request
sylvain.thenault@logilab.fr
parents:
940
diff
changeset
|
297 |
return self.vreg.config.fckeditor_installed() and self.property_value('ui.fckeditor') |
0 | 298 |
|
299 |
def edited_eids(self, withtype=False): |
|
300 |
"""return a list of edited eids""" |
|
301 |
yielded = False |
|
302 |
# warning: use .keys since the caller may change `form` |
|
303 |
form = self.form |
|
304 |
try: |
|
305 |
eids = form['eid'] |
|
306 |
except KeyError: |
|
307 |
raise NothingToEdit(None, {None: self._('no selected entities')}) |
|
308 |
if isinstance(eids, basestring): |
|
309 |
eids = (eids,) |
|
310 |
for peid in eids: |
|
311 |
if withtype: |
|
312 |
typekey = '__type:%s' % peid |
|
313 |
assert typekey in form, 'no entity type specified' |
|
314 |
yield peid, form[typekey] |
|
315 |
else: |
|
316 |
yield peid |
|
317 |
yielded = True |
|
318 |
if not yielded: |
|
319 |
raise NothingToEdit(None, {None: self._('no selected entities')}) |
|
320 |
||
321 |
# minparams=3 by default: at least eid, __type, and some params to change |
|
322 |
def extract_entity_params(self, eid, minparams=3): |
|
323 |
"""extract form parameters relative to the given eid""" |
|
324 |
params = {} |
|
325 |
eid = str(eid) |
|
326 |
form = self.form |
|
327 |
for param in form: |
|
328 |
try: |
|
329 |
name, peid = param.split(':', 1) |
|
330 |
except ValueError: |
|
331 |
if not param.startswith('__') and param != "eid": |
|
332 |
self.warning('param %s mis-formatted', param) |
|
333 |
continue |
|
334 |
if peid == eid: |
|
335 |
value = form[param] |
|
336 |
if value == INTERNAL_FIELD_VALUE: |
|
337 |
value = None |
|
338 |
params[name] = value |
|
339 |
params['eid'] = eid |
|
340 |
if len(params) < minparams: |
|
341 |
raise RequestError(self._('missing parameters for entity %s') % eid) |
|
342 |
return params |
|
1426 | 343 |
|
0 | 344 |
def get_pending_operations(self, entity, relname, role): |
345 |
operations = {'insert' : [], 'delete' : []} |
|
346 |
for optype in ('insert', 'delete'): |
|
347 |
data = self.get_session_data('pending_%s' % optype) or () |
|
348 |
for eidfrom, rel, eidto in data: |
|
349 |
if relname == rel: |
|
350 |
if role == 'subject' and entity.eid == eidfrom: |
|
351 |
operations[optype].append(eidto) |
|
352 |
if role == 'object' and entity.eid == eidto: |
|
353 |
operations[optype].append(eidfrom) |
|
354 |
return operations |
|
1426 | 355 |
|
0 | 356 |
def get_pending_inserts(self, eid=None): |
357 |
"""shortcut to access req's pending_insert entry |
|
358 |
||
359 |
This is where are stored relations being added while editing |
|
360 |
an entity. This used to be stored in a temporary cookie. |
|
361 |
""" |
|
362 |
pending = self.get_session_data('pending_insert') or () |
|
363 |
return ['%s:%s:%s' % (subj, rel, obj) for subj, rel, obj in pending |
|
364 |
if eid is None or eid in (subj, obj)] |
|
365 |
||
366 |
def get_pending_deletes(self, eid=None): |
|
367 |
"""shortcut to access req's pending_delete entry |
|
368 |
||
369 |
This is where are stored relations being removed while editing |
|
370 |
an entity. This used to be stored in a temporary cookie. |
|
371 |
""" |
|
372 |
pending = self.get_session_data('pending_delete') or () |
|
373 |
return ['%s:%s:%s' % (subj, rel, obj) for subj, rel, obj in pending |
|
374 |
if eid is None or eid in (subj, obj)] |
|
375 |
||
376 |
def remove_pending_operations(self): |
|
377 |
"""shortcut to clear req's pending_{delete,insert} entries |
|
378 |
||
379 |
This is needed when the edition is completed (whether it's validated |
|
380 |
or cancelled) |
|
381 |
""" |
|
382 |
self.del_session_data('pending_insert') |
|
383 |
self.del_session_data('pending_delete') |
|
384 |
||
385 |
def cancel_edition(self, errorurl): |
|
386 |
"""remove pending operations and `errorurl`'s specific stored data |
|
387 |
""" |
|
388 |
self.del_session_data(errorurl) |
|
389 |
self.remove_pending_operations() |
|
1426 | 390 |
|
0 | 391 |
# high level methods for HTTP headers management ########################## |
392 |
||
393 |
# must be cached since login/password are popped from the form dictionary |
|
394 |
# and this method may be called multiple times during authentication |
|
395 |
@cached |
|
396 |
def get_authorization(self): |
|
397 |
"""Parse and return the Authorization header""" |
|
398 |
if self.authmode == "cookie": |
|
399 |
try: |
|
400 |
user = self.form.pop("__login") |
|
401 |
passwd = self.form.pop("__password", '') |
|
402 |
return user, passwd.encode('UTF8') |
|
403 |
except KeyError: |
|
404 |
self.debug('no login/password in form params') |
|
405 |
return None, None |
|
406 |
else: |
|
407 |
return self.header_authorization() |
|
1426 | 408 |
|
0 | 409 |
def get_cookie(self): |
410 |
"""retrieve request cookies, returns an empty cookie if not found""" |
|
411 |
try: |
|
412 |
return Cookie.SimpleCookie(self.get_header('Cookie')) |
|
413 |
except KeyError: |
|
414 |
return Cookie.SimpleCookie() |
|
415 |
||
416 |
def set_cookie(self, cookie, key, maxage=300): |
|
417 |
"""set / update a cookie key |
|
418 |
||
419 |
by default, cookie will be available for the next 5 minutes. |
|
420 |
Give maxage = None to have a "session" cookie expiring when the |
|
421 |
client close its browser |
|
422 |
""" |
|
423 |
morsel = cookie[key] |
|
424 |
if maxage is not None: |
|
425 |
morsel['Max-Age'] = maxage |
|
426 |
# make sure cookie is set on the correct path |
|
427 |
morsel['path'] = self.base_url_path() |
|
428 |
self.add_header('Set-Cookie', morsel.OutputString()) |
|
429 |
||
430 |
def remove_cookie(self, cookie, key): |
|
431 |
"""remove a cookie by expiring it""" |
|
432 |
morsel = cookie[key] |
|
433 |
morsel['Max-Age'] = 0 |
|
434 |
# The only way to set up cookie age for IE is to use an old "expired" |
|
435 |
# syntax. IE doesn't support Max-Age there is no library support for |
|
1426 | 436 |
# managing |
0 | 437 |
# ===> Do _NOT_ comment this line : |
438 |
morsel['expires'] = 'Thu, 01-Jan-1970 00:00:00 GMT' |
|
439 |
self.add_header('Set-Cookie', morsel.OutputString()) |
|
440 |
||
441 |
def set_content_type(self, content_type, filename=None, encoding=None): |
|
442 |
"""set output content type for this request. An optional filename |
|
443 |
may be given |
|
444 |
""" |
|
445 |
if content_type.startswith('text/'): |
|
446 |
content_type += ';charset=' + (encoding or self.encoding) |
|
447 |
self.set_header('content-type', content_type) |
|
448 |
if filename: |
|
449 |
if isinstance(filename, unicode): |
|
450 |
filename = header(filename).encode() |
|
451 |
self.set_header('content-disposition', 'inline; filename=%s' |
|
452 |
% filename) |
|
453 |
||
454 |
# high level methods for HTML headers management ########################## |
|
455 |
||
456 |
def add_js(self, jsfiles, localfile=True): |
|
457 |
"""specify a list of JS files to include in the HTML headers |
|
458 |
:param jsfiles: a JS filename or a list of JS filenames |
|
459 |
:param localfile: if True, the default data dir prefix is added to the |
|
460 |
JS filename |
|
461 |
""" |
|
462 |
if isinstance(jsfiles, basestring): |
|
463 |
jsfiles = (jsfiles,) |
|
464 |
for jsfile in jsfiles: |
|
465 |
if localfile: |
|
466 |
jsfile = self.datadir_url + jsfile |
|
467 |
self.html_headers.add_js(jsfile) |
|
468 |
||
469 |
def add_css(self, cssfiles, media=u'all', localfile=True, ieonly=False): |
|
470 |
"""specify a CSS file to include in the HTML headers |
|
471 |
:param cssfiles: a CSS filename or a list of CSS filenames |
|
472 |
:param media: the CSS's media if necessary |
|
473 |
:param localfile: if True, the default data dir prefix is added to the |
|
474 |
CSS filename |
|
475 |
""" |
|
476 |
if isinstance(cssfiles, basestring): |
|
477 |
cssfiles = (cssfiles,) |
|
478 |
if ieonly: |
|
479 |
if self.ie_browser(): |
|
480 |
add_css = self.html_headers.add_ie_css |
|
481 |
else: |
|
482 |
return # no need to do anything on non IE browsers |
|
483 |
else: |
|
484 |
add_css = self.html_headers.add_css |
|
485 |
for cssfile in cssfiles: |
|
486 |
if localfile: |
|
487 |
cssfile = self.datadir_url + cssfile |
|
488 |
add_css(cssfile, media) |
|
1426 | 489 |
|
1801
672acc730ce5
ajax_replace_url becomes obsolete, req.build_ajax_replace_url should be used instead
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1718
diff
changeset
|
490 |
def build_ajax_replace_url(self, nodeid, rql, vid, replacemode='replace', |
672acc730ce5
ajax_replace_url becomes obsolete, req.build_ajax_replace_url should be used instead
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1718
diff
changeset
|
491 |
**extraparams): |
672acc730ce5
ajax_replace_url becomes obsolete, req.build_ajax_replace_url should be used instead
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1718
diff
changeset
|
492 |
"""builds an ajax url that will replace `nodeid`s content |
672acc730ce5
ajax_replace_url becomes obsolete, req.build_ajax_replace_url should be used instead
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1718
diff
changeset
|
493 |
:param nodeid: the dom id of the node to replace |
672acc730ce5
ajax_replace_url becomes obsolete, req.build_ajax_replace_url should be used instead
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1718
diff
changeset
|
494 |
:param rql: rql to execute |
672acc730ce5
ajax_replace_url becomes obsolete, req.build_ajax_replace_url should be used instead
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1718
diff
changeset
|
495 |
:param vid: the view to apply on the resultset |
672acc730ce5
ajax_replace_url becomes obsolete, req.build_ajax_replace_url should be used instead
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1718
diff
changeset
|
496 |
:param replacemode: defines how the replacement should be done. |
672acc730ce5
ajax_replace_url becomes obsolete, req.build_ajax_replace_url should be used instead
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1718
diff
changeset
|
497 |
Possible values are : |
672acc730ce5
ajax_replace_url becomes obsolete, req.build_ajax_replace_url should be used instead
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1718
diff
changeset
|
498 |
- 'replace' to replace the node's content with the generated HTML |
672acc730ce5
ajax_replace_url becomes obsolete, req.build_ajax_replace_url should be used instead
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1718
diff
changeset
|
499 |
- 'swap' to replace the node itself with the generated HTML |
672acc730ce5
ajax_replace_url becomes obsolete, req.build_ajax_replace_url should be used instead
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1718
diff
changeset
|
500 |
- 'append' to append the generated HTML to the node's content |
672acc730ce5
ajax_replace_url becomes obsolete, req.build_ajax_replace_url should be used instead
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1718
diff
changeset
|
501 |
""" |
672acc730ce5
ajax_replace_url becomes obsolete, req.build_ajax_replace_url should be used instead
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1718
diff
changeset
|
502 |
url = self.build_url('view', rql=rql, vid=vid, __notemplate=1, |
672acc730ce5
ajax_replace_url becomes obsolete, req.build_ajax_replace_url should be used instead
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1718
diff
changeset
|
503 |
**extraparams) |
672acc730ce5
ajax_replace_url becomes obsolete, req.build_ajax_replace_url should be used instead
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1718
diff
changeset
|
504 |
return "javascript: loadxhtml('%s', '%s', '%s')" % ( |
672acc730ce5
ajax_replace_url becomes obsolete, req.build_ajax_replace_url should be used instead
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1718
diff
changeset
|
505 |
nodeid, html_escape(url), replacemode) |
672acc730ce5
ajax_replace_url becomes obsolete, req.build_ajax_replace_url should be used instead
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1718
diff
changeset
|
506 |
|
0 | 507 |
# urls/path management #################################################### |
1426 | 508 |
|
0 | 509 |
def url(self, includeparams=True): |
510 |
"""return currently accessed url""" |
|
511 |
return self.base_url() + self.relative_path(includeparams) |
|
512 |
||
513 |
def _datadir_url(self): |
|
514 |
"""return url of the application's data directory""" |
|
515 |
return self.base_url() + 'data%s/' % self.vreg.config.instance_md5_version() |
|
1426 | 516 |
|
0 | 517 |
def selected(self, url): |
518 |
"""return True if the url is equivalent to currently accessed url""" |
|
519 |
reqpath = self.relative_path().lower() |
|
520 |
baselen = len(self.base_url()) |
|
521 |
return (reqpath == url[baselen:].lower()) |
|
522 |
||
523 |
def base_url_prepend_host(self, hostname): |
|
524 |
protocol, roothost = urlsplit(self.base_url())[:2] |
|
525 |
if roothost.startswith('www.'): |
|
526 |
roothost = roothost[4:] |
|
527 |
return '%s://%s.%s' % (protocol, hostname, roothost) |
|
528 |
||
529 |
def base_url_path(self): |
|
530 |
"""returns the absolute path of the base url""" |
|
531 |
return urlsplit(self.base_url())[2] |
|
1426 | 532 |
|
0 | 533 |
@cached |
534 |
def from_controller(self): |
|
535 |
"""return the id (string) of the controller issuing the request""" |
|
536 |
controller = self.relative_path(False).split('/', 1)[0] |
|
537 |
registered_controllers = (ctrl.id for ctrl in |
|
538 |
self.vreg.registry_objects('controllers')) |
|
539 |
if controller in registered_controllers: |
|
540 |
return controller |
|
541 |
return 'view' |
|
1426 | 542 |
|
0 | 543 |
def external_resource(self, rid, default=_MARKER): |
544 |
"""return a path to an external resource, using its identifier |
|
545 |
||
546 |
raise KeyError if the resource is not defined |
|
547 |
""" |
|
548 |
try: |
|
549 |
value = self.vreg.config.ext_resources[rid] |
|
550 |
except KeyError: |
|
551 |
if default is _MARKER: |
|
552 |
raise |
|
553 |
return default |
|
554 |
if value is None: |
|
555 |
return None |
|
556 |
baseurl = self.datadir_url[:-1] # remove trailing / |
|
557 |
if isinstance(value, list): |
|
558 |
return [v.replace('DATADIR', baseurl) for v in value] |
|
559 |
return value.replace('DATADIR', baseurl) |
|
560 |
external_resource = cached(external_resource, keyarg=1) |
|
561 |
||
562 |
def validate_cache(self): |
|
563 |
"""raise a `DirectResponse` exception if a cached page along the way |
|
564 |
exists and is still usable. |
|
565 |
||
566 |
calls the client-dependant implementation of `_validate_cache` |
|
567 |
""" |
|
568 |
self._validate_cache() |
|
569 |
if self.http_method() == 'HEAD': |
|
570 |
raise StatusResponse(200, '') |
|
1426 | 571 |
|
0 | 572 |
# abstract methods to override according to the web front-end ############# |
1426 | 573 |
|
0 | 574 |
def http_method(self): |
575 |
"""returns 'POST', 'GET', 'HEAD', etc.""" |
|
576 |
raise NotImplementedError() |
|
577 |
||
578 |
def _validate_cache(self): |
|
579 |
"""raise a `DirectResponse` exception if a cached page along the way |
|
580 |
exists and is still usable |
|
581 |
""" |
|
582 |
raise NotImplementedError() |
|
1426 | 583 |
|
0 | 584 |
def relative_path(self, includeparams=True): |
585 |
"""return the normalized path of the request (ie at least relative |
|
586 |
to the application's root, but some other normalization may be needed |
|
587 |
so that the returned path may be used to compare to generated urls |
|
588 |
||
589 |
:param includeparams: |
|
590 |
boolean indicating if GET form parameters should be kept in the path |
|
591 |
""" |
|
592 |
raise NotImplementedError() |
|
593 |
||
594 |
def get_header(self, header, default=None): |
|
595 |
"""return the value associated with the given input HTTP header, |
|
596 |
raise KeyError if the header is not set |
|
597 |
""" |
|
598 |
raise NotImplementedError() |
|
599 |
||
600 |
def set_header(self, header, value): |
|
601 |
"""set an output HTTP header""" |
|
602 |
raise NotImplementedError() |
|
603 |
||
604 |
def add_header(self, header, value): |
|
605 |
"""add an output HTTP header""" |
|
606 |
raise NotImplementedError() |
|
1426 | 607 |
|
0 | 608 |
def remove_header(self, header): |
609 |
"""remove an output HTTP header""" |
|
610 |
raise NotImplementedError() |
|
1426 | 611 |
|
0 | 612 |
def header_authorization(self): |
613 |
"""returns a couple (auth-type, auth-value)""" |
|
614 |
auth = self.get_header("Authorization", None) |
|
615 |
if auth: |
|
616 |
scheme, rest = auth.split(' ', 1) |
|
617 |
scheme = scheme.lower() |
|
618 |
try: |
|
619 |
assert scheme == "basic" |
|
620 |
user, passwd = base64.decodestring(rest).split(":", 1) |
|
621 |
# XXX HTTP header encoding: use email.Header? |
|
622 |
return user.decode('UTF8'), passwd |
|
623 |
except Exception, ex: |
|
624 |
self.debug('bad authorization %s (%s: %s)', |
|
625 |
auth, ex.__class__.__name__, ex) |
|
626 |
return None, None |
|
627 |
||
1716
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
628 |
@obsolete("use parse_accept_header('Accept-Language')") |
0 | 629 |
def header_accept_language(self): |
630 |
"""returns an ordered list of preferred languages""" |
|
1716
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
631 |
return [value.split('-')[0] for value in |
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
632 |
self.parse_accept_header('Accept-Language')] |
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
633 |
|
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
634 |
def parse_accept_header(self, header): |
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
635 |
"""returns an ordered list of preferred languages""" |
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
636 |
accepteds = self.get_header(header, '') |
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
637 |
values = [] |
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
638 |
for info in accepteds.split(','): |
0 | 639 |
try: |
1716
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
640 |
value, scores = info.split(';', 1) |
0 | 641 |
except ValueError: |
1716
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
642 |
value = info |
0 | 643 |
score = 1.0 |
1716
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
644 |
else: |
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
645 |
for score in scores.split(';'): |
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
646 |
try: |
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
647 |
scorekey, scoreval = score.split('=') |
1717
d2c4d3bd0602
correct wrong condition and missing import
Graziella Toutoungis <graziella.toutoungis@logilab.fr>
parents:
1716
diff
changeset
|
648 |
if scorekey == 'q': # XXX 'level' |
1716
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
649 |
score = float(score[2:]) # remove 'q=' |
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
650 |
except ValueError: |
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
651 |
continue |
1718
26ff2d292183
correct the values list append
Graziella Toutoungis <graziella.toutoungis@logilab.fr>
parents:
1717
diff
changeset
|
652 |
values.append((score, value)) |
1716
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
653 |
values.sort(reverse=True) |
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
654 |
return (value for (score, value) in values) |
0 | 655 |
|
656 |
def header_if_modified_since(self): |
|
657 |
"""If the HTTP header If-modified-since is set, return the equivalent |
|
658 |
mx date time value (GMT), else return None |
|
659 |
""" |
|
660 |
raise NotImplementedError() |
|
1426 | 661 |
|
0 | 662 |
# page data management #################################################### |
663 |
||
664 |
def get_page_data(self, key, default=None): |
|
665 |
"""return value associated to `key` in curernt page data""" |
|
666 |
page_data = self.cnx.get_session_data(self.pageid, {}) |
|
667 |
return page_data.get(key, default) |
|
1426 | 668 |
|
0 | 669 |
def set_page_data(self, key, value): |
670 |
"""set value associated to `key` in current page data""" |
|
671 |
self.html_headers.add_unload_pagedata() |
|
672 |
page_data = self.cnx.get_session_data(self.pageid, {}) |
|
673 |
page_data[key] = value |
|
674 |
return self.cnx.set_session_data(self.pageid, page_data) |
|
1426 | 675 |
|
0 | 676 |
def del_page_data(self, key=None): |
677 |
"""remove value associated to `key` in current page data |
|
678 |
if `key` is None, all page data will be cleared |
|
679 |
""" |
|
680 |
if key is None: |
|
681 |
self.cnx.del_session_data(self.pageid) |
|
682 |
else: |
|
683 |
page_data = self.cnx.get_session_data(self.pageid, {}) |
|
684 |
page_data.pop(key, None) |
|
685 |
self.cnx.set_session_data(self.pageid, page_data) |
|
686 |
||
687 |
# user-agent detection #################################################### |
|
688 |
||
689 |
@cached |
|
690 |
def useragent(self): |
|
691 |
return self.get_header('User-Agent', None) |
|
692 |
||
693 |
def ie_browser(self): |
|
694 |
useragent = self.useragent() |
|
695 |
return useragent and 'MSIE' in useragent |
|
1426 | 696 |
|
0 | 697 |
def xhtml_browser(self): |
698 |
useragent = self.useragent() |
|
1421
77ee26df178f
doc type handling refactoring: do the ext substitution at the module level
sylvain.thenault@logilab.fr
parents:
1173
diff
changeset
|
699 |
# * MSIE/Konqueror does not support xml content-type |
77ee26df178f
doc type handling refactoring: do the ext substitution at the module level
sylvain.thenault@logilab.fr
parents:
1173
diff
changeset
|
700 |
# * Opera supports xhtml and handles namespaces properly but it breaks |
77ee26df178f
doc type handling refactoring: do the ext substitution at the module level
sylvain.thenault@logilab.fr
parents:
1173
diff
changeset
|
701 |
# jQuery.attr() |
495
f8b1edfe9621
[#80966] Opera supports xhtml and handles namespaces properly but it breaks jQuery.attr(), so xhtml_browser return False if the webbrowser is opera
Stephanie Marcu <stephanie.marcu@logilab.fr>
parents:
0
diff
changeset
|
702 |
if useragent and ('MSIE' in useragent or 'KHTML' in useragent |
f8b1edfe9621
[#80966] Opera supports xhtml and handles namespaces properly but it breaks jQuery.attr(), so xhtml_browser return False if the webbrowser is opera
Stephanie Marcu <stephanie.marcu@logilab.fr>
parents:
0
diff
changeset
|
703 |
or 'Opera' in useragent): |
0 | 704 |
return False |
705 |
return True |
|
706 |
||
1421
77ee26df178f
doc type handling refactoring: do the ext substitution at the module level
sylvain.thenault@logilab.fr
parents:
1173
diff
changeset
|
707 |
def html_content_type(self): |
77ee26df178f
doc type handling refactoring: do the ext substitution at the module level
sylvain.thenault@logilab.fr
parents:
1173
diff
changeset
|
708 |
if self.xhtml_browser(): |
77ee26df178f
doc type handling refactoring: do the ext substitution at the module level
sylvain.thenault@logilab.fr
parents:
1173
diff
changeset
|
709 |
return 'application/xhtml+xml' |
77ee26df178f
doc type handling refactoring: do the ext substitution at the module level
sylvain.thenault@logilab.fr
parents:
1173
diff
changeset
|
710 |
return 'text/html' |
77ee26df178f
doc type handling refactoring: do the ext substitution at the module level
sylvain.thenault@logilab.fr
parents:
1173
diff
changeset
|
711 |
|
0 | 712 |
from cubicweb import set_log_methods |
713 |
set_log_methods(CubicWebRequestBase, LOGGER) |