def parameter(dico, resource, special=None): """ Convert value to a parameter for SOAP query @type dico: dict @param dico: Contain parameter starts with OERP_ @type resource: dict @param resource: Contain parameter starts with WIZARD_ @rtype: xmlstring @return: XML String representation """ res = '' for key in resource: _logger.debug(' PARAMETER -> RESOURCE: %s' % key) if key in 'xml_data': continue e = Element('parameter') e.set('name', 'OERP_%s' % key.upper()) e.text = ustr(resource[key]) res += tostring(e) + '\n' for key in dico: _logger.debug(' PARAMETER -> DICO: %s' % key) if key in 'params': continue val = dico[key] e = Element('parameter') e.set('name', 'WIZARD_%s' % key.upper()) if isinstance(val, list): if isinstance(val[0], tuple): e.text = ','.join(map(str, val[0][2])) else: e.text = ','.join(map(str, val)) else: e.text = val and ustr(val) or '' res += tostring(e) + '\n' if special is None: special = {} for key in special: _logger.debug(' PARAMETER -> SPECIAL: %s' % key) e = Element('parameter') e.set('name', key) e.text = ustr(special[key]) res += tostring(e) + '\n' res = entities(res) if resource.get('xml_data'): res += '<parameter class="java.lang.String" name="XML_DATA">' res += '<![CDATA["%s"]]></parameter>' % resource[ 'xml_data'] return res
def put(self, uri, data, content_type=None): """ put the object into the filesystem """ self.parent.log_message( 'Putting %s (%d), %s' % (misc.ustr(uri), data and len(data) or 0, content_type)) cr, uid, pool, dbname, uri2 = self.get_cr(uri) if not dbname: if cr: cr.close() raise DAV_Forbidden try: node = self.uri2object(cr, uid, pool, uri2[:]) except Exception: node = False objname = misc.ustr(uri2[-1]) ret = None if not node: dir_node = self.uri2object(cr, uid, pool, uri2[:-1]) if not dir_node: cr.close() raise DAV_NotFound('Parent folder not found') newchild = self._try_function(dir_node.create_child, (cr, objname, data), "create %s" % objname, cr=cr) if not newchild: cr.commit() cr.close() raise DAV_Error(400, "Failed to create resource") uparts = urlparse.urlparse(uri) fileloc = '/'.join(newchild.full_path()) if isinstance(fileloc, unicode): fileloc = fileloc.encode('utf-8') # the uri we get is a mangled one, where the davpath has been removed davpath = self.parent.get_davpath() surl = '%s://%s' % (uparts[0], uparts[1]) uloc = urllib.quote(fileloc) hurl = False if uri != ('/' + uloc) and uri != (surl + '/' + uloc): hurl = '%s%s/%s/%s' % (surl, davpath, dbname, uloc) etag = False try: etag = str(newchild.get_etag(cr)) except Exception, e: self.parent.log_error("Cannot get etag for node: %s" % e) ret = (str(hurl), etag)
def _signup_create_user(self, cr, uid, values, context=None): """ create a new user from the template user """ ir_config_parameter = self.pool.get('ir.config_parameter') ir_model_data = self.pool.get('ir.model.data') template_user_id = literal_eval(ir_config_parameter.get_param(cr, uid, 'auth_signup.template_user_id', 'False')) assert template_user_id and self.exists(cr, uid, template_user_id, context=context), 'Signup: invalid template user' # check that uninvited users may sign up if 'partner_id' not in values: if not literal_eval(ir_config_parameter.get_param(cr, uid, 'auth_signup.allow_uninvited', 'False')): raise SignupError('Signup is not allowed for uninvited users') assert values.get('login'), "Signup: no login given for new user" assert values.get('partner_id') or values.get('name'), "Signup: no name or partner given for new user" # create a copy of the template user (attached to a specific partner_id if given) #values['active'] = False context = dict(context or {}, no_reset_password=True) try: with cr.savepoint(): new_id = self.copy(cr, uid, template_user_id, values, context=context) self.write(cr,uid,[new_id],{'active':False},context=context) website_group_id = ir_model_data.xmlid_to_res_id(cr,uid,"res_partner_ept.website_user_group") if website_group_id: self.write(cr,uid,[new_id],{'groups_id':[(4,website_group_id)]}) self.create_partner(cr, uid, new_id, context=context) return new_id except Exception, e: # copy may failed if asked login is not available. raise SignupError(ustr(e))
def new_convert_xml_import( cr, module, xmlfile, idref=None, mode='init', noupdate=False, report=None): doc = etree.parse(xmlfile) xdoc = Document() rng_doc = minidom.parse( os.path.join(config['root_path'], 'import_xml.rng')) rng_element_tags = rng_doc.getElementsByTagName('rng:element') for rng_element in rng_element_tags: attributes = dict(rng_element.attributes) if attributes.get('name', False) \ and attributes['name'].value == 'menuitem': new_optional = xdoc.createElement('rng:optional') new_attribute = xdoc.createElement('rng:attribute') new_attribute.setAttribute('name', 'invisible_groups') new_optional.appendChild(new_attribute) rng_element.appendChild(new_optional) relaxng = etree.RelaxNG( etree.fromstring(rng_doc.toxml())) try: relaxng.assert_(doc) except Exception: _logger.error('The XML file does not fit the required schema !') _logger.error(misc.ustr(relaxng.error_log.last_error)) raise if idref is None: idref = {} obj = xml_import(cr, module, idref, mode, report=report, noupdate=noupdate) obj.parse(doc.getroot(), mode=mode) return True
def _process_text(self, txt): """Translate ``txt`` according to the language in the local context, replace dynamic ``[[expr]]`` with their real value, then escape the result for XML. :param str txt: original text to translate (must NOT be XML-escaped) :return: translated text, with dynamic expressions evaluated and with special XML characters escaped (``&,<,>``). """ if not self.localcontext: return str2xml(txt) if not txt: return '' result = '' sps = _regex.split(txt) while sps: # This is a simple text to translate to_translate = tools.ustr(sps.pop(0)) result += tools.ustr(self.localcontext.get('translate', lambda x:x)(to_translate)) if sps: txt = None try: expr = sps.pop(0) txt = eval(expr, self.localcontext) if txt and isinstance(txt, basestring): txt = tools.ustr(txt) except Exception: _logger.error("Failed to evaluate expression [[ %s ]] with context %r while rendering report, ignored.", expr, self.localcontext) if isinstance(txt, basestring): result += txt elif txt and (txt is not None) and (txt is not False): result += ustr(txt) return str2xml(result)
def _str_to_selection(self, cr, uid, model, column, value, context=None): selection = column.selection if not isinstance(selection, (tuple, list)): # FIXME: Don't pass context to avoid translations? # Or just copy context & remove lang? selection = selection(model, cr, uid, context=None) for item, label in selection: label = ustr(label) labels = self._get_translations(cr, uid, ('selection', 'model', 'code'), label, context=context) labels.append(label) if value == unicode(item) or value in labels: return item, [] raise ValueError( _(u"Value '%s' not found in selection field '%%(field)s'") % (value), { 'moreinfo': [ _label or unicode(item) for item, _label in selection if _label or item ] })
def _process_text(self, txt): """Translate ``txt`` according to the language in the local context, replace dynamic ``[[expr]]`` with their real value, then escape the result for XML. :param str txt: original text to translate (must NOT be XML-escaped) :return: translated text, with dynamic expressions evaluated and with special XML characters escaped (``&,<,>``). """ if not self.localcontext: return str2xml(txt) if not txt: return '' result = '' sps = _regex.split(txt) while sps: # This is a simple text to translate to_translate = tools.ustr(sps.pop(0)) result += tools.ustr( self.localcontext.get('translate', lambda x: x)(to_translate)) if sps: try: txt = None expr = sps.pop(0) txt = eval(expr, self.localcontext) if txt and isinstance(txt, basestring): txt = tools.ustr(txt) except Exception: pass if isinstance(txt, basestring): result += txt elif txt and (txt is not None) and (txt is not False): result += ustr(txt) return str2xml(result)
def _signup_create_user(self, cr, uid, values, context=None): """ create a new user from the template user """ ir_config_parameter = self.pool.get("ir.config_parameter") template_user_id = literal_eval(ir_config_parameter.get_param(cr, uid, "auth_signup.template_user_id", "False")) assert template_user_id and self.exists( cr, uid, template_user_id, context=context ), "Signup: invalid template user" # check that uninvited users may sign up if "partner_id" not in values: if not literal_eval(ir_config_parameter.get_param(cr, uid, "auth_signup.allow_uninvited", "False")): raise SignupError("Signup is not allowed for uninvited users") assert values.get("login"), "Signup: no login given for new user" assert values.get("partner_id") or values.get("name"), "Signup: no name or partner given for new user" # create a copy of the template user (attached to a specific partner_id if given) values["active"] = True context = dict(context or {}, no_reset_password=True) try: with cr.savepoint(): return self.copy(cr, uid, template_user_id, values, context=context) except Exception, e: # copy may failed if asked login is not available. raise SignupError(ustr(e))
def simple_vat_check(self, cr, uid, country_code, vat_number, context=None): ''' Check the VAT number depending of the country. http://sima-pc.com/nif.php ''' if not ustr(country_code).encode('utf-8').isalpha(): return False check_func_name = 'check_vat_' + country_code check_func = getattr(self, check_func_name, None) or \ getattr(vatnumber, check_func_name, None) if not check_func: # No VAT validation available, default to check that the country code exists if country_code.upper() == 'EU': # Foreign companies that trade with non-enterprises in the EU # may have a VATIN starting with "EU" instead of a country code. return True res_country = self.pool.get('res.country') return bool( res_country.search(cr, uid, [('code', '=ilike', country_code)], context=context)) return check_func(vat_number)
def _signup_create_user(self, cr, uid, values, context=None): """ create a new user from the template user """ ir_config_parameter = self.pool.get('ir.config_parameter') template_user_id = literal_eval( ir_config_parameter.get_param(cr, uid, 'auth_signup.template_user_id', 'False')) assert template_user_id and self.exists( cr, uid, template_user_id, context=context), 'Signup: invalid template user' # check that uninvited users may sign up if 'partner_id' not in values: if not literal_eval( ir_config_parameter.get_param( cr, uid, 'auth_signup.allow_uninvited', 'False')): raise SignupError('Signup is not allowed for uninvited users') assert values.get('login'), "Signup: no login given for new user" assert values.get('partner_id') or values.get( 'name'), "Signup: no name or partner given for new user" # create a copy of the template user (attached to a specific partner_id if given) values['active'] = True context = dict(context or {}, no_reset_password=True) try: with cr.savepoint(): return self.copy(cr, uid, template_user_id, values, context=context) except Exception, e: # copy may failed if asked login is not available. raise SignupError(ustr(e))
def convert_xml_import(cr, module, xmlfile, idref=None, mode='init', noupdate=False, report=None): ''' Copy of openerp.tools.convert_xml_import save for the xml transformation part ''' doc = etree.parse(xmlfile) #local change relaxng = etree.parse(os.path.join(config['root_path'],'import_xml.rng' )) for override in overrides: _logger.debug('applying override %s' % str(overrides)) transformation = etree.XSLT(etree.parse(tools.file_open(override))) relaxng = transformation(relaxng) _logger.debug('succeeded') try: relaxng = etree.RelaxNG(relaxng) #/local change relaxng.assert_(doc) except Exception: _logger.error('The XML file does not fit the required schema !') _logger.error(misc.ustr(relaxng.error_log.last_error)) raise if idref is None: idref={} obj = xml_import(cr, module, idref, mode, report=report, noupdate=noupdate) obj.parse(doc.getroot()) return True
def parameter_dict(dico, resource, special=None): """ Convert value to a parameter for SOAP query @type dico: dict @param dico: Contain parameter starts with OERP_ @type resource: dict @param resource: Contain parameter starts with WIZARD_ @rtype: dict @return: All keys in a dict """ res = {} for key in resource: _logger.debug(' PARAMETER -> RESOURCE: %s' % key) if key in 'xml_data': continue res['OERP_%s' % key.upper()] = ustr(resource[key]) for key in dico: _logger.debug(' PARAMETER -> DICO: %s' % key) if key in 'params': continue val = dico[key] if isinstance(val, list): if isinstance(val[0], tuple): res['WIZARD_%s' % key.upper()] = ','.join(map(str, val[0][2])) else: res['WIZARD_%s' % key.upper()] = ','.join(map(str, val)) else: res['WIZARD_%s' % key.upper()] = val and ustr(val) or '' # Duplicate WIZARD parameters with prefix OERP # Backward compatibility if isinstance(val, list): if isinstance(val[0], tuple): res['OERP_%s' % key.upper()] = ','.join(map(str, val[0][2])) else: res['OERP_%s' % key.upper()] = ','.join(map(str, val)) else: res['OERP_%s' % key.upper()] = val and ustr(val) or '' for key in special: _logger.debug(' PARAMETER -> SPECIAL: %s' % key) res[key] = ustr(special[key]) return res
def put(self, uri, data, content_type=None): """ put the object into the filesystem """ self.parent.log_message('Putting %s (%d), %s'%( misc.ustr(uri), data and len(data) or 0, content_type)) cr, uid, pool,dbname, uri2 = self.get_cr(uri) if not dbname: if cr: cr.close() raise DAV_Forbidden try: node = self.uri2object(cr, uid, pool, uri2[:]) except Exception: node = False objname = misc.ustr(uri2[-1]) ret = None if not node: dir_node = self.uri2object(cr, uid, pool, uri2[:-1]) if not dir_node: cr.close() raise DAV_NotFound('Parent folder not found') newchild = self._try_function(dir_node.create_child, (cr, objname, data), "create %s" % objname, cr=cr) if not newchild: cr.commit() cr.close() raise DAV_Error(400, "Failed to create resource") uparts=urlparse.urlparse(uri) fileloc = '/'.join(newchild.full_path()) if isinstance(fileloc, unicode): fileloc = fileloc.encode('utf-8') # the uri we get is a mangled one, where the davpath has been removed davpath = self.parent.get_davpath() surl = '%s://%s' % (uparts[0], uparts[1]) uloc = urllib.quote(fileloc) hurl = False if uri != ('/'+uloc) and uri != (surl + '/' + uloc): hurl = '%s%s/%s/%s' %(surl, davpath, dbname, uloc) etag = False try: etag = str(newchild.get_etag(cr)) except Exception, e: self.parent.log_error("Cannot get etag for node: %s" % e) ret = (str(hurl), etag)
def lock(self, uri, lock_data): """ Lock (may create) resource. Data is a dict, may contain: depth, token, refresh, lockscope, locktype, owner """ cr, uid, pool, dbname, uri2 = self.get_cr(uri) created = False if not dbname: raise DAV_Error, 409 try: node = self.uri2object(cr, uid, pool, uri2[:]) except Exception: node = False objname = misc.ustr(uri2[-1]) if not node: dir_node = self.uri2object(cr, uid, pool, uri2[:-1]) if not dir_node: raise DAV_NotFound('Parent folder not found.') # We create a new node (file) but with empty data=None, # as in RFC4918 p. 9.10.4 node = self._try_function(dir_node.create_child, (cr, objname, None), "create %s" % objname, cr=cr) if not node: cr.commit() raise DAV_Error(400, "Failed to create resource.") created = True try: node_fn = node.dav_lock except AttributeError: # perhaps the node doesn't support locks raise DAV_Error(400, 'No locks for this resource.') # Obtain the lock on the node lres, pid, token = self._try_function(node_fn, (cr, lock_data), "lock %s" % objname, cr=cr) if not lres: cr.commit() raise DAV_Error(423, "Resource already locked.") assert isinstance(lres, list), 'lres: %s' % repr(lres) try: data = mk_lock_response(self, uri, lres) cr.commit() except Exception: raise return created, data, token
def _signup_create_user(self, cr, uid, values, context=None): """ create a new user from the template user """ ir_config_parameter = self.pool.get('ir.config_parameter') template_user_id = literal_eval(ir_config_parameter.get_param( cr, uid, 'auth_signup.template_user_id', 'False')) assert template_user_id and self.exists( cr, uid, template_user_id, context=context), 'Signup: invalid template user' # check that uninvited users may sign up if 'partner_id' not in values: if not literal_eval(ir_config_parameter.get_param(cr, uid, 'auth_signup.allow_uninvited', 'False')): raise SignupError('Signup is not allowed for uninvited users') assert values.get('login'), "Signup: no login given for new user" assert values.get('partner_id') or values.get( 'name'), "Signup: no name or partner given for new user" values['active'] = True context = dict(context or {}, no_reset_password=True) values2 = dict() if values.get('l10n_mx_street3', False): values2['l10n_mx_street3'] = values['l10n_mx_street3'] del values['l10n_mx_street3'] if values.get('l10n_mx_street4', False): values2['l10n_mx_street4'] = values['l10n_mx_street4'] del values['l10n_mx_street4'] if values.get('zip_sat_id', False): values2['zip_sat_id'] = values['zip_sat_id'] del values['zip_sat_id'] if values.get('township_sat_id', False): values2['township_sat_id'] = values['township_sat_id'] del values['township_sat_id'] if values.get('locality_sat_id', False): values2['locality_sat_id'] = values['locality_sat_id'] del values['locality_sat_id'] try: with cr.savepoint(): new_user_id = self.copy( cr, uid, template_user_id, values, context=context) try: self.write(cr, uid, new_user_id, values2, context=context) except Exception: pass return new_user_id except Exception, e: # copy may failed if asked login is not available. raise SignupError(ustr(e))
def _index(self, cr, uid, bin_data, datas_fname, file_type): """ compute the index content of the given filename, or binary data. This is a python implementation of the unix command 'strings'. :param bin_data : datas in binary form :return index_content : string containing all the printable character of the binary data """ index_content = False if file_type: index_content = file_type.split("/")[0] if index_content == "text": # compute index_content only for text type words = re.findall("[^\x00-\x1F\x7F-\xFF]{4,}", bin_data) index_content = ustr("\n".join(words)) return index_content
def _index(self, cr, uid, bin_data, datas_fname, file_type): """ compute the index content of the given filename, or binary data. This is a python implementation of the unix command 'strings'. :param bin_data : datas in binary form :return index_content : string containing all the printable character of the binary data """ index_content = False if file_type: index_content = file_type.split('/')[0] if index_content == 'text': # compute index_content only for text type words = re.findall("[^\x00-\x1F\x7F-\xFF]{4,}", bin_data) index_content = ustr("\n".join(words)) return index_content
def force_xml_import(cr, xmlfile): """ Import a XML file like if all nodes have a ``noupdate="0"``""" doc = etree.parse(xmlfile) rng_path = os.path.join(config['root_path'], 'import_xml.rng') relaxng = etree.RelaxNG(etree.parse(rng_path)) try: relaxng.assert_(doc) except AssertionError: _logger.error('The XML file does not fit the required schema') _logger.error(misc.ustr(relaxng.error_log.last_error)) raise exceptions.Warning(_('The banks file cannot be read.')) obj = ForceXMLImport(cr, MODULE, {}, 'update') obj.parse(doc.getroot(), mode='update')
def simple_vat_check(self, cr, uid, country_code, vat_number, context=None): ''' Check the VAT number depending of the country. http://sima-pc.com/nif.php ''' if not ustr(country_code).encode('utf-8').isalpha(): return False check_func_name = 'check_vat_' + country_code check_func = getattr(self, check_func_name, None) or \ getattr(vatnumber, check_func_name, None) if not check_func: # No VAT validation available, default to check that the country code exists res_country = self.pool.get('res.country') return bool(res_country.search(cr, uid, [('code', '=ilike', country_code)], context=context)) return check_func(vat_number)
def check_vat(self, cr, uid, ids, context=None): res = super(res_partner, self).check_vat(cr, uid, ids, context=context) valid = 0 vat_country = False vat_number = False if context: valid = context.get('default_vat_subjected') if valid != 1: for partner in self.browse(cr, uid, ids, context=context): if not partner.vat: continue vat_country, vat_number = self._split_vat(partner.vat) if not ustr(vat_country).encode('utf-8').isalpha(): res = True return res
def check_vat(self, cr, uid, ids, context=None): res = super(res_partner, self).check_vat(cr, uid, ids, context=context) valid=0 vat_country=False vat_number=False if context: valid=context.get('default_vat_subjected') if valid!=1: for partner in self.browse(cr, uid, ids, context=context): if not partner.vat: continue vat_country, vat_number = self._split_vat(partner.vat) if not ustr(vat_country).encode('utf-8').isalpha(): res=True return res
def do_signup(self, qcontext): values = dict((key, qcontext.get(key)) for key in ('login', 'name', 'password')) assert any([k for k in values.values()]), "The form was not properly filled in." assert values.get('password') == qcontext.get('confirm_password'), "Passwords do not match; please retype them." if qcontext.get('token'): return super(AuthSignupHome, self).do_signup(qcontext) else: try: request.registry['cec.alumnos'].create(request.cr, openerp.SUPERUSER_ID, {'name': values.get('name'), 'email': values.get('login')}, {"password": values.get('password')}) request.cr.commit() except Exception, e: raise SignupError(ustr(e))
def import_help(self): for this in self: xmlfile = StringIO(base64.decodestring(this.source_file)) doc = etree.parse(xmlfile) relaxng = etree.RelaxNG( etree.parse( os.path.join(config['root_path'], 'import_xml.rng'))) try: relaxng.assert_(doc) except Exception: _logger.info('The XML file does not fit the required schema !', exc_info=True) _logger.info(misc.ustr(relaxng.error_log.last_error)) raise obj = XmlImport(self.env.cr, self._module, idref={}, mode='init', report=None, noupdate=False, xml_filename=None) obj.parse(doc.getroot(), mode='init')
def simple_vat_check(self, cr, uid, country_code, vat_number, context=None): """ Check the VAT number depending of the country. http://sima-pc.com/nif.php """ if not ustr(country_code).encode("utf-8").isalpha(): return False check_func_name = "check_vat_" + country_code check_func = getattr(self, check_func_name, None) or getattr(vatnumber, check_func_name, None) if not check_func: # No VAT validation available, default to check that the country code exists if country_code.upper() == "EU": # Foreign companies that trade with non-enterprises in the EU # may have a VATIN starting with "EU" instead of a country code. return True res_country = self.pool.get("res.country") return bool(res_country.search(cr, uid, [("code", "=ilike", country_code)], context=context)) return check_func(vat_number)
def apply_special_promotions(self, cr, uid, order_id, context=None): order = self.pool.get('sale.order').browse(cr, uid, order_id, context=context) active_promos = self.search(cr, uid, [('active', '=', True), ('special_promo', '=', True)], context=context) for promotion_rule in self.browse(cr, uid, active_promos, context): result = self.evaluate(cr, uid, promotion_rule, order, context) #If evaluates to true if result: try: self.execute_actions(cr, uid, promotion_rule, order_id, context) except Exception, e: raise orm.except_orm("Promotions", ustr(e)) #If stop further is true if promotion_rule.stop_further: return True
def get_graph_data(self, question, current_filters=None): '''Returns formatted data required by graph library on basis of filter''' # TODO refactor this terrible method and merge it with prepare_result_dict current_filters = current_filters if current_filters else [] survey_obj = request.registry['survey.survey'] result = [] if question.type == 'multiple_choice': result.append({ 'key': ustr(question.question), 'values': survey_obj.prepare_result(request.cr, request.uid, question, current_filters, context=request.context)['answers'] }) if question.type == 'simple_choice': result = survey_obj.prepare_result( request.cr, request.uid, question, current_filters, context=request.context)['answers'] if question.type == 'matrix': data = survey_obj.prepare_result(request.cr, request.uid, question, current_filters, context=request.context) for answer in data['answers']: values = [] for row in data['rows']: values.append({ 'text': data['rows'].get(row), 'count': data['result'].get((row, answer)) }) result.append({ 'key': data['answers'].get(answer), 'values': values }) return json.dumps(result)
def test_expr(expr, allowed_codes, mode="eval"): """test_expr(expression, allowed_codes[, mode]) -> code_object Test that the expression contains only the allowed opcodes. If the expression is valid and contains only allowed codes, return the compiled code object. Otherwise raise a ValueError, a Syntax Error or TypeError accordingly. """ try: if mode == 'eval': # eval() does not like leading/trailing whitespace expr = expr.strip() code_obj = compile(expr, "", mode) except (SyntaxError, TypeError, ValueError): raise except Exception, e: import sys exc_info = sys.exc_info() raise ValueError, '"%s" while compiling\n%r' % (ustr(e), expr), exc_info[2]
def _str_to_selection(self, cr, uid, model, column, value, context=None): selection = column.selection if not isinstance(selection, (tuple, list)): # FIXME: Don't pass context to avoid translations? # Or just copy context & remove lang? selection = selection(model, cr, uid, context=None) for item, label in selection: label = ustr(label) labels = self._get_translations( cr, uid, ('selection', 'model', 'code'), label, context=context) labels.append(label) if value == unicode(item) or value in labels: return item, [] raise ValueError( _(u"Value '%s' not found in selection field '%%(field)s'") % ( value), { 'moreinfo': [_label or unicode(item) for item, _label in selection if _label or item] })
def get_graph_data(self, question, current_filters=None): '''Returns formatted data required by graph library on basis of filter''' # TODO refactor this terrible method and merge it with prepare_result_dict current_filters = current_filters if current_filters else [] survey_obj = request.registry['survey.survey'] result = [] if question.type == 'multiple_choice': result.append({'key': ustr(question.question), 'values': survey_obj.prepare_result(request.cr, request.uid, question, current_filters, context=request.context)['answers'] }) if question.type == 'simple_choice': result = survey_obj.prepare_result(request.cr, request.uid, question, current_filters, context=request.context)['answers'] if question.type == 'matrix': data = survey_obj.prepare_result(request.cr, request.uid, question, current_filters, context=request.context) for answer in data['answers']: values = [] for row in data['rows']: values.append({'text': data['rows'].get(row), 'count': data['result'].get((row, answer))}) result.append({'key': data['answers'].get(answer), 'values': values}) return json.dumps(result)
def test_expr(expr, allowed_codes, mode="eval"): """test_expr(expression, allowed_codes[, mode]) -> code_object Test that the expression contains only the allowed opcodes. If the expression is valid and contains only allowed codes, return the compiled code object. Otherwise raise a ValueError, a Syntax Error or TypeError accordingly. """ try: if mode == "eval": # eval() does not like leading/trailing whitespace expr = expr.strip() code_obj = compile(expr, "", mode) except (SyntaxError, TypeError, ValueError): raise except Exception, e: import sys exc_info = sys.exc_info() raise ValueError, '"%s" while compiling\n%r' % (ustr(e), expr), exc_info[2]
def check_vat_mx(self, vat): ''' Mexican VAT verification Verificar RFC México ''' # we convert to 8-bit encoding, to help the regex parse only bytes vat = ustr(vat).encode('iso8859-1') m = self.__check_vat_mx_re.match(vat) if not m: #No valid format return False try: ano = int(m.group('ano')) if ano > 30: ano = 1900 + ano else: ano = 2000 + ano datetime.date(ano, int(m.group('mes')), int(m.group('dia'))) except ValueError: return False #Valid format and valid date return True
def _signup_create_user(self, cr, uid, values, context=None): print("Creating A New User") """ create a new user from the template user """ ir_config_parameter = self.pool.get('ir.config_parameter') # Differentiating Company For Multi company company_access_obj = self.pool.get('employee_access.detail') company_obj = self.pool.get('res.company') product_obj = self.pool.get('product.template') analytic_journal_obj = self.pool.get('account.analytic.journal') template_user_id = literal_eval( ir_config_parameter.get_param(cr, uid, 'auth_signup.template_user_id', 'False')) assert template_user_id and self.exists( cr, uid, template_user_id, context=context), 'Signup: invalid template user' # check that uninvited users may sign up if 'partner_id' not in values: if not literal_eval( ir_config_parameter.get_param( cr, uid, 'auth_signup.allow_uninvited', 'False')): raise SignupError('Signup is not allowed for uninvited users') assert values.get('login'), "Signup: no login given for new user" assert values.get('partner_id') or values.get( 'name'), "Signup: no name or partner given for new user" # create a copy of the template user (attached to a specific partner_id if given) values['active'] = True context = dict(context or {}, no_reset_password=True) # email_domain = values['login'].split('@') # company_search_new = company_obj.search(cr,uid,[('email_domain','=',email_domain[1])],context=context) company_search_domain = company_access_obj.search( cr, uid, [('email_login', '=', values['login'])], context=context) company_id = company_access_obj.browse( cr, uid, company_search_domain).company_id print("company_id"), company_id.id company_search_new = company_obj.search(cr, uid, [('id', '=', company_id.id)]) print("company_search"), company_search_new try: with cr.savepoint(): new_uuuu = self.copy(cr, uid, template_user_id, values, context=context) #return new_uuuu values_hr = { 'name': values['name'], 'work_email': values['email'], 'active': True, 'user_id': new_uuuu, } if company_search_new: values_hr.update({'company_id': company_search_new[0]}) company_browse = company_obj.browse( cr, uid, company_search_new) print("The company name is "), company_browse.name product_search = product_obj.search( cr, uid, [('company_id', '=', company_search_new[0]), ('type', '=', 'service'), ('use_for_timesheet', '=', True)]) if product_search: values_hr.update({'product_id': product_search[0]}) else: product_vals = { 'name': 'Services' + ' ' + company_browse.name, 'company_id': company_search_new[0], 'type': 'service', 'use_for_timesheet': True, } product_id = product_obj.create( cr, SUPERUSER_ID, product_vals) values_hr.update({'product_id': product_id}) print("The product id is :"), product_id analytic_journal_search = analytic_journal_obj.search( cr, uid, [('company_id', '=', company_search_new[0]), ('type', '=', 'general')]) if analytic_journal_search: values_hr.update( {'journal_id': analytic_journal_search[0]}) else: analytic_vals = { 'name': 'Timesheet Journal' + ' ' + company_browse.name, 'code': 'TJ', 'company_id': company_search_new[0], 'type': 'general', } analytic_id = analytic_journal_obj.create( cr, SUPERUSER_ID, analytic_vals) values_hr.update({'journal_id': analytic_id}) print("The journal_id id is :"), analytic_id default_hr = self.pool.get('hr.employee').create(cr, SUPERUSER_ID, values_hr, context=None) return default_hr # return new_uuuu except Exception, e: # copy may failed if asked login is not available. raise SignupError(ustr(e))
def parameter(dico, resource, special=None): """ Convert value to a parameter for SOAP query @type dico: dict @param dico: Contain parameter starts with OERP_ @type resource: dict @param resource: Contain parameter starts with WIZARD_ @rtype: xmlstring @return: XML String representation """ res = '' for key in resource: _logger.debug(' PARAMETER -> RESOURCE: %s' % key) if key in 'xml_data': continue e = Element('parameter') e.set('name', 'OERP_%s' % key.upper()) e.text = ustr(resource[key]) res += tostring(e) + '\n' for key in dico: _logger.debug(' PARAMETER -> DICO: %s' % key) if key in 'params': continue val = dico[key] e = Element('parameter') e.set('name', 'WIZARD_%s' % key.upper()) if isinstance(val, list): if isinstance(val[0], tuple): e.text = ','.join(map(str, val[0][2])) else: e.text = ','.join(map(str, val)) else: e.text = val and ustr(val) or '' res += tostring(e) + '\n' # Duplicate WIZARD parameters with prefix OERP e = Element('parameter') e.set('name', 'OERP_%s' % key.upper()) if isinstance(val, list): if isinstance(val[0], tuple): e.text = ','.join(map(str, val[0][2])) else: e.text = ','.join(map(str, val)) else: e.text = val and ustr(val) or '' res += tostring(e) + '\n' if special is None: special = {} for key in special: _logger.debug(' PARAMETER -> SPECIAL: %s' % key) e = Element('parameter') e.set('name', key) e.text = ustr(special[key]) res += tostring(e) + '\n' res = entities(res) if resource.get('xml_data'): res += '<parameter class="java.lang.String"' \ 'name="XML_DATA">' res += '<![CDATA["%s"]]></parameter>' % \ resource['xml_data'] return res
def _signup_create_user(self, cr, uid, values, context=None): print ("Creating A New User") """ create a new user from the template user """ ir_config_parameter = self.pool.get('ir.config_parameter') # Differentiating Company For Multi company company_access_obj=self.pool.get('employee_access.detail') company_obj=self.pool.get('res.company') product_obj = self.pool.get('product.template') analytic_journal_obj = self.pool.get('account.analytic.journal') template_user_id = literal_eval(ir_config_parameter.get_param(cr, uid, 'auth_signup.template_user_id', 'False')) assert template_user_id and self.exists(cr, uid, template_user_id, context=context), 'Signup: invalid template user' # check that uninvited users may sign up if 'partner_id' not in values: if not literal_eval(ir_config_parameter.get_param(cr, uid, 'auth_signup.allow_uninvited', 'False')): raise SignupError('Signup is not allowed for uninvited users') assert values.get('login'), "Signup: no login given for new user" assert values.get('partner_id') or values.get('name'), "Signup: no name or partner given for new user" # create a copy of the template user (attached to a specific partner_id if given) values['active'] = True context = dict(context or {}, no_reset_password=True) # email_domain = values['login'].split('@') # company_search_new = company_obj.search(cr,uid,[('email_domain','=',email_domain[1])],context=context) company_search_domain = company_access_obj.search(cr,uid,[('email_login','=',values['login'])],context=context) company_id=company_access_obj.browse(cr,uid,company_search_domain).company_id print ("company_id"),company_id.id company_search_new=company_obj.search(cr,uid,[('id','=',company_id.id)]) print ("company_search"),company_search_new try: with cr.savepoint(): new_uuuu=self.copy(cr, uid, template_user_id, values, context=context) #return new_uuuu values_hr = { 'name':values['name'], 'work_email':values['email'], 'active':True, 'user_id':new_uuuu, } if company_search_new: values_hr.update({'company_id':company_search_new[0]}) company_browse = company_obj.browse(cr,uid,company_search_new) print ("The company name is "),company_browse.name product_search = product_obj.search(cr,uid,[('company_id','=',company_search_new[0]), ('type','=','service'),('use_for_timesheet','=', True)]) if product_search: values_hr.update({'product_id':product_search[0]}) else: product_vals={ 'name': 'Services' + ' ' + company_browse.name, 'company_id': company_search_new[0], 'type': 'service', 'use_for_timesheet': True, } product_id=product_obj.create(cr,SUPERUSER_ID,product_vals) values_hr.update({'product_id':product_id}) print ("The product id is :"),product_id analytic_journal_search=analytic_journal_obj.search(cr,uid,[('company_id','=',company_search_new[0]),('type','=','general')]) if analytic_journal_search: values_hr.update({'journal_id':analytic_journal_search[0]}) else: analytic_vals={ 'name':'Timesheet Journal' + ' ' + company_browse.name, 'code':'TJ', 'company_id':company_search_new[0], 'type':'general', } analytic_id=analytic_journal_obj.create(cr,SUPERUSER_ID,analytic_vals) values_hr.update({'journal_id':analytic_id}) print ("The journal_id id is :"),analytic_id default_hr = self.pool.get('hr.employee').create(cr,SUPERUSER_ID,values_hr,context=None) return default_hr # return new_uuuu except Exception, e: # copy may failed if asked login is not available. raise SignupError(ustr(e))
def safe_eval(expr, globals_dict=None, locals_dict=None, mode="eval", nocopy=False, locals_builtins=False): """safe_eval(expression[, globals[, locals[, mode[, nocopy]]]]) -> result System-restricted Python expression evaluation Evaluates a string that contains an expression that mostly uses Python constants, arithmetic expressions and the objects directly provided in context. This can be used to e.g. evaluate an OpenERP domain expression from an untrusted source. :throws TypeError: If the expression provided is a code object :throws SyntaxError: If the expression provided is not valid Python :throws NameError: If the expression provided accesses forbidden names :throws ValueError: If the expression provided uses forbidden bytecode """ if isinstance(expr, CodeType): raise TypeError("safe_eval does not allow direct evaluation of code objects.") if globals_dict is None: globals_dict = {} # prevent altering the globals/locals from within the sandbox # by taking a copy. if not nocopy: # isinstance() does not work below, we want *exactly* the dict class if (globals_dict is not None and type(globals_dict) is not dict) \ or (locals_dict is not None and type(locals_dict) is not dict): _logger.warning( "Looks like you are trying to pass a dynamic environment, " "you should probably pass nocopy=True to safe_eval().") globals_dict = dict(globals_dict) if locals_dict is not None: locals_dict = dict(locals_dict) globals_dict.update( __builtins__={ '__import__': _import, 'True': True, 'False': False, 'None': None, 'str': str, 'unicode': unicode, 'bool': bool, 'int': int, 'float': float, 'long': long, 'enumerate': enumerate, 'dict': dict, 'list': list, 'tuple': tuple, 'map': map, 'abs': abs, 'min': min, 'max': max, 'sum': sum, 'reduce': reduce, 'filter': filter, 'round': round, 'len': len, 'repr': repr, 'set': set, 'all': all, 'any': any, 'ord': ord, 'chr': chr, 'cmp': cmp, 'divmod': divmod, 'isinstance': isinstance, 'range': range, 'xrange': xrange, 'zip': zip, 'Exception': Exception, } ) if locals_builtins: if locals_dict is None: locals_dict = {} locals_dict.update(globals_dict.get('__builtins__')) c = test_expr(expr, _SAFE_OPCODES, mode=mode) try: return eval(c, globals_dict, locals_dict) except openerp.osv.orm.except_orm: raise except openerp.exceptions.Warning: raise except openerp.exceptions.RedirectWarning: raise except openerp.exceptions.AccessDenied: raise except openerp.exceptions.AccessError: raise except OperationalError: # Do not hide PostgreSQL low-level exceptions, to let the auto-replay # of serialized transactions work its magic raise except Exception, e: import sys exc_info = sys.exc_info() raise ValueError, '"%s" while evaluating\n%r' % (ustr(e), expr), exc_info[2]
def text_get(node): return ''.join([ustr(n.text) for n in node])
def safe_eval(expr, globals_dict=None, locals_dict=None, mode="eval", nocopy=False, locals_builtins=False): """safe_eval(expression[, globals[, locals[, mode[, nocopy]]]]) -> result System-restricted Python expression evaluation Evaluates a string that contains an expression that mostly uses Python constants, arithmetic expressions and the objects directly provided in context. This can be used to e.g. evaluate an OpenERP domain expression from an untrusted source. :throws TypeError: If the expression provided is a code object :throws SyntaxError: If the expression provided is not valid Python :throws NameError: If the expression provided accesses forbidden names :throws ValueError: If the expression provided uses forbidden bytecode """ if isinstance(expr, CodeType): raise TypeError("safe_eval does not allow direct evaluation of code objects.") if globals_dict is None: globals_dict = {} # prevent altering the globals/locals from within the sandbox # by taking a copy. if not nocopy: # isinstance() does not work below, we want *exactly* the dict class if (globals_dict is not None and type(globals_dict) is not dict) or ( locals_dict is not None and type(locals_dict) is not dict ): _logger.warning( "Looks like you are trying to pass a dynamic environment, " "you should probably pass nocopy=True to safe_eval()." ) globals_dict = dict(globals_dict) if locals_dict is not None: locals_dict = dict(locals_dict) globals_dict.update( __builtins__={ "__import__": _import, "True": True, "False": False, "None": None, "str": str, "unicode": unicode, "globals": locals, "locals": locals, "bool": bool, "int": int, "float": float, "long": long, "enumerate": enumerate, "dict": dict, "list": list, "tuple": tuple, "map": map, "abs": abs, "min": min, "max": max, "sum": sum, "reduce": reduce, "filter": filter, "round": round, "len": len, "repr": repr, "set": set, "all": all, "any": any, "ord": ord, "chr": chr, "cmp": cmp, "divmod": divmod, "isinstance": isinstance, "range": range, "xrange": xrange, "zip": zip, } ) if locals_builtins: if locals_dict is None: locals_dict = {} locals_dict.update(globals_dict.get("__builtins__")) c = test_expr(expr, _SAFE_OPCODES, mode=mode) try: return eval(c, globals_dict, locals_dict) except openerp.osv.orm.except_orm: raise except openerp.exceptions.Warning: raise except openerp.exceptions.RedirectWarning: raise except openerp.exceptions.AccessDenied: raise except openerp.exceptions.AccessError: raise except Exception, e: import sys exc_info = sys.exc_info() raise ValueError, '"%s" while evaluating\n%r' % (ustr(e), expr), exc_info[2]
def _scenario_save(self, message, transition_type, scenario_id=None, step_id=None, current_object=None): """ Save the scenario on this terminal, handling transient errors by retrying the same step Return the action to the terminal """ self.ensure_one() result = ('M', ['TEST'], False) tries = 0 current_object = current_object or '' while True: try: result = self._do_scenario_save(message, transition_type, scenario_id=scenario_id, step_id=step_id, current_object=current_object) break except OperationalError as e: # Automatically retry the typical transaction serialization # errors self.env.cr.rollback() if e.pgcode not in PG_CONCURRENCY_ERRORS_TO_RETRY: logger.warning("[%s] OperationalError", self.code, exc_info=True) result = ('R', ['Please contact', 'your', 'administrator'], 0) break if tries >= MAX_TRIES_ON_CONCURRENCY_FAILURE: logger.warning( "[%s] Concurrent transaction - " "OperationalError %s, maximum number of tries reached", self.code, e.pgcode) result = ('E', [ ustr('Concurrent transaction - OperationalError ' '%s, maximum number of tries reached') % (e.pgcode) ], True) break wait_time = random.uniform(0.0, 2**tries) tries += 1 logger.info( "[%s] Concurrent transaction detected (%s), " "retrying %d/%d in %.04f sec...", self.code, e.pgcode, tries, MAX_TRIES_ON_CONCURRENCY_FAILURE, wait_time) time.sleep(wait_time) except (exceptions.except_orm, exceptions.Warning) as e: # ORM exception, display the error message and require the "go # back" action self.env.cr.rollback() logger.warning('[%s] OSV Exception:', self.code, exc_info=True) result = ('E', [e.name or '', '', e.value or ''], True) break except Exception as e: self.env.cr.rollback() logger.error('[%s] Exception: ', self.code, exc_info=True) result = ('R', ['Please contact', 'your', 'administrator'], 0) self.empty_scanner_values() break self.log('Return value : %r' % (result, )) # Manage automatic steps if result[0] == 'A': return self.scanner_call(self.code, 'action', message=result[2]) return result
def log(self, log_message): if self.log_enabled: logger.info('[%s] %s' % (self.code, ustr(log_message)))