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