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