[IMP] removed the possible SQL injection server.
[odoo/odoo.git] / bin / addons / base / ir / ir_values.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 from osv import osv,fields
23 from osv.orm import except_orm
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(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.selection([('client_action_multi', 'client_action_multi'),
79                                    ('client_action_relate', 'client_action_relate'),
80                                    ('tree_but_open', 'tree_but_open'),
81                                    ('tree_but_action', 'tree_but_action'),
82                                    ('client_print_multi', 'client_print_multi')],
83                                   'Event Type',
84                                   help="The kind of action or button in the client side that will trigger the action."),
85         'meta': fields.text('Meta Datas'),
86         'meta_unpickle': fields.function(_value_unpickle, fnct_inv=_value_pickle,
87             method=True, type='text', string='Metadata'),
88         'res_id': fields.integer('Object ID', help="Keep 0 if the action must appear on all resources."),
89         'user_id': fields.many2one('res.users', 'User', ondelete='cascade'),
90         'company_id': fields.many2one('res.company', 'Company')
91     }
92     _defaults = {
93         'key': lambda *a: 'action',
94         'key2': lambda *a: 'tree_but_open',
95         'company_id': lambda *a: False
96     }
97
98     def _auto_init(self, cr, context={}):
99         super(ir_values, self)._auto_init(cr, context)
100         cr.execute('SELECT indexname FROM pg_indexes WHERE indexname = \'ir_values_key_model_key2_index\'')
101         if not cr.fetchone():
102             cr.execute('CREATE INDEX ir_values_key_model_key2_index ON ir_values (key, model, key2)')
103             cr.commit()
104
105     def set(self, cr, uid, key, key2, name, models, value, replace=True, isobject=False, meta=False, preserve_user=False, company=False):
106         if type(value)==type(u''):
107             value = value.encode('utf8')
108         if not isobject:
109             value = pickle.dumps(value)
110         if meta:
111             meta = pickle.dumps(meta)
112         ids_res = []
113         for model in models:
114             if type(model)==type([]) or type(model)==type(()):
115                 model,res_id = model
116             else:
117                 res_id=False
118             if replace:
119                 if key in ('meta', 'default'):
120                     ids = self.search(cr, uid, [
121                         ('key', '=', key),
122                         ('key2', '=', key2),
123                         ('name', '=', name),
124                         ('model', '=', model),
125                         ('res_id', '=', res_id),
126                         ('user_id', '=', preserve_user and uid)
127                         ])
128                 else:
129                     ids = self.search(cr, uid, [
130                         ('key', '=', key),
131                         ('key2', '=', key2),
132                         ('value', '=', value),
133                         ('model', '=', model),
134                         ('res_id', '=', res_id),
135                         ('user_id', '=', preserve_user and uid)
136                         ])
137                 self.unlink(cr, uid, ids)
138             vals = {
139                 'name': name,
140                 'value': value,
141                 'model': model,
142                 'object': isobject,
143                 'key': key,
144                 'key2': key2 and key2[:200],
145                 'meta': meta,
146                 'user_id': preserve_user and uid,
147             }
148             if company:
149                 cid = self.pool.get('res.users').browse(cr, uid, uid, context={}).company_id.id
150                 vals['company_id']=cid
151             if res_id:
152                 vals['res_id']= res_id
153             ids_res.append(self.create(cr, uid, vals))
154         return ids_res
155
156     def get(self, cr, uid, key, key2, models, meta=False, context={}, res_id_req=False, without_user=True, key2_req=True):
157         result = []
158         for m in models:
159             if type(m)==type([]) or type(m)==type(()):
160                 m,res_id = m
161             else:
162                 res_id=False
163
164             where = ['key=%s','model=%s']
165             params = [key, str(m)]
166             if key2:
167                 where.append('key2=%s')
168                 params.append(key2[:200])
169             else:
170                 if key2_req and not meta:
171                     where.append('key2 is null')
172             if res_id_req and (models[-1][0]==m):
173                 if res_id:
174                     where.append('res_id=%s')
175                     params.append(res_id)
176                 else:
177                     where.append('(res_id is NULL)')
178             elif res_id:
179                 if (models[-1][0]==m):
180                     where.append('(res_id=%s or (res_id is null))')
181                     params.append(res_id)
182                 else:
183                     where.append('res_id=%s')
184                     params.append(res_id)
185
186             where.append('(user_id=%s or (user_id IS NULL))')
187             params.append(uid)
188             clause = ' and '.join(where)
189             cr.execute('select id,name,value,object,meta, key from ir_values where ' + clause, params)
190             result = cr.fetchall()
191             if result:
192                 break
193
194         if not result:
195             return []
196
197         def _result_get(x, keys):
198             if x[1] in keys:
199                 return False
200             keys.append(x[1])
201             if x[3]:
202                 model,id = x[2].split(',')
203                 id = int(id)
204                 fields = self.pool.get(model).fields_get_keys(cr, uid)
205                 pos = 0
206                 while pos<len(fields):
207                     if fields[pos] in ('report_sxw_content', 'report_rml_content',
208                         'report_sxw', 'report_rml', 'report_sxw_content_data',
209                         'report_rml_content_data'):
210                         del fields[pos]
211                     else:
212                         pos+=1
213                 try:
214                     datas = self.pool.get(model).read(cr, uid, [id], fields, context)
215                 except except_orm, e:
216                     return False
217                 datas= datas and datas[0] or None
218                 if not datas:
219                     #ir_del(cr, uid, x[0])
220                     return False
221             else:
222                 datas = pickle.loads(str(x[2].encode('utf-8')))
223             if meta:
224                 meta2 = pickle.loads(x[4])
225                 return (x[0],x[1],datas,meta2)
226             return (x[0],x[1],datas)
227         keys = []
228         res = filter(bool, map(lambda x: _result_get(x, keys), list(result)))
229         res2 = res[:]
230         for r in res:
231             if type(r[2])==type({}) and 'type' in r[2]:
232                 groups = r[2].get('groups_id')
233                 if groups:
234                         cr.execute('SELECT COUNT(1) FROM res_groups_users_rel WHERE gid IN %s AND uid=%s',
235                                    (tuple(groups), uid)
236                                   )
237                         cnt = cr.fetchone()[0]
238                         if cnt:
239                             res2.remove(r)
240                         if r[1] == 'Menuitem' and not res2:
241                             raise osv.except_osv('Error !','You do not have the permission to perform this operation !!!')
242         return res2
243 ir_values()
244
245
246
247 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
248