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