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