def __init__(self, login=None, password=None, server=None, port=None, use_ssl=None): import webnotes.model.doc from webnotes.utils import cint # get defaults from control panel try: es = webnotes.model.doc.Document('Email Settings','Email Settings') except webnotes.DoesNotExistError: es = None self._sess = None if server: self.server = server self.port = port self.use_ssl = cint(use_ssl) self.login = login self.password = password elif es and es.outgoing_mail_server: self.server = es.outgoing_mail_server self.port = es.mail_port self.use_ssl = cint(es.use_ssl) self.login = es.mail_login self.password = es.mail_password self.always_use_login_id_as_sender = es.always_use_login_id_as_sender else: self.server = conf.get("mail_server") or "" self.port = conf.get("mail_port") or None self.use_ssl = cint(conf.get("use_ssl") or 0) self.login = conf.get("mail_login") or "" self.password = conf.get("mail_password") or ""
def sql(self, query, values=(), as_dict=0, as_list=0, formatted=0, debug=0, ignore_ddl=0, as_utf8=0, auto_commit=0, update=None): """ * Execute a `query`, with given `values` * returns as a dictionary if as_dict = 1 * returns as a list of lists (with cleaned up dates) if as_list = 1 """ # in transaction validations self.check_transaction_status(query) # autocommit if auto_commit: self.commit() # execute try: if values != (): if isinstance(values, dict): values = dict(values) if debug: try: self.explain_query(query, values) webnotes.errprint(query % values) except TypeError: webnotes.errprint([query, values]) if (conf.get("logging") or False) == 2: webnotes.log("<<<< query") webnotes.log(query) webnotes.log("with values:") webnotes.log(values) webnotes.log(">>>>") self._cursor.execute(query, values) else: if debug: self.explain_query(query) webnotes.errprint(query) if (conf.get("logging") or False) == 2: webnotes.log("<<<< query") webnotes.log(query) webnotes.log(">>>>") self._cursor.execute(query) except Exception, e: # ignore data definition errors if ignore_ddl and e.args[0] in (1146, 1054, 1091): pass else: raise
def __init__(self,doctype='', login=None, password=None, server=None, port=None, use_ssl=None): import webnotes.model.doc from webnotes.utils import cint es = None self.flag=False #webnotes.errprint("in the SMTPSER") #webnotes.errprint(doctype) # get defaults from control panel """try: es = webnotes.model.doc.Document('Email Settings','Email Settings') except webnotes.DoesNotExistError: es = None""" try: if doctype=="Email Inbox" or doctype=="Compose Mail": #webnotes.errprint("in the if of Email Document") self.flag=True else: es = webnotes.model.doc.Document('Email Settings','Email Settings') except webnotes.DoesNotExistError: es = None self._sess = None if server: self.server = server self.port = port self.use_ssl = cint(use_ssl) self.login = login self.password = password elif es and es.outgoing_mail_server: self.server = es.outgoing_mail_server self.port = es.mail_port self.use_ssl = cint(es.use_ssl) self.login = es.mail_login self.password = es.mail_password self.always_use_login_id_as_sender = es.always_use_login_id_as_sender elif self.flag: #webnotes.errprint("in the true flag") self.server = "smtp.gmail.com" self.port = 587 self.use_ssl = 1 self.login=webnotes.session.user # webnotes.errprint(self.login) acc_token=webnotes.conn.sql("""select response from `tabProfile` where name ='%s'"""%(self.login),as_list=1) # webnotes.errprint(access_token) self.access_token=acc_token[0][0] else: self.server = conf.get("mail_server") or "" self.port = conf.get("mail_port") or None self.use_ssl = cint(conf.get("use_ssl") or 0) self.login = conf.get("mail_login") or "" self.password = conf.get("mail_password") or ""
def sql(self, query, values=(), as_dict = 0, as_list = 0, formatted = 0, debug=0, ignore_ddl=0, as_utf8=0, auto_commit=0, update=None): """ * Execute a `query`, with given `values` * returns as a dictionary if as_dict = 1 * returns as a list of lists (with cleaned up dates) if as_list = 1 """ # in transaction validations self.check_transaction_status(query) # autocommit if auto_commit: self.commit() # execute try: if values!=(): if isinstance(values, dict): values = dict(values) # MySQL-python==1.2.5 hack! if not isinstance(values, (dict, tuple, list)): values = (values,) if debug: try: self.explain_query(query, values) webnotes.errprint(query % values) except TypeError: webnotes.errprint([query, values]) if (conf.get("logging") or False)==2: webnotes.log("<<<< query") webnotes.log(query) webnotes.log("with values:") webnotes.log(values) webnotes.log(">>>>") self._cursor.execute(query, values) else: if debug: self.explain_query(query) webnotes.errprint(query) if (conf.get("logging") or False)==2: webnotes.log("<<<< query") webnotes.log(query) webnotes.log(">>>>") self._cursor.execute(query) except Exception, e: # ignore data definition errors if ignore_ddl and e.args[0] in (1146,1054,1091): pass else: raise
def send(self, as_bulk=False): """send the message or add it to Outbox Email""" if webnotes.flags.mute_emails or conf.get("mute_emails") or False: webnotes.msgprint("Emails are muted") return import smtplib try: smtpserver = SMTPServer() if hasattr(smtpserver, "always_use_login_id_as_sender") and \ cint(smtpserver.always_use_login_id_as_sender) and smtpserver.login: self.sender = smtpserver.login smtpserver.sess.sendmail(self.sender, self.recipients + (self.cc or []), self.as_string()) except smtplib.SMTPSenderRefused: webnotes.msgprint( """Invalid Outgoing Mail Server's Login Id or Password. \ Please rectify and try again.""", raise_exception=webnotes.OutgoingEmailError) except smtplib.SMTPRecipientsRefused: webnotes.msgprint("""Invalid Recipient (To) Email Address. \ Please rectify and try again.""", raise_exception=webnotes.OutgoingEmailError)
def boot_session(bootinfo): """boot session - send website info if guest""" import webnotes import webnotes.model.doc bootinfo['custom_css'] = webnotes.conn.get_value('Style Settings', None, 'custom_css') or '' bootinfo['website_settings'] = webnotes.model.doc.getsingle('Website Settings') if webnotes.session['user']!='Guest': bootinfo['letter_heads'] = get_letter_heads() load_country_and_currency(bootinfo) import webnotes.model.doctype bootinfo['notification_settings'] = webnotes.doc("Notification Control", "Notification Control").get_values() # if no company, show a dialog box to create a new company bootinfo["customer_count"] = webnotes.conn.sql("""select count(*) from tabCustomer""")[0][0] if not bootinfo["customer_count"]: bootinfo['setup_complete'] = webnotes.conn.sql("""select name from tabCompany limit 1""") and 'Yes' or 'No' # load subscription info from webnotes import conf for key in ['max_users', 'expires_on', 'max_space', 'status', 'commercial_support']: if key in conf: bootinfo[key] = conf.get(key) bootinfo['docs'] += webnotes.conn.sql("""select name, default_currency, cost_center from `tabCompany`""", as_dict=1, update={"doctype":":Company"})
def flush(from_test=False): """flush email queue, every time: called from scheduler""" import webnotes from webnotes import conf from webnotes.utils.email_lib.smtp import SMTPServer, get_email smptserver = SMTPServer() auto_commit = not from_test if webnotes.flags.mute_emails or conf.get("mute_emails") or False: webnotes.msgprint("Emails are muted") from_test = True for i in xrange(500): email = webnotes.conn.sql("""select * from `tabBulk Email` where status='Not Sent' limit 1 for update""", as_dict=1) if email: email = email[0] else: break webnotes.conn.sql("""update `tabBulk Email` set status='Sending' where name=%s""", email["name"], auto_commit=auto_commit) try: if not from_test: smptserver.sess.sendmail(email["sender"], email["recipient"], email["message"]) webnotes.conn.sql("""update `tabBulk Email` set status='Sent' where name=%s""", email["name"], auto_commit=auto_commit) except Exception, e: webnotes.conn.sql("""update `tabBulk Email` set status='Error', error=%s where name=%s""", (unicode(e), email["name"]), auto_commit=auto_commit)
def export_doc(self): # export if self.doc.standard == 'Yes' and (conf.get('developer_mode') or 0) == 1: from webnotes.modules.export_file import export_to_files export_to_files(record_list=[['Print Format', self.doc.name]], record_module=self.doc.module)
def validate(self): """validate the email ids""" from webnotes.utils import validate_email_add def _validate(email): """validate an email field""" if email and not validate_email_add(email): webnotes.msgprint("%s is not a valid email id" % email, raise_exception = 1) return email if not self.sender: self.sender = webnotes.conn.get_value('Email Settings', None, 'auto_email_id') or conf.get('auto_email_id') or None if not self.sender: webnotes.msgprint("""Please specify 'Auto Email Id' \ in Setup > Email Settings""") if not "expires_on" in conf: webnotes.msgprint("""Alternatively, \ you can also specify 'auto_email_id' in conf.py""") raise webnotes.ValidationError self.sender = _validate(self.sender) self.reply_to = _validate(self.reply_to) for e in self.recipients + (self.cc or []): _validate(e.strip())
def send(self, as_bulk=False): """send the message or add it to Outbox Email""" if webnotes.flags.mute_emails or conf.get("mute_emails") or False: webnotes.msgprint("Emails are muted") return import smtplib try: smtpserver = SMTPServer() if hasattr(smtpserver, "always_use_login_id_as_sender") and \ cint(smtpserver.always_use_login_id_as_sender) and smtpserver.login: self.sender = smtpserver.login smtpserver.sess.sendmail(self.sender, self.recipients + (self.cc or []), self.as_string()) except smtplib.SMTPSenderRefused: webnotes.msgprint("""Invalid Outgoing Mail Server's Login Id or Password. \ Please rectify and try again.""") raise except smtplib.SMTPRecipientsRefused: webnotes.msgprint("""Invalid Recipient (To) Email Address. \ Please rectify and try again.""") raise
def validate(self): """validate the email ids""" from webnotes.utils import validate_email_add def _validate(email): """validate an email field""" if email and not validate_email_add(email): webnotes.msgprint("%s is not a valid email id" % email, raise_exception=1) return email if not self.sender: self.sender = webnotes.conn.get_value( 'Email Settings', None, 'auto_email_id') or conf.get('auto_email_id') or None if not self.sender: webnotes.msgprint("""Please specify 'Auto Email Id' \ in Setup > Email Settings""") if not "expires_on" in conf: webnotes.msgprint("""Alternatively, \ you can also specify 'auto_email_id' in conf.py""") raise webnotes.ValidationError self.sender = _validate(self.sender) self.reply_to = _validate(self.reply_to) for e in self.recipients + (self.cc or []): _validate(e.strip())
def export_doc(self): # export if self.doc.is_standard == 'Yes' and (conf.get('developer_mode') or 0) == 1: from webnotes.modules.export_file import export_to_files export_to_files(record_list=[['Report', self.doc.name]], record_module=webnotes.conn.get_value( "DocType", self.doc.ref_doctype, "module"))
def validate_send(self): if self.doc.fields.get("__islocal"): webnotes.msgprint(_("""Please save the Newsletter before sending."""), raise_exception=1) from webnotes import conf if (conf.get("status") or None) == "Trial": webnotes.msgprint(_("""Sending newsletters is not allowed for Trial users, \ to prevent abuse of this feature."""), raise_exception=1)
def check_max_file_size(content): file_size=0 max_file_size = conf.get('max_file_size') or 1000000 if content: file_size = len(content) if file_size > max_file_size: webnotes.msgprint(_("File size exceeded the maximum allowed size"), raise_exception=MaxFileSizeReachedError) return file_size
def get_value(self, key, builder=None): if builder and conf.get("auto_cache_clear") or False: return builder() val = self.get(self.n(key)) if not val and builder: val = builder() self.set_value(key, val) return val
def check_max_file_size(content): max_file_size = conf.get('max_file_size') or 1000000 file_size = len(content) if file_size > max_file_size: webnotes.msgprint(_("File size exceeded the maximum allowed size"), raise_exception=MaxFileSizeReachedError) return file_size
def export_doc(self): from webnotes.modules.export_file import export_to_files if self.doc.is_standard == 'Yes' and (conf.get('developer_mode') or 0) == 1: export_to_files(record_list=[['Report', self.doc.name]], record_module=webnotes.conn.get_value("DocType", self.doc.ref_doctype, "module")) elif self.doc.is_standard == 'No' and self.doc.report_type == "Script Report": from webnotes.plugins import get_plugin_name export_to_files(record_list=[['Report', self.doc.name]], record_module=webnotes.conn.get_value("DocType", self.doc.ref_doctype, "module"), plugin=get_plugin_name("Report", self.doc.name), create_init=False)
def check_bulk_limit(new_mails): from webnotes import conf from webnotes.utils import nowdate this_month = webnotes.conn.sql("""select count(*) from `tabBulk Email` where month(creation)=month(%s)""" % nowdate())[0][0] monthly_bulk_mail_limit = conf.get('monthly_bulk_mail_limit') or 500 if this_month + len(recipients) > monthly_bulk_mail_limit: webnotes.msgprint("""Monthly Bulk Mail Limit (%s) Crossed""" % monthly_bulk_mail_limit, raise_exception=BulkLimitCrossedError)
def validate_send(self): if self.doc.fields.get("__islocal"): webnotes.msgprint( _("""Please save the Newsletter before sending."""), raise_exception=1) from webnotes import conf if (conf.get("status") or None) == "Trial": webnotes.msgprint( _("""Sending newsletters is not allowed for Trial users, \ to prevent abuse of this feature."""), raise_exception=1)
def export_doc(self): from webnotes.modules.export_file import export_to_files if self.doc.is_standard == 'Yes' and (conf.get('developer_mode') or 0) == 1: export_to_files(record_list=[['Report', self.doc.name]], record_module=webnotes.conn.get_value( "DocType", self.doc.ref_doctype, "module")) elif self.doc.is_standard == 'No' and self.doc.report_type == "Script Report": from webnotes.plugins import get_plugin_name export_to_files(record_list=[['Report', self.doc.name]], record_module=webnotes.conn.get_value( "DocType", self.doc.ref_doctype, "module"), plugin=get_plugin_name("Report", self.doc.name), create_init=False)
def make_logs(): """make strings for msgprint and errprint""" import json from webnotes import conf from webnotes.utils import cstr if webnotes.error_log: # webnotes.response['exc'] = json.dumps("\n".join([cstr(d) for d in webnotes.error_log])) webnotes.response['exc'] = json.dumps([cstr(d) for d in webnotes.local.error_log]) if webnotes.local.message_log: webnotes.response['_server_messages'] = json.dumps([cstr(d) for d in webnotes.local.message_log]) if webnotes.debug_log and conf.get("logging") or False: webnotes.response['_debug_messages'] = json.dumps(webnotes.local.debug_log)
def check_bulk_limit(new_mails): from webnotes import conf from webnotes.utils import nowdate this_month = webnotes.conn.sql( """select count(*) from `tabBulk Email` where month(creation)=month(%s)""" % nowdate())[0][0] monthly_bulk_mail_limit = conf.get('monthly_bulk_mail_limit') or 500 if this_month + len(recipients) > monthly_bulk_mail_limit: webnotes.msgprint("""Monthly Bulk Mail Limit (%s) Crossed""" % monthly_bulk_mail_limit, raise_exception=BulkLimitCrossedError)
def __init__(self, login=None, password=None, server=None, port=None, use_ssl=None): import webnotes.model.doc from webnotes.utils import cint # get defaults from control panel try: es = webnotes.model.doc.Document('Email Settings', 'Email Settings') except webnotes.DoesNotExistError: es = None self._sess = None if server: self.server = server self.port = port self.use_ssl = cint(use_ssl) self.login = login self.password = password elif es and es.outgoing_mail_server: self.server = es.outgoing_mail_server self.port = es.mail_port self.use_ssl = cint(es.use_ssl) self.login = es.mail_login self.password = es.mail_password self.always_use_login_id_as_sender = es.always_use_login_id_as_sender else: self.server = conf.get("mail_server") or "" self.port = conf.get("mail_port") or None self.use_ssl = cint(conf.get("use_ssl") or 0) self.login = conf.get("mail_login") or "" self.password = conf.get("mail_password") or ""
def make_logs(): """make strings for msgprint and errprint""" import json from webnotes import conf from webnotes.utils import cstr if webnotes.error_log: # webnotes.response['exc'] = json.dumps("\n".join([cstr(d) for d in webnotes.error_log])) webnotes.response['exc'] = json.dumps( [cstr(d) for d in webnotes.local.error_log]) if webnotes.local.message_log: webnotes.response['_server_messages'] = json.dumps( [cstr(d) for d in webnotes.local.message_log]) if webnotes.debug_log and conf.get("logging") or False: webnotes.response['_debug_messages'] = json.dumps( webnotes.local.debug_log)
def on_update(self): from webnotes.model.db_schema import updatedb updatedb(self.doc.name) self.change_modified_of_parent() make_module_and_roles(self.doclist) from webnotes import conf if (not webnotes.flags.in_import) and conf.get('developer_mode') or 0: self.export_doc() self.make_controller_template() # update index if not self.doc.custom: from webnotes.model.code import load_doctype_module module = load_doctype_module( self.doc.name, self.doc.module) if hasattr(module, "on_doctype_update"): module.on_doctype_update() webnotes.clear_cache(doctype=self.doc.name)
def on_update(self): from webnotes.model.db_schema import updatedb updatedb(self.doc.name) self.change_modified_of_parent() make_module_and_roles(self.doclist) from webnotes import conf if (not webnotes.flags.in_import) and conf.get('developer_mode') or 0: self.export_doc() self.make_controller_template() # update index if not self.doc.custom: from webnotes.model.code import load_doctype_module module = load_doctype_module(self.doc.name, self.doc.module) if hasattr(module, "on_doctype_update"): module.on_doctype_update() webnotes.clear_cache(doctype=self.doc.name)
def flush(from_test=False): """flush email queue, every time: called from scheduler""" import webnotes from webnotes import conf from webnotes.utils.email_lib.smtp import SMTPServer, get_email smptserver = SMTPServer() auto_commit = not from_test if webnotes.flags.mute_emails or conf.get("mute_emails") or False: webnotes.msgprint("Emails are muted") from_test = True for i in xrange(500): email = webnotes.conn.sql("""select * from `tabBulk Email` where status='Not Sent' limit 1 for update""", as_dict=1) if email: email = email[0] else: break webnotes.conn.sql( """update `tabBulk Email` set status='Sending' where name=%s""", email["name"], auto_commit=auto_commit) try: if not from_test: smptserver.sess.sendmail(email["sender"], email["recipient"], email["message"]) webnotes.conn.sql( """update `tabBulk Email` set status='Sent' where name=%s""", email["name"], auto_commit=auto_commit) except Exception, e: webnotes.conn.sql( """update `tabBulk Email` set status='Error', error=%s where name=%s""", (unicode(e), email["name"]), auto_commit=auto_commit)
def export_doc(self): # export if self.doc.is_standard == 'Yes' and (conf.get('developer_mode') or 0) == 1: from webnotes.modules.export_file import export_to_files export_to_files(record_list=[['Report', self.doc.name]], record_module=webnotes.conn.get_value("DocType", self.doc.ref_doctype, "module"))
def get_backup_path(): import os backup_path = webnotes.utils.get_site_path(conf.get("backup_path", "public/backups")) return backup_path
def save_file(fname, content, dt, dn, decode=False): if decode: if isinstance(content, unicode): content = content.encode("utf-8") content = base64.b64decode(content) fname = slugify(unicode( os.path.splitext(fname)[0])) + os.path.splitext(fname)[1] import filecmp from webnotes.model.code import load_doctype_module files_path = get_site_path(conf.files_path) module = load_doctype_module( dt, webnotes.conn.get_value("DocType", dt, "module")) if hasattr(module, "attachments_folder"): files_path = os.path.join(files_path, module.attachments_folder) file_size = check_max_file_size(content) temp_fname = write_file(content, files_path) fname = scrub_file_name(fname) fname_parts = fname.split(".", -1) main = ".".join(fname_parts[:-1]) extn = fname_parts[-1] versions = get_file_versions(files_path, main, extn) if versions: found_match = False for version in versions: if filecmp.cmp(os.path.join(files_path, version), temp_fname): # remove new file, already exists! os.remove(temp_fname) fname = version fpath = os.path.join(files_path, fname) found_match = True break if not found_match: # get_new_version name fname = get_new_fname_based_on_version(files_path, main, extn, versions) fpath = os.path.join(files_path, fname) # rename if os.path.exists(fpath.encode("utf-8")): webnotes.throw("File already exists: " + fname) os.rename(temp_fname, fpath.encode("utf-8")) else: fpath = os.path.join(files_path, fname) # rename new file if os.path.exists(fpath.encode("utf-8")): webnotes.throw("File already exists: " + fname) os.rename(temp_fname, fpath.encode("utf-8")) f = webnotes.bean({ "doctype": "File Data", "file_name": os.path.relpath(os.path.join(files_path, fname), get_site_path(conf.get("public_path", "public"))), "attached_to_doctype": dt, "attached_to_name": dn, "file_size": file_size }) f.ignore_permissions = True try: f.insert() except webnotes.DuplicateEntryError: return {"file_name": f.doc.file_name} return f.doc
def get_backup_path(): import os backup_path = webnotes.utils.get_site_path( conf.get("backup_path", "public/backups")) return backup_path
def save_file(fname, content, dt, dn, decode=False): if decode: if isinstance(content, unicode): content = content.encode("utf-8") content = base64.b64decode(content) import filecmp from webnotes.model.code import load_doctype_module files_path = get_site_path(conf.files_path) module = load_doctype_module(dt, webnotes.conn.get_value("DocType", dt, "module")) if hasattr(module, "attachments_folder"): files_path = os.path.join(files_path, module.attachments_folder) file_size = check_max_file_size(content) temp_fname = write_file(content, files_path) fname = scrub_file_name(fname) fname_parts = fname.split(".", -1) main = ".".join(fname_parts[:-1]) extn = fname_parts[-1] versions = get_file_versions(files_path, main, extn) if versions: found_match = False for version in versions: if filecmp.cmp(os.path.join(files_path, version), temp_fname): # remove new file, already exists! os.remove(temp_fname) fname = version fpath = os.path.join(files_path, fname) found_match = True break if not found_match: # get_new_version name fname = get_new_fname_based_on_version(files_path, main, extn, versions) fpath = os.path.join(files_path, fname) # rename if os.path.exists(fpath.encode("utf-8")): webnotes.throw("File already exists: " + fname) os.rename(temp_fname, fpath.encode("utf-8")) else: fpath = os.path.join(files_path, fname) # rename new file if os.path.exists(fpath.encode("utf-8")): webnotes.throw("File already exists: " + fname) os.rename(temp_fname, fpath.encode("utf-8")) f = webnotes.bean({ "doctype": "File Data", "file_name": os.path.relpath(os.path.join(files_path, fname), get_site_path(conf.get("public_path", "public"))), "attached_to_doctype": dt, "attached_to_name": dn, "file_size": file_size }) f.ignore_permissions = True try: f.insert(); except webnotes.DuplicateEntryError: return {"file_name": f.doc.file_name} return f.doc
def load_conf_settings(bootinfo): from webnotes import conf for key in ['developer_mode']: if key in conf: bootinfo[key] = conf.get(key)