author | Florent <florent@secondweb.fr> |
Tue, 19 May 2009 17:05:54 +0200 | |
branch | stable |
changeset 1873 | e96f50e52099 |
parent 1802 | d628defebc17 |
child 1940 | 2565aae48d48 |
permissions | -rw-r--r-- |
0 | 1 |
"""The edit controller, handling form submitting. |
2 |
||
3 |
:organization: Logilab |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1798
diff
changeset
|
4 |
:copyright: 2001-2009 LOGILAB S.A. (Paris, FRANCE), all rights reserved. |
0 | 5 |
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr |
6 |
""" |
|
7 |
__docformat__ = "restructuredtext en" |
|
8 |
from decimal import Decimal |
|
9 |
||
10 |
from rql.utils import rqlvar_maker |
|
11 |
||
12 |
from cubicweb import Binary, ValidationError, typed_eid |
|
13 |
from cubicweb.web import INTERNAL_FIELD_VALUE, RequestError, NothingToEdit |
|
14 |
from cubicweb.web.controller import parse_relations_descr |
|
15 |
from cubicweb.web.views.basecontrollers import ViewController |
|
16 |
||
17 |
||
18 |
class ToDoLater(Exception): |
|
19 |
"""exception used in the edit controller to indicate that a relation |
|
20 |
can't be handled right now and have to be handled later |
|
21 |
""" |
|
22 |
||
23 |
class EditController(ViewController): |
|
24 |
id = 'edit' |
|
25 |
||
26 |
def publish(self, rset=None, fromjson=False): |
|
27 |
"""edit / create / copy / delete entity / relations""" |
|
28 |
self.fromjson = fromjson |
|
884 | 29 |
for key in self.req.form: |
0 | 30 |
# There should be 0 or 1 action |
31 |
if key.startswith('__action_'): |
|
32 |
cbname = key[1:] |
|
33 |
try: |
|
34 |
callback = getattr(self, cbname) |
|
35 |
except AttributeError: |
|
884 | 36 |
raise RequestError(self.req._('invalid action %r' % key)) |
0 | 37 |
else: |
38 |
return callback() |
|
39 |
self._default_publish() |
|
40 |
self.reset() |
|
41 |
||
42 |
def _default_publish(self): |
|
43 |
req = self.req |
|
44 |
form = req.form |
|
45 |
# no specific action, generic edition |
|
46 |
self._to_create = req.data['eidmap'] = {} |
|
47 |
self._pending_relations = [] |
|
48 |
todelete = self.req.get_pending_deletes() |
|
49 |
toinsert = self.req.get_pending_inserts() |
|
50 |
try: |
|
51 |
methodname = form.pop('__method', None) |
|
52 |
for eid in req.edited_eids(): |
|
53 |
formparams = req.extract_entity_params(eid) |
|
54 |
if methodname is not None: |
|
55 |
entity = req.eid_rset(eid).get_entity(0, 0) |
|
56 |
method = getattr(entity, methodname) |
|
57 |
method(formparams) |
|
58 |
eid = self.edit_entity(formparams) |
|
59 |
except (RequestError, NothingToEdit): |
|
60 |
if '__linkto' in form and 'eid' in form: |
|
61 |
self.execute_linkto() |
|
62 |
elif not ('__delete' in form or '__insert' in form or todelete or toinsert): |
|
63 |
raise ValidationError(None, {None: req._('nothing to edit')}) |
|
64 |
# handle relations in newly created entities |
|
65 |
if self._pending_relations: |
|
66 |
for rschema, formparams, x, entity in self._pending_relations: |
|
67 |
self.handle_relation(rschema, formparams, x, entity, True) |
|
1753 | 68 |
|
0 | 69 |
# XXX this processes *all* pending operations of *all* entities |
70 |
if form.has_key('__delete'): |
|
71 |
todelete += req.list_form_param('__delete', form, pop=True) |
|
72 |
if todelete: |
|
73 |
self.delete_relations(parse_relations_descr(todelete)) |
|
74 |
if form.has_key('__insert'): |
|
75 |
toinsert = req.list_form_param('__insert', form, pop=True) |
|
76 |
if toinsert: |
|
77 |
self.insert_relations(parse_relations_descr(toinsert)) |
|
78 |
self.req.remove_pending_operations() |
|
1753 | 79 |
|
0 | 80 |
def edit_entity(self, formparams, multiple=False): |
81 |
"""edit / create / copy an entity and return its eid""" |
|
82 |
etype = formparams['__type'] |
|
83 |
entity = self.vreg.etype_class(etype)(self.req, None, None) |
|
84 |
entity.eid = eid = self._get_eid(formparams['eid']) |
|
85 |
edited = self.req.form.get('__maineid') == formparams['eid'] |
|
86 |
# let a chance to do some entity specific stuff. |
|
1753 | 87 |
entity.pre_web_edit() |
0 | 88 |
# create a rql query from parameters |
89 |
self.relations = [] |
|
90 |
self.restrictions = [] |
|
91 |
# process inlined relations at the same time as attributes |
|
92 |
# this is required by some external source such as the svn source which |
|
93 |
# needs some information provided by those inlined relation. Moreover |
|
94 |
# this will generate less write queries. |
|
95 |
for rschema in entity.e_schema.subject_relations(): |
|
96 |
if rschema.is_final(): |
|
97 |
self.handle_attribute(entity, rschema, formparams) |
|
98 |
elif rschema.inlined: |
|
99 |
self.handle_inlined_relation(rschema, formparams, entity) |
|
100 |
execute = self.req.execute |
|
101 |
if eid is None: # creation or copy |
|
1753 | 102 |
if self.relations: |
0 | 103 |
rql = 'INSERT %s X: %s' % (etype, ','.join(self.relations)) |
104 |
else: |
|
105 |
rql = 'INSERT %s X' % etype |
|
106 |
if self.restrictions: |
|
107 |
rql += ' WHERE %s' % ','.join(self.restrictions) |
|
108 |
try: |
|
1753 | 109 |
# get the new entity (in some cases, the type might have |
0 | 110 |
# changed as for the File --> Image mutation) |
111 |
entity = execute(rql, formparams).get_entity(0, 0) |
|
112 |
eid = entity.eid |
|
113 |
except ValidationError, ex: |
|
114 |
# ex.entity may be an int or an entity instance |
|
115 |
self._to_create[formparams['eid']] = ex.entity |
|
116 |
if self.fromjson: |
|
117 |
ex.entity = formparams['eid'] |
|
118 |
raise |
|
119 |
self._to_create[formparams['eid']] = eid |
|
120 |
elif self.relations: # edition of an existant entity |
|
121 |
varmaker = rqlvar_maker() |
|
122 |
var = varmaker.next() |
|
123 |
while var in formparams: |
|
124 |
var = varmaker.next() |
|
125 |
rql = 'SET %s WHERE X eid %%(%s)s' % (','.join(self.relations), var) |
|
126 |
if self.restrictions: |
|
127 |
rql += ', %s' % ','.join(self.restrictions) |
|
128 |
formparams[var] = eid |
|
129 |
execute(rql, formparams) |
|
130 |
for rschema in entity.e_schema.subject_relations(): |
|
131 |
if rschema.is_final() or rschema.inlined: |
|
132 |
continue |
|
133 |
self.handle_relation(rschema, formparams, 'subject', entity) |
|
134 |
for rschema in entity.e_schema.object_relations(): |
|
135 |
if rschema.is_final(): |
|
136 |
continue |
|
137 |
self.handle_relation(rschema, formparams, 'object', entity) |
|
138 |
if edited: |
|
139 |
self.notify_edited(entity) |
|
140 |
if formparams.has_key('__delete'): |
|
141 |
todelete = self.req.list_form_param('__delete', formparams, pop=True) |
|
142 |
self.delete_relations(parse_relations_descr(todelete)) |
|
143 |
if formparams.has_key('__cloned_eid'): |
|
144 |
entity.copy_relations(formparams['__cloned_eid']) |
|
145 |
if formparams.has_key('__insert'): |
|
146 |
toinsert = self.req.list_form_param('__insert', formparams, pop=True) |
|
147 |
self.insert_relations(parse_relations_descr(toinsert)) |
|
148 |
if edited: # only execute linkto for the main entity |
|
149 |
self.execute_linkto(eid) |
|
150 |
return eid |
|
151 |
||
152 |
def _action_apply(self): |
|
153 |
self._default_publish() |
|
154 |
self.reset() |
|
1753 | 155 |
|
0 | 156 |
def _action_cancel(self): |
157 |
errorurl = self.req.form.get('__errorurl') |
|
158 |
if errorurl: |
|
159 |
self.req.cancel_edition(errorurl) |
|
160 |
return self.reset() |
|
161 |
||
162 |
def _action_delete(self): |
|
163 |
self.delete_entities(self.req.edited_eids(withtype=True)) |
|
164 |
return self.reset() |
|
165 |
||
1162
f210dce0dc47
fix for booelan attribute which have empty string as false value and didn't work if default value for this attribute was True.
Stephanie Marcu <stephanie.marcu@logilab.fr>
parents:
0
diff
changeset
|
166 |
def _needs_edition(self, rtype, formparams, entity): |
0 | 167 |
"""returns True and and the new value if `rtype` was edited""" |
168 |
editkey = 'edits-%s' % rtype |
|
169 |
if not editkey in formparams: |
|
170 |
return False, None # not edited |
|
171 |
value = formparams.get(rtype) or None |
|
1162
f210dce0dc47
fix for booelan attribute which have empty string as false value and didn't work if default value for this attribute was True.
Stephanie Marcu <stephanie.marcu@logilab.fr>
parents:
0
diff
changeset
|
172 |
if entity.has_eid() and (formparams.get(editkey) or None) == value: |
0 | 173 |
return False, None # not modified |
174 |
if value == INTERNAL_FIELD_VALUE: |
|
1753 | 175 |
value = None |
0 | 176 |
return True, value |
177 |
||
178 |
def handle_attribute(self, entity, rschema, formparams): |
|
179 |
"""append to `relations` part of the rql query to edit the |
|
180 |
attribute described by the given schema if necessary |
|
181 |
""" |
|
182 |
attr = rschema.type |
|
1162
f210dce0dc47
fix for booelan attribute which have empty string as false value and didn't work if default value for this attribute was True.
Stephanie Marcu <stephanie.marcu@logilab.fr>
parents:
0
diff
changeset
|
183 |
edition_needed, value = self._needs_edition(attr, formparams, entity) |
0 | 184 |
if not edition_needed: |
185 |
return |
|
186 |
# test if entity class defines a special handler for this attribute |
|
187 |
custom_edit = getattr(entity, 'custom_%s_edit' % attr, None) |
|
188 |
if custom_edit: |
|
189 |
custom_edit(formparams, value, self.relations) |
|
190 |
return |
|
191 |
attrtype = rschema.objects(entity.e_schema)[0].type |
|
192 |
# on checkbox or selection, the field may not be in params |
|
193 |
if attrtype == 'Boolean': |
|
194 |
value = bool(value) |
|
195 |
elif attrtype == 'Decimal': |
|
196 |
value = Decimal(value) |
|
197 |
elif attrtype == 'Bytes': |
|
198 |
# if it is a file, transport it using a Binary (StringIO) |
|
907 | 199 |
# XXX later __detach is for the new widget system, the former is to |
200 |
# be removed once web/widgets.py has been dropped |
|
201 |
if formparams.has_key('__%s_detach' % attr) or formparams.has_key('%s__detach' % attr): |
|
0 | 202 |
# drop current file value |
203 |
value = None |
|
1101
0c067de38e46
unification of meta-attributes handling:
sylvain.thenault@logilab.fr
parents:
907
diff
changeset
|
204 |
# no need to check value when nor explicit detach nor new file |
0c067de38e46
unification of meta-attributes handling:
sylvain.thenault@logilab.fr
parents:
907
diff
changeset
|
205 |
# submitted, since it will think the attribute is not modified |
0 | 206 |
elif isinstance(value, unicode): |
207 |
# file modified using a text widget |
|
1360
13ae1121835e
rename attribute_metadata method to attr_metadata to save a few chars
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
208 |
encoding = entity.attr_metadata(attr, 'encoding') |
13ae1121835e
rename attribute_metadata method to attr_metadata to save a few chars
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
209 |
value = Binary(value.encode(encoding)) |
1765
a25c7c73c8f6
check a file is submitted first
sylvain.thenault@logilab.fr
parents:
1753
diff
changeset
|
210 |
elif value: |
1361
c558a88bb85d
ignore browser submitted values for file's MIME type
sylvain.thenault@logilab.fr
parents:
1360
diff
changeset
|
211 |
# value is a 3-uple (filename, mimetype, stream) |
0 | 212 |
val = Binary(value[2].read()) |
213 |
if not val.getvalue(): # usually an unexistant file |
|
214 |
value = None |
|
215 |
else: |
|
216 |
val.filename = value[0] |
|
1361
c558a88bb85d
ignore browser submitted values for file's MIME type
sylvain.thenault@logilab.fr
parents:
1360
diff
changeset
|
217 |
# ignore browser submitted MIME type since it may be buggy |
c558a88bb85d
ignore browser submitted values for file's MIME type
sylvain.thenault@logilab.fr
parents:
1360
diff
changeset
|
218 |
# XXX add a config option to tell if we should consider it |
c558a88bb85d
ignore browser submitted values for file's MIME type
sylvain.thenault@logilab.fr
parents:
1360
diff
changeset
|
219 |
# or not? |
c558a88bb85d
ignore browser submitted values for file's MIME type
sylvain.thenault@logilab.fr
parents:
1360
diff
changeset
|
220 |
#if entity.e_schema.has_metadata(attr, 'format'): |
c558a88bb85d
ignore browser submitted values for file's MIME type
sylvain.thenault@logilab.fr
parents:
1360
diff
changeset
|
221 |
# key = '%s_format' % attr |
c558a88bb85d
ignore browser submitted values for file's MIME type
sylvain.thenault@logilab.fr
parents:
1360
diff
changeset
|
222 |
# formparams[key] = value[1] |
c558a88bb85d
ignore browser submitted values for file's MIME type
sylvain.thenault@logilab.fr
parents:
1360
diff
changeset
|
223 |
# self.relations.append('X %s_format %%(%s)s' |
c558a88bb85d
ignore browser submitted values for file's MIME type
sylvain.thenault@logilab.fr
parents:
1360
diff
changeset
|
224 |
# % (attr, key)) |
1101
0c067de38e46
unification of meta-attributes handling:
sylvain.thenault@logilab.fr
parents:
907
diff
changeset
|
225 |
# XXX suppose a File compatible schema |
0 | 226 |
if entity.e_schema.has_subject_relation('name') \ |
227 |
and not formparams.get('name'): |
|
228 |
formparams['name'] = value[0] |
|
229 |
self.relations.append('X name %(name)s') |
|
230 |
value = val |
|
231 |
elif value is not None: |
|
232 |
if attrtype in ('Date', 'Datetime', 'Time'): |
|
233 |
try: |
|
234 |
value = self.parse_datetime(value, attrtype) |
|
235 |
except ValueError: |
|
236 |
raise ValidationError(entity.eid, |
|
237 |
{attr: self.req._("invalid date")}) |
|
238 |
elif attrtype == 'Password': |
|
239 |
# check confirmation (see PasswordWidget for confirmation field name) |
|
240 |
confirmval = formparams.get(attr + '-confirm') |
|
241 |
if confirmval != value: |
|
242 |
raise ValidationError(entity.eid, |
|
243 |
{attr: self.req._("password and confirmation don't match")}) |
|
244 |
# password should *always* be utf8 encoded |
|
245 |
value = value.encode('UTF8') |
|
246 |
else: |
|
247 |
# strip strings |
|
248 |
value = value.strip() |
|
249 |
elif attrtype == 'Password': |
|
250 |
# skip None password |
|
251 |
return # unset password |
|
252 |
formparams[attr] = value |
|
253 |
self.relations.append('X %s %%(%s)s' % (attr, attr)) |
|
254 |
||
255 |
def _relation_values(self, rschema, formparams, x, entity, late=False): |
|
256 |
"""handle edition for the (rschema, x) relation of the given entity |
|
257 |
""" |
|
258 |
rtype = rschema.type |
|
259 |
editkey = 'edit%s-%s' % (x[0], rtype) |
|
260 |
if not editkey in formparams: |
|
261 |
return # not edited |
|
262 |
try: |
|
263 |
values = self._linked_eids(self.req.list_form_param(rtype, formparams), late) |
|
264 |
except ToDoLater: |
|
265 |
self._pending_relations.append((rschema, formparams, x, entity)) |
|
266 |
return |
|
267 |
origvalues = set(typed_eid(eid) for eid in self.req.list_form_param(editkey, formparams)) |
|
268 |
return values, origvalues |
|
269 |
||
270 |
def handle_inlined_relation(self, rschema, formparams, entity, late=False): |
|
271 |
"""handle edition for the (rschema, x) relation of the given entity |
|
272 |
""" |
|
273 |
try: |
|
274 |
values, origvalues = self._relation_values(rschema, formparams, |
|
275 |
'subject', entity, late) |
|
276 |
except TypeError: |
|
277 |
return # not edited / to do later |
|
278 |
if values == origvalues: |
|
279 |
return # not modified |
|
280 |
attr = str(rschema) |
|
281 |
if values: |
|
282 |
formparams[attr] = iter(values).next() |
|
283 |
self.relations.append('X %s %s' % (attr, attr.upper())) |
|
284 |
self.restrictions.append('%s eid %%(%s)s' % (attr.upper(), attr)) |
|
285 |
elif entity.has_eid(): |
|
286 |
self.handle_relation(rschema, formparams, 'subject', entity, late) |
|
1753 | 287 |
|
0 | 288 |
def handle_relation(self, rschema, formparams, x, entity, late=False): |
289 |
"""handle edition for the (rschema, x) relation of the given entity |
|
290 |
""" |
|
291 |
try: |
|
292 |
values, origvalues = self._relation_values(rschema, formparams, x, |
|
293 |
entity, late) |
|
294 |
except TypeError: |
|
295 |
return # not edited / to do later |
|
296 |
etype = entity.e_schema |
|
297 |
if values == origvalues: |
|
298 |
return # not modified |
|
299 |
if x == 'subject': |
|
300 |
desttype = rschema.objects(etype)[0] |
|
301 |
card = rschema.rproperty(etype, desttype, 'cardinality')[0] |
|
302 |
subjvar, objvar = 'X', 'Y' |
|
303 |
else: |
|
304 |
desttype = rschema.subjects(etype)[0] |
|
305 |
card = rschema.rproperty(desttype, etype, 'cardinality')[1] |
|
306 |
subjvar, objvar = 'Y', 'X' |
|
307 |
eid = entity.eid |
|
308 |
if x == 'object' or not rschema.inlined or not values: |
|
309 |
# this is not an inlined relation or no values specified, |
|
310 |
# explicty remove relations |
|
1798
cc86fe8efaaa
pass default values along the whole call chain, fix hidden field update bug
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1765
diff
changeset
|
311 |
rql = 'DELETE %s %s %s WHERE X eid %%(x)s, Y eid %%(y)s' % ( |
cc86fe8efaaa
pass default values along the whole call chain, fix hidden field update bug
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1765
diff
changeset
|
312 |
subjvar, rschema, objvar) |
0 | 313 |
for reid in origvalues.difference(values): |
314 |
self.req.execute(rql, {'x': eid, 'y': reid}, ('x', 'y')) |
|
1798
cc86fe8efaaa
pass default values along the whole call chain, fix hidden field update bug
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1765
diff
changeset
|
315 |
seteids = values.difference(origvalues) |
cc86fe8efaaa
pass default values along the whole call chain, fix hidden field update bug
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1765
diff
changeset
|
316 |
if seteids: |
cc86fe8efaaa
pass default values along the whole call chain, fix hidden field update bug
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1765
diff
changeset
|
317 |
rql = 'SET %s %s %s WHERE X eid %%(x)s, Y eid %%(y)s' % ( |
cc86fe8efaaa
pass default values along the whole call chain, fix hidden field update bug
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1765
diff
changeset
|
318 |
subjvar, rschema, objvar) |
cc86fe8efaaa
pass default values along the whole call chain, fix hidden field update bug
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1765
diff
changeset
|
319 |
for reid in seteids: |
cc86fe8efaaa
pass default values along the whole call chain, fix hidden field update bug
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1765
diff
changeset
|
320 |
self.req.execute(rql, {'x': eid, 'y': reid}, ('x', 'y')) |
1753 | 321 |
|
0 | 322 |
def _get_eid(self, eid): |
323 |
# should be either an int (existant entity) or a variable (to be |
|
324 |
# created entity) |
|
325 |
assert eid or eid == 0, repr(eid) # 0 is a valid eid |
|
326 |
try: |
|
327 |
return typed_eid(eid) |
|
328 |
except ValueError: |
|
329 |
try: |
|
330 |
return self._to_create[eid] |
|
331 |
except KeyError: |
|
332 |
self._to_create[eid] = None |
|
333 |
return None |
|
334 |
||
335 |
def _linked_eids(self, eids, late=False): |
|
336 |
"""return a list of eids if they are all known, else raise ToDoLater |
|
337 |
""" |
|
338 |
result = set() |
|
339 |
for eid in eids: |
|
340 |
if not eid: # AutoCompletionWidget |
|
341 |
continue |
|
342 |
eid = self._get_eid(eid) |
|
343 |
if eid is None: |
|
344 |
if not late: |
|
345 |
raise ToDoLater() |
|
346 |
# eid is still None while it's already a late call |
|
347 |
# this mean that the associated entity has not been created |
|
348 |
raise Exception('duh') |
|
349 |
result.add(eid) |
|
350 |
return result |
|
351 |
||
1753 | 352 |