[MERGE] OPW 578099: ir.filters should be translated according to the user language
[odoo/odoo.git] / bin / osv / fields.py
index 724077a..652a481 100644 (file)
 #
 import datetime as DT
 import string
-import netsvc
 import sys
 import warnings
-
+import xmlrpclib
 from psycopg2 import Binary
 
+import osv
+import netsvc
 import tools
 from tools.translate import _
 
@@ -63,8 +64,16 @@ class _column(object):
     _symbol_set = (_symbol_c, _symbol_f)
     _symbol_get = None
 
-    def __init__(self, string='unknown', required=False, readonly=False, domain=None, context={}, states=None, priority=0, change_default=False, size=None, ondelete="set null", translate=False, select=False, **args):
-        if not context:
+    def __init__(self, string='unknown', required=False, readonly=False, domain=None, context=None, states=None, priority=0, change_default=False, size=None, ondelete="set null", translate=False, select=False, manual=False, **args):
+        """
+
+        The 'manual' keyword argument specifies if the field is a custom one.
+        It corresponds to the 'state' column in ir_model_fields.
+
+        """
+        if domain is None:
+            domain = []
+        if context is None:
             context = {}
         self.states = states or {}
         self.string = string
@@ -76,12 +85,13 @@ class _column(object):
         self.change_default = change_default
         self.ondelete = ondelete
         self.translate = translate
-        self._domain = domain or []
+        self._domain = domain
         self._context = context
         self.write = False
         self.read = False
         self.view_load = 0
         self.select = select
+        self.manual = manual
         self.selectable = True
         self.group_operator = args.get('group_operator', False)
         for a in args:
@@ -121,26 +131,39 @@ class boolean(_column):
     _symbol_f = lambda x: x and 'True' or 'False'
     _symbol_set = (_symbol_c, _symbol_f)
 
-class integer_big(_column):
-    _type = 'integer_big'
+class integer(_column):
+    _type = 'integer'
     _symbol_c = '%s'
     _symbol_f = lambda x: int(x or 0)
     _symbol_set = (_symbol_c, _symbol_f)
     _symbol_get = lambda self,x: x or 0
 
-class integer(_column):
-    _type = 'integer'
+class integer_big(_column):
+    _type = 'integer_big'
+    # do not reference the _symbol_* of integer class, as that would possibly
+    # unbind the lambda functions
     _symbol_c = '%s'
     _symbol_f = lambda x: int(x or 0)
     _symbol_set = (_symbol_c, _symbol_f)
     _symbol_get = lambda self,x: x or 0
 
-
 class reference(_column):
     _type = 'reference'
+    _classic_read = False 
     def __init__(self, string, selection, size, **args):
         _column.__init__(self, string=string, size=size, selection=selection, **args)
 
+    def get(self, cr, obj, ids, name, uid=None, context=None, values=None):
+        result = {}
+        # copy initial values fetched previously.
+        for value in values:
+            result[value['id']] = value[name]
+            if value[name]:
+                model, res_id = value[name].split(',')
+                if not obj.pool.get(model).exists(cr, uid, [int(res_id)], context=context):
+                    result[value['id']] = False
+        return result
+
 
 class char(_column):
     _type = 'char'
@@ -254,7 +277,13 @@ class binary(_column):
                 if v['id'] == i:
                     val = v[name]
                     break
-            if context.get('bin_size', False) and val:
+
+            # If client is requesting only the size of the field, we return it instead
+            # of the content. Presumably a separate request will be done to read the actual
+            # content if it's needed at some point.
+            # TODO: after 6.0 we should consider returning a dict with size and content instead of
+            #       having an implicit convention for the value
+            if val and context.get('bin_size_%s' % name, context.get('bin_size')):
                 res[i] = tools.human_size(long(val))
             else:
                 res[i] = val
@@ -333,8 +362,10 @@ class many2one(_column):
         return result
 
     def get(self, cr, obj, ids, name, user=None, context=None, values=None):
-        context = context or {}
-        values = values or {}
+        if context is None:
+            context = {}
+        if values is None:
+            values = {}
 
         res = {}
         for r in values:
@@ -346,7 +377,9 @@ class many2one(_column):
         # build a dictionary of the form {'id_of_distant_resource': name_of_distant_resource}
         # we use uid=1 because the visibility of a many2one field value (just id and name)
         # must be the access right of the parent form and not the linked object itself.
-        records = dict(obj.name_get(cr, 1, list(set(filter(None, res.values()))), context=context))
+        records = dict(obj.name_get(cr, 1,
+                                    list(set([x for x in res.values() if isinstance(x, (int,long))])),
+                                    context=context))
         for id in res:
             if res[id] in records:
                 res[id] = (res[id], records[res[id]])
@@ -397,7 +430,7 @@ class one2many(_column):
         assert(self.change_default != True)
 
     def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
-        if not context:
+        if context is None:
             context = {}
         if self._context:
             context = context.copy()
@@ -433,7 +466,7 @@ class one2many(_column):
             elif act[0] == 3:
                 obj.datas[act[1]][self._fields_id] = False
             elif act[0] == 4:
-                obj.datas[act[1]] = id
+                obj.datas[act[1]][self._fields_id] = id
             elif act[0] == 5:
                 for o in obj.datas.values():
                     if o[self._fields_id] == id:
@@ -446,12 +479,12 @@ class one2many(_column):
         raise _('Not Implemented')
 
     def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
-        if not context:
+        if context is None:
             context = {}
         if self._context:
             context = context.copy()
         context.update(self._context)
-        if not values:
+        if values is None:
             values = {}
 
         res = {}
@@ -542,7 +575,13 @@ class many2many(_column):
             warnings.warn("Specifying offset at a many2many.get() may produce unpredictable results.",
                       DeprecationWarning, stacklevel=2)
         obj = obj.pool.get(self._obj)
-        wquery = obj._where_calc(cr, user, self._domain, context=context)
+
+        # static domains are lists, and are evaluated both here and on client-side, while string
+        # domains supposed by dynamic and evaluated on client-side only (thus ignored here)
+        # FIXME: make this distinction explicit in API!
+        domain = isinstance(self._domain, list) and self._domain or []
+
+        wquery = obj._where_calc(cr, user, domain, context=context)
         obj._apply_ir_rules(cr, user, wquery, 'read', context=context)
         from_c, where_c, where_params = wquery.get_sql()
         if where_c:
@@ -599,9 +638,12 @@ class many2many(_column):
             elif act[0] == 3:
                 cr.execute('delete from '+self._rel+' where ' + self._id1 + '=%s and '+ self._id2 + '=%s', (id, act[1]))
             elif act[0] == 4:
-                cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s,%s)', (id, act[1]))
+                # following queries are in the same transaction - so should be relatively safe
+                cr.execute('SELECT 1 FROM '+self._rel+' WHERE '+self._id1+' = %s and '+self._id2+' = %s', (id, act[1]))
+                if not cr.fetchone():
+                    cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s,%s)', (id, act[1]))
             elif act[0] == 5:
-                cr.execute('update '+self._rel+' set '+self._id2+'=null where '+self._id2+'=%s', (id,))
+                cr.execute('delete from '+self._rel+' where ' + self._id1 + ' = %s', (id,))
             elif act[0] == 6:
 
                 d1, d2,tables = obj.pool.get('ir.rule').domain_get(cr, user, obj._name, context=context)
@@ -657,6 +699,37 @@ def get_nice_size(a):
         size = 0
     return (x, tools.human_size(size))
 
+def sanitize_binary_value(dict_item):
+    # binary fields should be 7-bit ASCII base64-encoded data,
+    # but we do additional sanity checks to make sure the values
+    # are not something else that won't pass via xmlrpc
+    index, value = dict_item
+    if isinstance(value, (xmlrpclib.Binary, tuple, list, dict)):
+        # these builtin types are meant to pass untouched
+        return index, value
+
+    # For all other cases, handle the value as a binary string:
+    # it could be a 7-bit ASCII string (e.g base64 data), but also
+    # any 8-bit content from files, with byte values that cannot
+    # be passed inside XML!
+    # See for more info:
+    #  - http://bugs.python.org/issue10066
+    #  - http://www.w3.org/TR/2000/REC-xml-20001006#NT-Char
+    #
+    # One solution is to convert the byte-string to unicode,
+    # so it gets serialized as utf-8 encoded data (always valid XML)
+    # If invalid XML byte values were present, tools.ustr() uses
+    # the Latin-1 codec as fallback, which converts any 8-bit
+    # byte value, resulting in valid utf-8-encoded bytes
+    # in the end:
+    #  >>> unicode('\xe1','latin1').encode('utf8') == '\xc3\xa1'
+    # Note: when this happens, decoding on the other endpoint
+    # is not likely to produce the expected output, but this is
+    # just a safety mechanism (in these cases base64 data or
+    # xmlrpc.Binary values should be used instead)
+    return index, tools.ustr(value)
+
+
 # ---------------------------------------------------------
 # Function fields
 # ---------------------------------------------------------
@@ -712,6 +785,11 @@ class function(_column):
             self._symbol_f = boolean._symbol_f
             self._symbol_set = boolean._symbol_set
 
+        if type in ['integer','integer_big']:
+            self._symbol_c = integer._symbol_c
+            self._symbol_f = integer._symbol_f
+            self._symbol_set = integer._symbol_set
+
     def digits_change(self, cr):
         if self.digits_compute:
             t = self.digits_compute(cr)
@@ -726,9 +804,9 @@ class function(_column):
         return self._fnct_search(obj, cr, uid, obj, name, args, context=context)
 
     def get(self, cr, obj, ids, name, user=None, context=None, values=None):
-        if not context:
+        if context is None:
             context = {}
-        if not values:
+        if values is None:
             values = {}
         res = {}
         if self._method:
@@ -747,9 +825,13 @@ class function(_column):
                     if res[r] and res[r] in dict_names:
                         res[r] = (res[r], dict_names[res[r]])
 
-        if self._type == 'binary' and context.get('bin_size', False):
-            # convert the data returned by the function with the size of that data...
-            res = dict(map( get_nice_size, res.items()))
+        if self._type == 'binary':
+            if context.get('bin_size', False):
+                # client requests only the size of binary fields
+                res = dict(map(get_nice_size, res.items()))
+            else:
+                res = dict(map(sanitize_binary_value, res.items()))
+
         if self._type == "integer":
             for r in res.keys():
                 # Converting value into string so that it does not affect XML-RPC Limits
@@ -774,7 +856,7 @@ class function(_column):
 
 class related(function):
 
-    def _fnct_search(self, tobj, cr, uid, obj=None, name=None, domain=None, context={}):
+    def _fnct_search(self, tobj, cr, uid, obj=None, name=None, domain=None, context=None):
         self._field_get2(cr, uid, obj, context)
         i = len(self._arg)-1
         sarg = name
@@ -791,7 +873,7 @@ class related(function):
         return [(self._arg[0], 'in', sarg)]
 
     def _fnct_write(self,obj,cr, uid, ids, field_name, values, args, context=None):
-        self._field_get2(cr, uid, obj, context)
+        self._field_get2(cr, uid, obj, context=context)
         if type(ids) != type([]):
             ids=[ids]
         objlst = obj.browse(cr, uid, ids)
@@ -872,7 +954,7 @@ class related(function):
             # TODO: improve here to change self.store = {...} according to related objects
             pass
 
-    def _field_get2(self, cr, uid, obj, context={}):
+    def _field_get2(self, cr, uid, obj, context=None):
         if self._relations:
             return
         obj_name = obj._name
@@ -892,10 +974,10 @@ class related(function):
 # ---------------------------------------------------------
 
 class dummy(function):
-    def _fnct_search(self, tobj, cr, uid, obj=None, name=None, domain=None, context={}):
+    def _fnct_search(self, tobj, cr, uid, obj=None, name=None, domain=None, context=None):
         return []
 
-    def _fnct_write(self,obj,cr, uid, ids, field_name, values, args, context=None):
+    def _fnct_write(self, obj, cr, uid, ids, field_name, values, args, context=None):
         return False
 
     def _fnct_read(self, obj, cr, uid, ids, field_name, args, context=None):
@@ -961,8 +1043,14 @@ class property(function):
             cr.execute('DELETE FROM ir_property WHERE id IN %s', (tuple(nids),))
 
         default_val = self._get_default(obj, cr, uid, prop_name, context)
-
-        if id_val is not default_val:
+        property_create = False
+        if isinstance(default_val, osv.orm.browse_record):
+            if default_val.id != id_val:
+                property_create = True
+        elif default_val != id_val:
+            property_create = True
+
+        if property_create:
             def_id = self._field_get(cr, uid, obj._name, prop_name)
             company = obj.pool.get('res.company')
             cid = company._company_default_get(cr, uid, obj._name, def_id,
@@ -997,11 +1085,16 @@ class property(function):
             value = properties.get_by_record(cr, uid, prop, context=context)
             res[prop.res_id.id][prop.fields_id.name] = value or False
             if value and (prop.type == 'many2one'):
-                replaces.setdefault(value._name, {})
-                replaces[value._name][value.id] = True
+                record_exists = obj.pool.get(value._name).exists(cr, uid, value.id)
+                if record_exists:
+                    replaces.setdefault(value._name, {})
+                    replaces[value._name][value.id] = True
+                else:
+                    res[prop.res_id.id][prop.fields_id.name] = False
 
         for rep in replaces:
-            replaces[rep] = dict(obj.pool.get(rep).name_get(cr, uid, replaces[rep].keys(), context=context))
+            nids = obj.pool.get(rep).search(cr, uid, [('id','in',replaces[rep].keys())], context=context)
+            replaces[rep] = dict(obj.pool.get(rep).name_get(cr, uid, nids, context=context))
 
         for prop in prop_name:
             for id in ids:
@@ -1030,5 +1123,27 @@ class property(function):
         self.field_id = {}
 
 
+class column_info(object):
+    """Struct containing details about an osv column, either one local to
+       its model, or one inherited via _inherits.
+
+       :attr name: name of the column
+       :attr column: column instance, subclass of osv.fields._column
+       :attr parent_model: if the column is inherited, name of the model
+                           that contains it, None for local columns.
+       :attr parent_column: the name of the column containing the m2o
+                            relationship to the parent model that contains
+                            this column, None for local columns.
+       :attr original_parent: if the column is inherited, name of the original
+                            parent model that contains it i.e in case of multilevel
+                            inheritence, None for local columns.
+    """
+    def __init__(self, name, column, parent_model=None, parent_column=None, original_parent=None):
+        self.name = name
+        self.column = column
+        self.parent_model = parent_model
+        self.parent_column = parent_column
+        self.original_parent = original_parent
+
 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: