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