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