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