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