author | Sylvain Thénault <sylvain.thenault@logilab.fr> |
Tue, 19 Jan 2010 10:19:08 +0100 | |
changeset 4257 | 0a9b38a492e1 |
parent 4252 | 6c4f109c2b03 |
child 4277 | 35cd057339b2 |
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 |
|
0 | 389 |
def get_pending_operations(self, entity, relname, role): |
390 |
operations = {'insert' : [], 'delete' : []} |
|
391 |
for optype in ('insert', 'delete'): |
|
392 |
data = self.get_session_data('pending_%s' % optype) or () |
|
393 |
for eidfrom, rel, eidto in data: |
|
394 |
if relname == rel: |
|
395 |
if role == 'subject' and entity.eid == eidfrom: |
|
396 |
operations[optype].append(eidto) |
|
397 |
if role == 'object' and entity.eid == eidto: |
|
398 |
operations[optype].append(eidfrom) |
|
399 |
return operations |
|
1426 | 400 |
|
0 | 401 |
def get_pending_inserts(self, eid=None): |
402 |
"""shortcut to access req's pending_insert entry |
|
403 |
||
404 |
This is where are stored relations being added while editing |
|
405 |
an entity. This used to be stored in a temporary cookie. |
|
406 |
""" |
|
407 |
pending = self.get_session_data('pending_insert') or () |
|
408 |
return ['%s:%s:%s' % (subj, rel, obj) for subj, rel, obj in pending |
|
409 |
if eid is None or eid in (subj, obj)] |
|
410 |
||
411 |
def get_pending_deletes(self, eid=None): |
|
412 |
"""shortcut to access req's pending_delete entry |
|
413 |
||
414 |
This is where are stored relations being removed while editing |
|
415 |
an entity. This used to be stored in a temporary cookie. |
|
416 |
""" |
|
417 |
pending = self.get_session_data('pending_delete') or () |
|
418 |
return ['%s:%s:%s' % (subj, rel, obj) for subj, rel, obj in pending |
|
419 |
if eid is None or eid in (subj, obj)] |
|
420 |
||
421 |
def remove_pending_operations(self): |
|
422 |
"""shortcut to clear req's pending_{delete,insert} entries |
|
423 |
||
424 |
This is needed when the edition is completed (whether it's validated |
|
425 |
or cancelled) |
|
426 |
""" |
|
427 |
self.del_session_data('pending_insert') |
|
428 |
self.del_session_data('pending_delete') |
|
429 |
||
430 |
def cancel_edition(self, errorurl): |
|
431 |
"""remove pending operations and `errorurl`'s specific stored data |
|
432 |
""" |
|
433 |
self.del_session_data(errorurl) |
|
434 |
self.remove_pending_operations() |
|
1426 | 435 |
|
0 | 436 |
# high level methods for HTTP headers management ########################## |
437 |
||
438 |
# must be cached since login/password are popped from the form dictionary |
|
439 |
# and this method may be called multiple times during authentication |
|
440 |
@cached |
|
441 |
def get_authorization(self): |
|
442 |
"""Parse and return the Authorization header""" |
|
443 |
if self.authmode == "cookie": |
|
444 |
try: |
|
445 |
user = self.form.pop("__login") |
|
446 |
passwd = self.form.pop("__password", '') |
|
447 |
return user, passwd.encode('UTF8') |
|
448 |
except KeyError: |
|
449 |
self.debug('no login/password in form params') |
|
450 |
return None, None |
|
451 |
else: |
|
452 |
return self.header_authorization() |
|
1426 | 453 |
|
0 | 454 |
def get_cookie(self): |
455 |
"""retrieve request cookies, returns an empty cookie if not found""" |
|
456 |
try: |
|
457 |
return Cookie.SimpleCookie(self.get_header('Cookie')) |
|
458 |
except KeyError: |
|
459 |
return Cookie.SimpleCookie() |
|
460 |
||
3653
ef71abb1e77b
[req] new expires argument to set_cookie
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3293
diff
changeset
|
461 |
def set_cookie(self, cookie, key, maxage=300, expires=None): |
0 | 462 |
"""set / update a cookie key |
463 |
||
464 |
by default, cookie will be available for the next 5 minutes. |
|
465 |
Give maxage = None to have a "session" cookie expiring when the |
|
466 |
client close its browser |
|
467 |
""" |
|
468 |
morsel = cookie[key] |
|
469 |
if maxage is not None: |
|
470 |
morsel['Max-Age'] = maxage |
|
3653
ef71abb1e77b
[req] new expires argument to set_cookie
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3293
diff
changeset
|
471 |
if expires: |
ef71abb1e77b
[req] new expires argument to set_cookie
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3293
diff
changeset
|
472 |
morsel['expires'] = expires.strftime('%a, %d %b %Y %H:%M:%S %z') |
0 | 473 |
# make sure cookie is set on the correct path |
474 |
morsel['path'] = self.base_url_path() |
|
475 |
self.add_header('Set-Cookie', morsel.OutputString()) |
|
476 |
||
477 |
def remove_cookie(self, cookie, key): |
|
478 |
"""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
|
479 |
self.set_cookie(cookie, key, maxage=0, expires=date(1970, 1, 1)) |
0 | 480 |
|
481 |
def set_content_type(self, content_type, filename=None, encoding=None): |
|
482 |
"""set output content type for this request. An optional filename |
|
483 |
may be given |
|
484 |
""" |
|
485 |
if content_type.startswith('text/'): |
|
486 |
content_type += ';charset=' + (encoding or self.encoding) |
|
487 |
self.set_header('content-type', content_type) |
|
488 |
if filename: |
|
489 |
if isinstance(filename, unicode): |
|
490 |
filename = header(filename).encode() |
|
491 |
self.set_header('content-disposition', 'inline; filename=%s' |
|
492 |
% filename) |
|
493 |
||
494 |
# high level methods for HTML headers management ########################## |
|
495 |
||
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
|
496 |
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
|
497 |
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
|
498 |
|
0 | 499 |
def add_js(self, jsfiles, localfile=True): |
500 |
"""specify a list of JS files to include in the HTML headers |
|
501 |
:param jsfiles: a JS filename or a list of JS filenames |
|
502 |
:param localfile: if True, the default data dir prefix is added to the |
|
503 |
JS filename |
|
504 |
""" |
|
505 |
if isinstance(jsfiles, basestring): |
|
506 |
jsfiles = (jsfiles,) |
|
507 |
for jsfile in jsfiles: |
|
508 |
if localfile: |
|
509 |
jsfile = self.datadir_url + jsfile |
|
510 |
self.html_headers.add_js(jsfile) |
|
511 |
||
512 |
def add_css(self, cssfiles, media=u'all', localfile=True, ieonly=False): |
|
513 |
"""specify a CSS file to include in the HTML headers |
|
514 |
:param cssfiles: a CSS filename or a list of CSS filenames |
|
515 |
:param media: the CSS's media if necessary |
|
516 |
:param localfile: if True, the default data dir prefix is added to the |
|
517 |
CSS filename |
|
518 |
""" |
|
519 |
if isinstance(cssfiles, basestring): |
|
520 |
cssfiles = (cssfiles,) |
|
521 |
if ieonly: |
|
522 |
if self.ie_browser(): |
|
523 |
add_css = self.html_headers.add_ie_css |
|
524 |
else: |
|
525 |
return # no need to do anything on non IE browsers |
|
526 |
else: |
|
527 |
add_css = self.html_headers.add_css |
|
528 |
for cssfile in cssfiles: |
|
529 |
if localfile: |
|
530 |
cssfile = self.datadir_url + cssfile |
|
531 |
add_css(cssfile, media) |
|
1426 | 532 |
|
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
|
533 |
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
|
534 |
**extraparams): |
672acc730ce5
ajax_replace_url becomes obsolete, req.build_ajax_replace_url should be used instead
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1718
diff
changeset
|
535 |
"""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
|
536 |
: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
|
537 |
: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
|
538 |
: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
|
539 |
: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
|
540 |
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
|
541 |
- '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
|
542 |
- '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
|
543 |
- '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
|
544 |
""" |
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
|
545 |
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
|
546 |
**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
|
547 |
return "javascript: loadxhtml('%s', '%s', '%s')" % ( |
2312
af4d8f75c5db
use xml_escape
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2258
diff
changeset
|
548 |
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
|
549 |
|
0 | 550 |
# urls/path management #################################################### |
1426 | 551 |
|
0 | 552 |
def url(self, includeparams=True): |
553 |
"""return currently accessed url""" |
|
554 |
return self.base_url() + self.relative_path(includeparams) |
|
555 |
||
556 |
def _datadir_url(self): |
|
2476
1294a6bdf3bf
application -> instance where it makes sense
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2315
diff
changeset
|
557 |
"""return url of the instance's data directory""" |
0 | 558 |
return self.base_url() + 'data%s/' % self.vreg.config.instance_md5_version() |
1426 | 559 |
|
0 | 560 |
def selected(self, url): |
561 |
"""return True if the url is equivalent to currently accessed url""" |
|
562 |
reqpath = self.relative_path().lower() |
|
563 |
baselen = len(self.base_url()) |
|
564 |
return (reqpath == url[baselen:].lower()) |
|
565 |
||
566 |
def base_url_prepend_host(self, hostname): |
|
567 |
protocol, roothost = urlsplit(self.base_url())[:2] |
|
568 |
if roothost.startswith('www.'): |
|
569 |
roothost = roothost[4:] |
|
570 |
return '%s://%s.%s' % (protocol, hostname, roothost) |
|
571 |
||
572 |
def base_url_path(self): |
|
573 |
"""returns the absolute path of the base url""" |
|
574 |
return urlsplit(self.base_url())[2] |
|
1426 | 575 |
|
0 | 576 |
@cached |
577 |
def from_controller(self): |
|
578 |
"""return the id (string) of the controller issuing the request""" |
|
579 |
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
|
580 |
registered_controllers = self.vreg['controllers'].keys() |
0 | 581 |
if controller in registered_controllers: |
582 |
return controller |
|
583 |
return 'view' |
|
1426 | 584 |
|
0 | 585 |
def external_resource(self, rid, default=_MARKER): |
586 |
"""return a path to an external resource, using its identifier |
|
587 |
||
588 |
raise KeyError if the resource is not defined |
|
589 |
""" |
|
590 |
try: |
|
591 |
value = self.vreg.config.ext_resources[rid] |
|
592 |
except KeyError: |
|
593 |
if default is _MARKER: |
|
594 |
raise |
|
595 |
return default |
|
596 |
if value is None: |
|
597 |
return None |
|
598 |
baseurl = self.datadir_url[:-1] # remove trailing / |
|
599 |
if isinstance(value, list): |
|
600 |
return [v.replace('DATADIR', baseurl) for v in value] |
|
601 |
return value.replace('DATADIR', baseurl) |
|
602 |
external_resource = cached(external_resource, keyarg=1) |
|
603 |
||
604 |
def validate_cache(self): |
|
605 |
"""raise a `DirectResponse` exception if a cached page along the way |
|
606 |
exists and is still usable. |
|
607 |
||
608 |
calls the client-dependant implementation of `_validate_cache` |
|
609 |
""" |
|
610 |
self._validate_cache() |
|
611 |
if self.http_method() == 'HEAD': |
|
612 |
raise StatusResponse(200, '') |
|
1426 | 613 |
|
0 | 614 |
# abstract methods to override according to the web front-end ############# |
1426 | 615 |
|
0 | 616 |
def http_method(self): |
617 |
"""returns 'POST', 'GET', 'HEAD', etc.""" |
|
618 |
raise NotImplementedError() |
|
619 |
||
620 |
def _validate_cache(self): |
|
621 |
"""raise a `DirectResponse` exception if a cached page along the way |
|
622 |
exists and is still usable |
|
623 |
""" |
|
624 |
raise NotImplementedError() |
|
1426 | 625 |
|
0 | 626 |
def relative_path(self, includeparams=True): |
627 |
"""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
|
628 |
to the instance's root, but some other normalization may be needed |
0 | 629 |
so that the returned path may be used to compare to generated urls |
630 |
||
631 |
:param includeparams: |
|
632 |
boolean indicating if GET form parameters should be kept in the path |
|
633 |
""" |
|
634 |
raise NotImplementedError() |
|
635 |
||
636 |
def get_header(self, header, default=None): |
|
637 |
"""return the value associated with the given input HTTP header, |
|
638 |
raise KeyError if the header is not set |
|
639 |
""" |
|
640 |
raise NotImplementedError() |
|
641 |
||
642 |
def set_header(self, header, value): |
|
643 |
"""set an output HTTP header""" |
|
644 |
raise NotImplementedError() |
|
645 |
||
646 |
def add_header(self, header, value): |
|
647 |
"""add an output HTTP header""" |
|
648 |
raise NotImplementedError() |
|
1426 | 649 |
|
0 | 650 |
def remove_header(self, header): |
651 |
"""remove an output HTTP header""" |
|
652 |
raise NotImplementedError() |
|
1426 | 653 |
|
0 | 654 |
def header_authorization(self): |
655 |
"""returns a couple (auth-type, auth-value)""" |
|
656 |
auth = self.get_header("Authorization", None) |
|
657 |
if auth: |
|
658 |
scheme, rest = auth.split(' ', 1) |
|
659 |
scheme = scheme.lower() |
|
660 |
try: |
|
661 |
assert scheme == "basic" |
|
662 |
user, passwd = base64.decodestring(rest).split(":", 1) |
|
663 |
# XXX HTTP header encoding: use email.Header? |
|
664 |
return user.decode('UTF8'), passwd |
|
665 |
except Exception, ex: |
|
666 |
self.debug('bad authorization %s (%s: %s)', |
|
667 |
auth, ex.__class__.__name__, ex) |
|
668 |
return None, None |
|
669 |
||
2788
8d3dbe577d3a
R put version info in deprecation warnings
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2650
diff
changeset
|
670 |
@deprecated("[3.4] use parse_accept_header('Accept-Language')") |
0 | 671 |
def header_accept_language(self): |
672 |
"""returns an ordered list of preferred languages""" |
|
1716
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
673 |
return [value.split('-')[0] for value in |
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
674 |
self.parse_accept_header('Accept-Language')] |
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
675 |
|
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
676 |
def parse_accept_header(self, header): |
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
677 |
"""returns an ordered list of preferred languages""" |
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
678 |
accepteds = self.get_header(header, '') |
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
679 |
values = [] |
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
680 |
for info in accepteds.split(','): |
0 | 681 |
try: |
1716
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
682 |
value, scores = info.split(';', 1) |
0 | 683 |
except ValueError: |
1716
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
684 |
value = info |
0 | 685 |
score = 1.0 |
1716
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
686 |
else: |
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
687 |
for score in scores.split(';'): |
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
688 |
try: |
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
689 |
scorekey, scoreval = score.split('=') |
1717
d2c4d3bd0602
correct wrong condition and missing import
Graziella Toutoungis <graziella.toutoungis@logilab.fr>
parents:
1716
diff
changeset
|
690 |
if scorekey == 'q': # XXX 'level' |
1716
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
691 |
score = float(score[2:]) # remove 'q=' |
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
692 |
except ValueError: |
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
693 |
continue |
1718
26ff2d292183
correct the values list append
Graziella Toutoungis <graziella.toutoungis@logilab.fr>
parents:
1717
diff
changeset
|
694 |
values.append((score, value)) |
1716
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
695 |
values.sort(reverse=True) |
b12d9e22bac3
basic support for http Accept header (untested)
sylvain.thenault@logilab.fr
parents:
1560
diff
changeset
|
696 |
return (value for (score, value) in values) |
0 | 697 |
|
698 |
def header_if_modified_since(self): |
|
699 |
"""If the HTTP header If-modified-since is set, return the equivalent |
|
700 |
mx date time value (GMT), else return None |
|
701 |
""" |
|
702 |
raise NotImplementedError() |
|
1426 | 703 |
|
3094
978ed8c2c0e4
[googlemap] #344872 set request content-type to text/html
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2650
diff
changeset
|
704 |
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
|
705 |
"""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
|
706 |
|
978ed8c2c0e4
[googlemap] #344872 set request content-type to text/html
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2650
diff
changeset
|
707 |
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
|
708 |
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
|
709 |
""" |
978ed8c2c0e4
[googlemap] #344872 set request content-type to text/html
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2650
diff
changeset
|
710 |
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
|
711 |
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
|
712 |
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
|
713 |
|
0 | 714 |
# page data management #################################################### |
715 |
||
716 |
def get_page_data(self, key, default=None): |
|
717 |
"""return value associated to `key` in curernt page data""" |
|
718 |
page_data = self.cnx.get_session_data(self.pageid, {}) |
|
719 |
return page_data.get(key, default) |
|
1426 | 720 |
|
0 | 721 |
def set_page_data(self, key, value): |
722 |
"""set value associated to `key` in current page data""" |
|
723 |
self.html_headers.add_unload_pagedata() |
|
724 |
page_data = self.cnx.get_session_data(self.pageid, {}) |
|
725 |
page_data[key] = value |
|
726 |
return self.cnx.set_session_data(self.pageid, page_data) |
|
1426 | 727 |
|
0 | 728 |
def del_page_data(self, key=None): |
729 |
"""remove value associated to `key` in current page data |
|
730 |
if `key` is None, all page data will be cleared |
|
731 |
""" |
|
732 |
if key is None: |
|
733 |
self.cnx.del_session_data(self.pageid) |
|
734 |
else: |
|
735 |
page_data = self.cnx.get_session_data(self.pageid, {}) |
|
736 |
page_data.pop(key, None) |
|
737 |
self.cnx.set_session_data(self.pageid, page_data) |
|
738 |
||
739 |
# user-agent detection #################################################### |
|
740 |
||
741 |
@cached |
|
742 |
def useragent(self): |
|
743 |
return self.get_header('User-Agent', None) |
|
744 |
||
745 |
def ie_browser(self): |
|
746 |
useragent = self.useragent() |
|
747 |
return useragent and 'MSIE' in useragent |
|
1426 | 748 |
|
0 | 749 |
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
|
750 |
"""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
|
751 |
|
81c8b5312f9c
move test on force-html-content-type to xhtml_browser method
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2556
diff
changeset
|
752 |
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
|
753 |
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
|
754 |
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
|
755 |
""" |
81c8b5312f9c
move test on force-html-content-type to xhtml_browser method
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2556
diff
changeset
|
756 |
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
|
757 |
return False |
0 | 758 |
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
|
759 |
# * 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
|
760 |
# * 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
|
761 |
# 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
|
762 |
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
|
763 |
or 'Opera' in useragent): |
0 | 764 |
return False |
765 |
return True |
|
766 |
||
1421
77ee26df178f
doc type handling refactoring: do the ext substitution at the module level
sylvain.thenault@logilab.fr
parents:
1173
diff
changeset
|
767 |
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
|
768 |
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
|
769 |
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
|
770 |
return 'text/html' |
77ee26df178f
doc type handling refactoring: do the ext substitution at the module level
sylvain.thenault@logilab.fr
parents:
1173
diff
changeset
|
771 |
|
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
|
772 |
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
|
773 |
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
|
774 |
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
|
775 |
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
|
776 |
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
|
777 |
|
0 | 778 |
from cubicweb import set_log_methods |
779 |
set_log_methods(CubicWebRequestBase, LOGGER) |