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