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