diff --git a/cgi-bin/webnotes/auth.py b/cgi-bin/webnotes/auth.py index d15309020b..a3f04a1a1b 100644 --- a/cgi-bin/webnotes/auth.py +++ b/cgi-bin/webnotes/auth.py @@ -104,7 +104,7 @@ class HTTPRequest: else: db_name = getattr(webnotes.defs,'default_db_name','') - webnotes.conn = webnotes.db.Database(user = db_name,password = getattr(webnotes.defs,'db_password','')) + webnotes.conn = webnotes.db.Database(user = db_name,password = getattr(webnotes.defs,'db_password', '')) webnotes.ac_name = ac_name # ================================================================================= diff --git a/cgi-bin/webnotes/db.py b/cgi-bin/webnotes/db.py index 8d175e317e..45837a2051 100644 --- a/cgi-bin/webnotes/db.py +++ b/cgi-bin/webnotes/db.py @@ -26,7 +26,7 @@ class Database: self.transaction_writes = 0 self.testing_tables = [] - self.password = self.get_db_password(ac_name, password) + self.password = self.get_db_password(user, password) self.connect() if self.user != 'root': @@ -57,7 +57,9 @@ class Database: return '' def get_db_login(self, ac_name): - return getattr(defs,'db_name_map').get(ac_name, getattr(defs,'default_db_name')) + if hasattr(defs, 'db_name_map'): + return getattr(defs,'db_name_map').get(ac_name, getattr(defs,'default_db_name')) + else: return ac_name def connect(self): """ diff --git a/cgi-bin/webnotes/model/doclist.py b/cgi-bin/webnotes/model/doclist.py index c8df02660a..5e270a69cf 100644 --- a/cgi-bin/webnotes/model/doclist.py +++ b/cgi-bin/webnotes/model/doclist.py @@ -18,7 +18,7 @@ class DocList: self.to_docstatus = 0 if dt and dn: self.load_from_db(dt, dn) - + def load_from_db(self, dt, dn): """ Load doclist from dt @@ -34,15 +34,15 @@ class DocList: doclist = [doc,] for t in tablefields: doclist += getchildren(doc.name, t[0], t[1], dt, prefix=prefix) - + self.docs = docs - + def __iter__(self): """ Make this iterable """ return self.docs.__iter__() - + def from_compressed(self, data, docname): """ Expand called from client @@ -50,13 +50,13 @@ class DocList: from webnotes.model.utils import expand self.docs = expand(data) self.objectify(docname) - + def objectify(self, docname=None): """ Converts self.docs from a list of dicts to list of Documents """ from webnotes.model.doc import Document - + self.docs = [Document(fielddata=d) for d in self.docs] if not docname: self.doc, self.children = self.docs[0], self.docs[1:] @@ -69,21 +69,20 @@ class DocList: self.doc = d else: self.children.append(d) - # catch all if no self.doc if not self.doc: self.doc, self.children = self.docs[0], self.docs[1:] - + def make_obj(self): """ Create a DocType object """ if self.obj: return self.obj - + from webnotes.model.code import get_obj self.obj = get_obj(doc=self.doc, doclist=self.children) return self.obj - + def next(self): """ Next doc @@ -104,13 +103,13 @@ class DocList: if (not is_single(self.doc.doctype)) and (not cint(self.doc.fields.get('__islocal'))): tmp = webnotes.conn.sql(""" - SELECT modified FROM `tab%s` WHERE name="%s" for update""" + SELECT modified FROM `tab%s` WHERE name="%s" for update""" % (self.doc.doctype, self.doc.name)) if tmp and str(tmp[0][0]) != str(self.doc.modified): webnotes.msgprint(""" - Document has been modified after you have opened it. - To maintain the integrity of the data, you will not be able to save your changes. + Document has been modified after you have opened it. + To maintain the integrity of the data, you will not be able to save your changes. Please refresh this document. [%s/%s]""" % (tmp[0][0], self.doc.modified), raise_exception=1) def check_permission(self): @@ -119,7 +118,7 @@ class DocList: """ if not self.doc.check_perm(verbose=1): webnotes.msgprint("Not enough permission to save %s" % self.doc.doctype, raise_exception=1) - + def check_links(self): """ Checks integrity of links (throws exception if links are invalid) @@ -130,11 +129,11 @@ class DocList: ref[d.doctype] = d.make_link_list() err_list += d.validate_links(ref[d.doctype]) - + if err_list: - webnotes.msgprint("""[Link Validation] Could not find the following values: %s. + webnotes.msgprint("""[Link Validation] Could not find the following values: %s. Please correct and resave. Document Not Saved.""" % ', '.join(err_list), raise_exception=1) - + def update_timestamps_and_docstatus(self): """ Update owner, creation, modified_by, modified, docstatus @@ -142,17 +141,17 @@ class DocList: from webnotes.utils import now ts = now() user = webnotes.__dict__.get('session', {}).get('user') or 'Administrator' - + for d in self.docs: if self.doc.__islocal: d.owner = user d.creation = ts - + d.modified_by = user d.modified = ts if d.docstatus != 2: # don't update deleted d.docstatus = self.to_docstatus - + def prepare_for_save(self, check_links): """ Set owner, modified etc before saving @@ -175,7 +174,7 @@ class DocList: from webnotes.model.triggers import fire_event fire_event(self.doc, method) - + def save_main(self): """ Save the main doc @@ -184,7 +183,7 @@ class DocList: self.doc.save(cint(self.doc.__islocal)) except NameError, e: webnotes.msgprint('%s "%s" already exists' % (self.doc.doctype, self.doc.name)) - + # prompt if cancelled if webnotes.conn.get_value(self.doc.doctype, self.doc.name, 'docstatus')==2: webnotes.msgprint('[%s "%s" has been cancelled]' % (self.doc.doctype, self.doc.name)) @@ -197,7 +196,7 @@ class DocList: """ for d in self.children: deleted, local = d.fields.get('__deleted',0), d.fields.get('__islocal',0) - + if cint(local) and cint(deleted): pass @@ -206,7 +205,7 @@ class DocList: d.parent = self.doc.name # rename if reqd d.parenttype = self.doc.doctype - d.save(new = cint(local)) + d.save(new = cint(local)) def save(self, check_links=1): """ @@ -217,7 +216,7 @@ class DocList: self.save_main() self.save_children() self.run_method('on_update') - + def submit(self): """ Save & Submit - set docstatus = 1, run "on_submit" @@ -227,7 +226,7 @@ class DocList: self.to_docstatus = 1 self.save() self.run_method('on_submit') - + def cancel(self): """ Cancel - set docstatus 2, run "on_cancel" @@ -239,7 +238,7 @@ class DocList: self.save_main() self.save_children() self.run_method('on_cancel') - + def update_after_submit(self): """ Update after submit - some values changed after submit @@ -260,11 +259,11 @@ def getlist(doclist, parentfield): """ import webnotes.model.utils return webnotes.model.utils.getlist(doclist, parentfield) - + def copy_doclist(doclist, no_copy = []): """ Make a copy of the doclist """ import webnotes.model.utils return webnotes.model.utils.copy_doclist(doclist, no_copy) - + diff --git a/cgi-bin/webnotes/model/utils.py b/cgi-bin/webnotes/model/utils.py index 2d019273f1..b9892067d3 100644 --- a/cgi-bin/webnotes/model/utils.py +++ b/cgi-bin/webnotes/model/utils.py @@ -1,7 +1,7 @@ """ Model utilities, unclassified functions """ - + def expand(docs): """ Expand a doclist sent from the client side. (Internally used by the request handler) @@ -25,12 +25,12 @@ def compress(doclist): """ Compress a doclist before sending it to the client side. (Internally used by the request handler) - """ + """ if doclist and hasattr(doclist[0],'fields'): docs = [d.fields for d in doclist] else: docs = doclist - + kl, vl = {}, [] for d in docs: dt = d['doctype'] @@ -38,10 +38,10 @@ def compress(doclist): fl = d.keys() forbidden = ['server_code_compiled'] nl = ['doctype','localname','__oldparent','__unsaved'] - + # add client script for doctype, doctype due to ambiguity if dt=='DocType': nl.append('__client_script') - + for f in fl: if not (f in nl) and not (f in forbidden): nl.append(f) @@ -64,21 +64,24 @@ def compress(doclist): def getlist(doclist, field): """ Filter a list of records for a specific field from the full doclist - + Example:: - - # find all phone call details + + # find all phone call details dl = getlist(self.doclist, 'contact_updates') pl = [] for d in dl: if d.type=='Phone': pl.append(d) """ - + l = [] for d in doclist: if d.parent and (not d.parent.lower().startswith('old_parent:')) and d.parentfield == field: l.append(d) + + l.sort(lambda a, b: a.idx - b.idx) + return l # Copy doclist @@ -90,31 +93,31 @@ def copy_doclist(doclist, no_copy = []): Pass fields that are not to be copied in `no_copy` """ from webnotes.model.doc import Document - + cl = [] - + # main doc c = Document(fielddata = doclist[0].fields.copy()) - + # clear no_copy fields - for f in no_copy: + for f in no_copy: if c.fields.has_key(f): c.fields[f] = None - + c.name = None c.save(1) cl.append(c) - + # new parent name parent = c.name - + # children for d in doclist[1:]: c = Document(fielddata = d.fields.copy()) c.name = None - + # clear no_copy fields - for f in no_copy: + for f in no_copy: if c.fields.has_key(f): c.fields[f] = None @@ -138,18 +141,18 @@ def _make_html(doc, link_list): from webnotes.utils import cstr out = '' for k in doc.fields.keys(): - if k!='server_code_compiled': + if k!='server_code_compiled': v = cstr(doc.fields[k]) - + # link field if v and (k in link_list.keys()): dt = link_list[k] if type(dt)==str and dt.startswith('link:'): dt = dt[5:] - v = '%s' % (dt, v, v) - + v = '%s' % (dt, v, v) + out += '\t\n' % (cstr(k), v) - + out += '
%s%s
' return out @@ -159,13 +162,13 @@ def to_html(doclist): """ out = '' link_lists = {} - + for d in doclist: if not link_lists.get(d.doctype): link_lists[d.doctype] = d.make_link_list() out += _make_html(d, link_lists[d.doctype]) - + return out def commonify_doclist(doclist, with_comments=1): @@ -184,14 +187,14 @@ def commonify_doclist(doclist, with_comments=1): return c def strip_common(d): - for k in common_keys: + for k in common_keys: if k in d: del d[k] return d def make_common_dicts(doclist): - + common_dict = {} # one per doctype - + # make common dicts for all records for d in doclist: if not d['doctype'] in common_dict: @@ -206,15 +209,15 @@ def commonify_doclist(doclist, with_comments=1): common_dict = make_common_dicts(doclist) # make docs - final = [] + final = [] for d in doclist: f = strip_common(get_diff_dict(common_dict[d['doctype']], d)) f['doctype'] = d['doctype'] # keep doctype! - + # strip name for child records (only an auto generated number!) if f['doctype'] != doclist[0]['doctype']: del f['name'] - + if with_comments: f['##comment'] = d['doctype'] + ('name' in f and (', ' + f['name']) or '') final.append(f) @@ -226,10 +229,10 @@ def commonify_doclist(doclist, with_comments=1): if with_comments: d['##comment'] = 'These values are common for all ' + d['doctype'] commons.append(strip_common(d)) - + common_values = make_common(doclist) return [common_values]+commons+final - + def uncommonify_doclist(dl): """ Expands an commonified doclist @@ -249,13 +252,13 @@ def uncommonify_doclist(dl): final.append(d1) return final - + def pprint_doclist(doclist, with_comments = 1): """ Pretty Prints a doclist with common keys separated and comments """ from webnotes.utils import pprint_dict - + dictlist =[pprint_dict(d) for d in commonify_doclist(doclist, with_comments)] title = '# '+doclist[0]['doctype']+', '+doclist[0]['name'] return title + '\n[\n' + ',\n'.join(dictlist) + '\n]' @@ -268,5 +271,5 @@ def peval_doclist(txt): return uncommonify_doclist(eval(txt)) else: return eval(txt) - + return uncommonify_doclist(eval(txt)) diff --git a/cgi-bin/webnotes/utils/email_lib/receive.py b/cgi-bin/webnotes/utils/email_lib/receive.py index 7207d836f0..73d5e66c8c 100644 --- a/cgi-bin/webnotes/utils/email_lib/receive.py +++ b/cgi-bin/webnotes/utils/email_lib/receive.py @@ -39,8 +39,11 @@ class IncomingMail: """ get utf-8 encoded part content """ - return unicode(part.get_payload(decode=True),str(charset),"ignore").encode('utf8','replace') - + try: + return unicode(part.get_payload(decode=True),str(charset),"ignore").encode('utf8','replace') + except LookupError, e: + return part.get_payload() + def get_attachment(self, part, charset): """ Extracts an attachment diff --git a/cgi-bin/webnotes/widgets/page.py b/cgi-bin/webnotes/widgets/page.py index 0cad0b72d6..de31fb9fd7 100644 --- a/cgi-bin/webnotes/widgets/page.py +++ b/cgi-bin/webnotes/widgets/page.py @@ -19,7 +19,7 @@ class Page: Loads page info from files in module """ # load js - doc.fields['__script'] = module.get_doc_file('page',doc.name,'.js').read() + doc.fields['__script'] = module.get_doc_file('page',doc.name,'.js').read() or doc.script doc.script = None # load css diff --git a/cgi-bin/webnotes/widgets/query_builder.py b/cgi-bin/webnotes/widgets/query_builder.py index 72e320cd70..6b4196b6d7 100644 --- a/cgi-bin/webnotes/widgets/query_builder.py +++ b/cgi-bin/webnotes/widgets/query_builder.py @@ -14,7 +14,7 @@ def get_search_criteria_list(dt): def load_report_list(): webnotes.response['rep_list'] = get_search_criteria_list(form.getvalue('dt')) - + # Get, scrub metadata # ==================================================================== @@ -37,20 +37,20 @@ def get_parent_dt(dt): def get_sql_meta(tl): std_columns = { - 'owner':('Owner', '', '', '100'), - 'creation':('Created on', 'Date', '', '100'), - 'modified':('Last modified on', 'Date', '', '100'), + 'owner':('Owner', '', '', '100'), + 'creation':('Created on', 'Date', '', '100'), + 'modified':('Last modified on', 'Date', '', '100'), 'modified_by':('Modified By', '', '', '100') } - + meta = {} - + for dt in tl: meta[dt] = std_columns.copy() # for table doctype, the ID is the parent id pdt = get_parent_dt(dt) - if pdt: + if pdt: meta[dt]['parent'] = ('ID', 'Link', pdt, '200') # get the field properties from DocField @@ -58,10 +58,10 @@ def get_sql_meta(tl): for r in res: if r[0]: meta[dt][r[0]] = (r[1], r[2], r[3], r[4]); - + # name meta[dt]['name'] = ('ID', 'Link', dt, '200') - + return meta # Additional conditions to fulfill match permission rules @@ -80,12 +80,12 @@ def getmatchcondition(dt, ud, ur): return '' return ' OR '.join(cond) - + def add_match_conditions(q, tl, ur, ud): sl = [] for dt in tl: s = getmatchcondition(dt, ud, ur) - if s: + if s: sl.append(s) # insert the conditions @@ -94,13 +94,13 @@ def add_match_conditions(q, tl, ur, ud): condition_end = q.find('ORDER BY')!=-1 and 'ORDER BY' or 'LIMIT' condition_end = q.find('GROUP BY')!=-1 and 'GROUP BY' or condition_end - + if q.find('ORDER BY')!=-1 or q.find('LIMIT')!=-1 or q.find('GROUP BY')!=-1: # if query continues beyond conditions q = q.split(condition_end) q = q[0] + condition_st + '(' + ' OR '.join(sl) + ') ' + condition_end + q[1] else: q = q + condition_st + '(' + ' OR '.join(sl) + ')' - + return q # execute server-side script from Search Criteria @@ -111,7 +111,7 @@ def exec_report(code, res, colnames=[], colwidths=[], coltypes=[], coloptions=[] for c in colnames: col_idx[c] = i i+=1 - + # load globals (api) from webnotes import * from webnotes.utils import * @@ -127,12 +127,12 @@ def exec_report(code, res, colnames=[], colwidths=[], coltypes=[], coloptions=[] NEWLINE = '\n' exec str(code) - + if out!=None: res = out return res, style, header_html, footer_html, page_template - + # ==================================================================== def guess_type(m): @@ -146,7 +146,7 @@ def guess_type(m): return 'Date' else: return 'Data' - + def build_description_simple(): colnames, coltypes, coloptions, colwidths = [], [], [], [] @@ -155,7 +155,7 @@ def build_description_simple(): coltypes.append(guess_type[m[0]]) coloptions.append('') colwidths.append('100') - + return colnames, coltypes, coloptions, colwidths # ==================================================================== @@ -180,27 +180,27 @@ def build_description_standard(meta, tl): if (not dt) and merged_meta.get(fn): # no "AS" given, find type from merged description - + desc = merged_meta[fn] colnames.append(desc[0] or fn) coltypes.append(desc[1] or '') coloptions.append(desc[2] or '') colwidths.append(desc[3] or '100') - + elif meta.get(dt,{}).has_key(fn): # type specified for a multi-table join # usually from Report Builder - + desc = meta[dt][fn] colnames.append(desc[0] or fn) coltypes.append(desc[1] or '') coloptions.append(desc[2] or '') colwidths.append(desc[3] or '100') - + else: # nothing found # guess - + colnames.append(fn) coltypes.append(guess_type(f[1])) coloptions.append('') @@ -214,21 +214,21 @@ def build_description_standard(meta, tl): def runquery(q='', ret=0, from_export=0): import webnotes.utils - formatted = cint(form.getvalue('formatted')) - + formatted = cint(form.getvalue('formatted')) + # CASE A: Simple Query # -------------------- if form.getvalue('simple_query') or form.getvalue('is_simple'): - q = form.getvalue('simple_query') or form.getvalue('query') + if not q: q = form.getvalue('simple_query') or form.getvalue('query') if q.split()[0].lower() != 'select': raise Exception, 'Query must be a SELECT' - + as_dict = cint(form.getvalue('as_dict')) res = sql(q, as_dict = as_dict, as_list = not as_dict, formatted=formatted) - + # build colnames etc from metadata colnames, coltypes, coloptions, colwidths = [], [], [], [] - + # CASE B: Standard Query # ----------------------- else: @@ -236,17 +236,17 @@ def runquery(q='', ret=0, from_export=0): tl = get_sql_tables(q) meta = get_sql_meta(tl) - + q = add_match_conditions(q, tl, webnotes.user.roles, webnotes.user.get_defaults()) - + # replace special variables q = q.replace('__user', session['user']) q = q.replace('__today', webnotes.utils.nowdate()) - + res = sql(q, as_list=1, formatted=formatted) colnames, coltypes, coloptions, colwidths = build_description_standard(meta, tl) - + # run server script # ----------------- style, header_html, footer_html, page_template = '', '', '', '' @@ -254,15 +254,15 @@ def runquery(q='', ret=0, from_export=0): sc_id = form.getvalue('sc_id') from webnotes.model.code import get_code sc_details = webnotes.conn.sql("select module, standard, server_script from `tabSearch Criteria` where name=%s", sc_id)[0] - if sc_details[1]!='No': + if sc_details[1]!='No': code = get_code(sc_details[0], 'Search Criteria', sc_id, 'py') else: code = sc_details[2] - + if code: filter_values = form.has_key('filter_values') and eval(form.getvalue('filter_values','')) or {} res, style, header_html, footer_html, page_template = exec_report(code, res, colnames, colwidths, coltypes, coloptions, filter_values, q, from_export) - + out['colnames'] = colnames out['coltypes'] = coltypes out['coloptions'] = coloptions @@ -270,17 +270,17 @@ def runquery(q='', ret=0, from_export=0): out['header_html'] = header_html out['footer_html'] = footer_html out['page_template'] = page_template - + if style: out['style'] = style - + # just the data - return if ret==1: - return res + return res out['values'] = res - # return num of entries + # return num of entries qm = form.has_key('query_max') and form.getvalue('query_max') or '' if qm and qm.strip(): if qm.split()[0].lower() != 'select': @@ -298,31 +298,31 @@ def runquery_csv(): # run query res = runquery(from_export = 1) - + q = form.getvalue('query') - + rep_name = form.getvalue('report_name') if not form.has_key('simple_query'): # Report Name if not rep_name: rep_name = get_sql_tables(q)[0] - + if not rep_name: rep_name = 'DataExport' - + # Headings heads = [] - + rows = [[rep_name], out['colnames']] + out['values'] - + from cStringIO import StringIO import csv - + f = StringIO() writer = csv.writer(f) for r in rows: writer.writerow(r) - + f.seek(0) out['result'] = f.read() out['type'] = 'csv' diff --git a/cgi-bin/webnotes/widgets/search.py b/cgi-bin/webnotes/widgets/search.py index 9d8da2b790..bfd1c08486 100644 --- a/cgi-bin/webnotes/widgets/search.py +++ b/cgi-bin/webnotes/widgets/search.py @@ -22,16 +22,16 @@ def getsearchfields(): webnotes.response['searchfields'] = [['name', 'ID', 'Data', '']] + res def make_query(fields, dt, key, txt, start, length): - return """SELECT %(fields)s - FROM `tab%(dt)s` + return """SELECT %(fields)s + FROM `tab%(dt)s` WHERE `tab%(dt)s`.`%(key)s` LIKE '%(txt)s' AND `tab%(dt)s`.docstatus != 2 - ORDER BY `tab%(dt)s`.`%(key)s` + ORDER BY `tab%(dt)s`.`%(key)s` DESC LIMIT %(start)s, %(len)s """ % { 'fields': fields, 'dt': dt, 'key': key, 'txt': txt + '%', - 'start': start, + 'start': start, 'len': length } @@ -48,7 +48,7 @@ def get_std_fields_list(dt, key): def build_for_autosuggest(res): from webnotes.utils import cstr - + results = [] for r in res: info = '' @@ -56,10 +56,10 @@ def build_for_autosuggest(res): info = ','.join([cstr(t) for t in r[1:]]) if len(info) > 30: info = info[:30] + '...' - + results.append({'id':r[0], 'value':r[0], 'info':info}) return results - + def scrub_custom_query(query, key, txt): if '%(key)s' in query: query = query.replace('%(key)s', key) @@ -74,7 +74,7 @@ def search_link(): txt = webnotes.form.getvalue('txt') dt = webnotes.form.getvalue('dt') query = webnotes.form.getvalue('query') - + if query: res = webnotes.conn.sql(scrub_custom_query(query, 'name', txt)) else: @@ -97,5 +97,5 @@ def search_widget(): query = scrub_custom_query(user_query, key, txt) else: query = make_query(', '.join(get_std_fields_list(dt, key)), dt, key, txt, webnotes.form.getvalue('start') or 0, webnotes.form.getvalue('page_len') or 50) - + webnotes.widgets.query_builder.runquery(query) diff --git a/js/webpage/search.js b/js/webpage/search.js index b0098ea80a..d921e4c310 100644 --- a/js/webpage/search.js +++ b/js/webpage/search.js @@ -21,8 +21,8 @@ function makeselector() { ['Button', 'Search'], ['HTML', 'Help'], ['HTML', 'Result'] - ]); - + ]); + // search with var inp = d.widgets['Beginning With']; var field_sel = d.widgets['Search By']; @@ -39,7 +39,7 @@ function makeselector() { } d.style = 'Link'; d.set_query_description() - + if(!d.sel_type)d.sel_type = 'Value'; d.set_title('Select a "'+ d.sel_type +'" for field "'+label+'"'); } @@ -47,18 +47,18 @@ function makeselector() { if(d.style!='Search') { d.rows['Result'].innerHTML =''; d.values_len = 0; - } + } d.style = 'Search'; if(d.input) { d.input = null; sel_type = null; } d.sel_type = get_label_doctype(dt); d.set_title('Quick Search for ' + dt); } - - inp.onkeydown = function(e) { + + inp.onkeydown = function(e) { if(isIE)var kc = window.event.keyCode; else var kc = e.keyCode; - if(kc==13) if(!btn.disabled)btn.onclick(); + if(kc==13) if(!btn.disabled)btn.onclick(); } d.set_query_description = function() { @@ -68,18 +68,18 @@ function makeselector() { d.rows['Help'].innerHTML ='' } } - d.onshow = function() { + d.onshow = function() { if(d.set_doctype!=d.sel_type) { d.rows['Result'].innerHTML =''; d.values_len = 0; } - - inp.value = ''; + + inp.value = ''; if(d.input && d.input.txt.value) { inp.value = d.input.txt.value; } try{inp.focus();} catch(e){} - + if(d.input) d.input.set_get_query(); // temp function to strip labels from search fields @@ -88,10 +88,10 @@ function makeselector() { for(var i=0; i