Merge branch 'master' of openobject-server into mdv-gpl3-py26
[odoo/odoo.git] / bin / addons / base / ir / ir_values.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution   
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
6 #    $Id$
7 #
8 #    This program is free software: you can redistribute it and/or modify
9 #    it under the terms of the GNU General Public License as published by
10 #    the Free Software Foundation, either version 3 of the License, or
11 #    (at your option) any later version.
12 #
13 #    This program is distributed in the hope that it will be useful,
14 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #    GNU General Public License for more details.
17 #
18 #    You should have received a copy of the GNU General Public License
19 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 #
21 ##############################################################################
22
23 from osv import osv,fields
24 import pickle
25 from tools.translate import _
26
27 class ir_values(osv.osv):
28     _name = 'ir.values'
29
30     def _value_unpickle(self, cursor, user, ids, name, arg, context=None):
31         res = {}
32         for report in self.browse(cursor, user, ids, context=context):
33             value = report[name[:-9]]
34             if not report.object and value:
35                 try:
36                     value = str(pickle.loads(value))
37                 except:
38                     pass
39             res[report.id] = value
40         return res
41
42     def _value_pickle(self, cursor, user, id, name, value, arg, context=None):
43         if context is None:
44             context = {}
45         ctx = context.copy()
46         if self.CONCURRENCY_CHECK_FIELD in ctx:
47             del ctx[self.CONCURRENCY_CHECK_FIELD]
48         if not self.browse(cursor, user, id, context=context).object:
49             value = pickle.dumps(eval(value))
50         self.write(cursor, user, id, {name[:-9]: value}, context=ctx)
51
52     def onchange_object_id(self, cr, uid, ids, object_id, context={}):
53         if not object_id: return {}
54         act = self.pool.get('ir.model').browse(cr, uid, object_id, context=context)
55         return {
56                 'value': {'model': act.model}
57         }
58
59     def onchange_action_id(self, cr, uid, ids, action_id, context={}):
60         if not action_id: return {}
61         act = self.pool.get('ir.actions.actions').browse(cr, uid, action_id, context=context)
62         return {
63                 'value': {'value_unpickle': act.type+','+str(act.id)}
64         }
65
66     _columns = {
67         'name': fields.char('Name', size=128),
68         'model_id': fields.many2one('ir.model', 'Object', size=128,
69             help="This field is not used, it only helps you to select a good model."),
70         'model': fields.char('Object Name', size=128),
71         'action_id': fields.many2one('ir.actions.actions', 'Action',
72             help="This field is not used, it only helps you to select the right action."),
73         'value': fields.text('Value'),
74         'value_unpickle': fields.function(_value_unpickle, fnct_inv=_value_pickle,
75             method=True, type='text', string='Value'),
76         'object': fields.boolean('Is Object'),
77         'key': fields.selection([('action','Action'),('default','Default')], 'Type', size=128),
78         'key2': fields.char('Event Type', size=256,
79             help="The kind of action or button in the client side that will trigger the action."),
80         'meta': fields.text('Meta Datas'),
81         'meta_unpickle': fields.function(_value_unpickle, fnct_inv=_value_pickle,
82             method=True, type='text', string='Metadata'),
83         'res_id': fields.integer('Object ID', help="Keep 0 if the action must appear on all resources."),
84         'user_id': fields.many2one('res.users', 'User', ondelete='cascade'),
85         'company_id': fields.many2one('res.company', 'Company')
86     }
87     _defaults = {
88         'key': lambda *a: 'action',
89         'key2': lambda *a: 'tree_but_open',
90         'company_id': lambda *a: False
91     }
92
93     def _auto_init(self, cr, context={}):
94         super(ir_values, self)._auto_init(cr, context)
95         cr.execute('SELECT indexname FROM pg_indexes WHERE indexname = \'ir_values_key_model_key2_index\'')
96         if not cr.fetchone():
97             cr.execute('CREATE INDEX ir_values_key_model_key2_index ON ir_values (key, model, key2)')
98             cr.commit()
99
100     def set(self, cr, uid, key, key2, name, models, value, replace=True, isobject=False, meta=False, preserve_user=False, company=False):
101         if type(value)==type(u''):
102             value = value.encode('utf8')
103         if not isobject:
104             value = pickle.dumps(value)
105         if meta:
106             meta = pickle.dumps(meta)
107         ids_res = []
108         for model in models:
109             if type(model)==type([]) or type(model)==type(()):
110                 model,res_id = model
111             else:
112                 res_id=False
113             if replace:
114                 if key in ('meta', 'default'):
115                     ids = self.search(cr, uid, [
116                         ('key', '=', key),
117                         ('key2', '=', key2),
118                         ('name', '=', name),
119                         ('model', '=', model),
120                         ('res_id', '=', res_id),
121                         ('user_id', '=', preserve_user and uid)
122                         ])
123                 else:
124                     ids = self.search(cr, uid, [
125                         ('key', '=', key),
126                         ('key2', '=', key2),
127                         ('value', '=', value),
128                         ('model', '=', model),
129                         ('res_id', '=', res_id),
130                         ('user_id', '=', preserve_user and uid)
131                         ])
132                 self.unlink(cr, uid, ids)
133             vals = {
134                 'name': name,
135                 'value': value,
136                 'model': model,
137                 'object': isobject,
138                 'key': key,
139                 'key2': key2 and key2[:200],
140                 'meta': meta,
141                 'user_id': preserve_user and uid,
142             }
143             if company:
144                 cid = self.pool.get('res.users').browse(cr, uid, uid, context={}).company_id.id
145                 vals['company_id']=cid
146             if res_id:
147                 vals['res_id']= res_id
148             ids_res.append(self.create(cr, uid, vals))
149         return ids_res
150
151     def get(self, cr, uid, key, key2, models, meta=False, context={}, res_id_req=False, without_user=True, key2_req=True):
152         result = []
153         for m in models:
154             if type(m)==type([]) or type(m)==type(()):
155                 m,res_id = m
156             else:
157                 res_id=False
158
159             where1 = ['key=%s','model=%s']
160             where2 = [key,str(m)]
161             where_opt = []
162             if key2:
163                 where1.append('key2=%s')
164                 where2.append(key2[:200])
165             else:
166                 dest = where1
167                 if not key2_req or meta:
168                     dest=where_opt
169                 dest.append('key2 is null')
170
171             if res_id_req and (models[-1][0]==m):
172                 if res_id:
173                     where1.append('res_id=%d' % (res_id,))
174                 else:
175                     where1.append('(res_id is NULL)')
176             elif res_id:
177                 if (models[-1][0]==m):
178                     where1.append('(res_id=%d or (res_id is null))' % (res_id,))
179                     where_opt.append('res_id=%d' % (res_id,))
180                 else:
181                     where1.append('res_id=%d' % (res_id,))
182
183 #           if not without_user:
184             where_opt.append('user_id=%d' % (uid,))
185
186             result = []
187             ok = True
188             result_ids = {}
189             while ok:
190                 if not where_opt:
191                     cr.execute('select id,name,value,object,meta, key from ir_values where ' +\
192                             ' and '.join(where1)+' and user_id is null', where2)
193                 else:
194                     cr.execute('select id,name,value,object,meta, key from ir_values where ' +\
195                             ' and '.join(where1+where_opt), where2)
196                 for rec in cr.fetchall():
197                     if rec[0] in result_ids:
198                         continue
199                     result.append(rec)
200                     result_ids[rec[0]] = True
201                 if len(where_opt):
202                     where_opt.pop()
203                 else:
204                     ok = False
205
206             if result:
207                 break
208
209         if not result:
210             return []
211
212         def _result_get(x, keys):
213             if x[1] in keys:
214                 return False
215             keys.append(x[1])
216             if x[3]:
217                 model,id = x[2].split(',')
218                 id = int(id)
219                 fields = self.pool.get(model).fields_get_keys(cr, uid)
220                 pos = 0
221                 while pos<len(fields):
222                     if fields[pos] in ('report_sxw_content', 'report_rml_content',
223                         'report_sxw', 'report_rml', 'report_sxw_content_data',
224                         'report_rml_content_data'):
225                         del fields[pos]
226                     else:
227                         pos+=1
228                 datas = self.pool.get(model).read(cr, uid, [id], fields, context)
229                 datas= datas and datas[0] or None
230                 if not datas:
231                     #ir_del(cr, uid, x[0])
232                     return False
233             else:
234                 datas = pickle.loads(str(x[2]))
235             if meta:
236                 meta2 = pickle.loads(x[4])
237                 return (x[0],x[1],datas,meta2)
238             return (x[0],x[1],datas)
239         keys = []
240         res = filter(bool, map(lambda x: _result_get(x, keys), list(result)))
241         res2 = res[:]
242         for r in res:
243             if type(r[2])==type({}) and 'type' in r[2]:
244                 if r[2]['type'] in ('ir.actions.report.xml','ir.actions.act_window','ir.actions.wizard'):
245                     if r[2].has_key('groups_id'):
246                         groups = r[2]['groups_id']
247                         if len(groups) > 0:
248                             group_ids = ','.join([ str(x) for x in r[2]['groups_id']])
249                             cr.execute("select count(*) from res_groups_users_rel where gid in (%s) and uid='%s'" % (group_ids, uid))
250                             gr_ids = cr.fetchall()
251                             if not gr_ids[0][0] > 0:
252                                 res2.remove(r)
253                             if r[1]=='Menuitem' and not res2:
254                                   raise osv.except_osv('Error !','You do not have the permission to perform this operation !!!')
255     #                else:
256     #                    #raise osv.except_osv('Error !','You have not permission to perform operation !!!')
257     #                    res2.remove(r)
258         return res2
259 ir_values()
260
261
262
263 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
264