def execute_patch(patchmodule, method=None, methodargs=None): """execute the patch""" success = False block_user(True) webnotes.conn.begin() try: log("Executing %s in %s" % (patchmodule or str(methodargs), webnotes.conn.cur_db_name)) if patchmodule: if patchmodule.startswith("execute:"): exec patchmodule.split("execute:")[1] in globals() else: webnotes.get_attr(patchmodule + ".execute")() update_patch_log(patchmodule) elif method: method(**methodargs) webnotes.conn.commit() success = True except Exception, e: webnotes.conn.rollback() tb = webnotes.get_traceback() log(tb) import os if webnotes.request: add_to_patch_log(tb)
def has_additional_permission(doc): condition_methods = webnotes.get_hooks("has_permission:" + doc.doctype) for method in webnotes.get_hooks("has_permission:" + doc.doctype): if not webnotes.get_attr(method)(doc): return False return True
def get_bootinfo(): """build and return boot info""" bootinfo = webnotes._dict() hooks = webnotes.get_hooks() doclist = [] # profile get_profile(bootinfo) # control panel cp = webnotes.model.doc.getsingle('Control Panel') # system info bootinfo['control_panel'] = webnotes._dict(cp.copy()) bootinfo['sysdefaults'] = webnotes.defaults.get_defaults() bootinfo['server_date'] = webnotes.utils.nowdate() bootinfo["send_print_in_body_and_attachment"] = webnotes.conn.get_value("Email Settings", None, "send_print_in_body_and_attachment") if webnotes.session['user'] != 'Guest': bootinfo['user_info'] = get_fullnames() bootinfo['sid'] = webnotes.session['sid']; # home page bootinfo.modules = {} for app in webnotes.get_installed_apps(): try: bootinfo.modules.update(webnotes.get_attr(app + ".config.desktop.data") or {}) except ImportError, e: pass
def trigger(method): """trigger method in startup.schedule_handler""" traceback = "" for scheduler_event in webnotes.get_hooks().scheduler_event: event_name, handler = scheduler_event.split(":") if method == event_name: try: webnotes.get_attr(handler)() webnotes.conn.commit() except Exception: traceback += log("Method: {method}, Handler: {handler}".format(method=method, handler=handler)) traceback += log(webnotes.get_traceback()) webnotes.conn.rollback() return traceback or "ok"
def clear_cache(page_name=None): cache = webnotes.cache() if page_name: delete_page_cache(page_name) else: for p in webnotes.conn.sql_list("""select name from `tabWebsite Sitemap`"""): if p is not None: delete_page_cache(p) cache.delete_value("home_page") clear_permissions() for method in webnotes.get_hooks("website_clear_cache"): webnotes.get_attr(method)(page_name)
def get_notification_config(): config = webnotes._dict() for notification_config in webnotes.get_hooks().notification_config: nc = webnotes.get_attr(notification_config)() for key in ("for_doctype", "for_module", "for_module_doctypes"): config.setdefault(key, {}) config[key].update(nc.get(key, {})) return config
def get_attr(cmd): """get method object from cmd""" if '.' in cmd: method = webnotes.get_attr(cmd) else: method = globals()[cmd] webnotes.log("method:" + cmd) return method
def get_permission_query_conditions(doctype): condition_methods = webnotes.get_hooks("permission_query_conditions:" + doctype) if condition_methods: conditions = [] for method in condition_methods: c = webnotes.get_attr(method)() if c: conditions.append(c) return " and ".join(conditions) if conditions else None
def get_footer(footer=None): """append a footer (signature)""" footer = footer or "" # control panel footer += webnotes.conn.get_value('Control Panel', None, 'mail_footer') or '' # hooks for f in webnotes.get_hooks("mail_footer"): footer += webnotes.get_attr(f) footer += "<!--unsubscribe link here-->" return footer
def search_widget(doctype, txt, query=None, searchfield="name", start=0, page_len=50, filters=None): if isinstance(filters, basestring): import json filters = json.loads(filters) meta = webnotes.get_doctype(doctype) standard_queries = webnotes.get_hooks().standard_queries or [] if standard_queries: standard_queries = dict([v.split(":") for v in standard_queries]) if query and query.split()[0].lower()!="select": # by method webnotes.response["values"] = webnotes.get_attr(query)(doctype, txt, searchfield, start, page_len, filters) elif not query and doctype in standard_queries: # from standard queries search_widget(doctype, txt, standard_queries[doctype], searchfield, start, page_len, filters) else: if query: # custom query webnotes.response["values"] = webnotes.conn.sql(scrub_custom_query(query, searchfield, txt)) else: if isinstance(filters, dict): filters_items = filters.items() filters = [] for f in filters_items: if isinstance(f[1], (list, tuple)): filters.append([doctype, f[0], f[1][0], f[1][1]]) else: filters.append([doctype, f[0], "=", f[1]]) if filters==None: filters = [] # build from doctype if txt: filters.append([doctype, searchfield or "name", "like", txt + "%"]) if meta.get({"parent":doctype, "fieldname":"enabled", "fieldtype":"Check"}): filters.append([doctype, "enabled", "=", 1]) if meta.get({"parent":doctype, "fieldname":"disabled", "fieldtype":"Check"}): filters.append([doctype, "disabled", "!=", 1]) webnotes.response["values"] = webnotes.widgets.reportview.execute(doctype, filters=filters, fields = get_std_fields_list(meta, searchfield or "name"), limit_start = start, limit_page_length=page_len, as_list=True)
def get_notifications(): config = get_notification_config() can_read = webnotes.user.get_can_read() open_count_doctype = {} open_count_module = {} notification_count = dict( webnotes.conn.sql( """select for_doctype, open_count from `tabNotification Count` where owner=%s""", (webnotes.session.user,), ) ) for d in config.for_doctype: if d in can_read: condition = config.for_doctype[d] key = condition.keys()[0] if d in notification_count: open_count_doctype[d] = notification_count[d] else: result = webnotes.get_list( d, fields=["count(*)"], filters=[[d, key, "=", condition[key]]], as_list=True, limit_page_length=1 )[0][0] webnotes.doc({"doctype": "Notification Count", "for_doctype": d, "open_count": result}).insert() open_count_doctype[d] = result for m in config.for_module: if m in notification_count: open_count_module[m] = notification_count[m] else: open_count_module[m] = webnotes.get_attr(config.for_module[m])() webnotes.doc( {"doctype": "Notification Count", "for_doctype": m, "open_count": open_count_module[m]} ).insert() return {"open_count_doctype": open_count_doctype, "open_count_module": open_count_module}
def run_method(self, method, *args, **kwargs): if not args: args = [] self.make_controller() def add_to_response(out, new_response): if isinstance(new_response, dict): out.update(new_response) if hasattr(self.controller, method): add_to_response(webnotes.local.response, webnotes.call(getattr(self.controller, method), *args, **kwargs)) args = [self, method] + list(args) for handler in webnotes.get_hooks("bean_event:" + self.doc.doctype + ":" + method) \ + webnotes.get_hooks("bean_event:*:" + method): add_to_response(webnotes.local.response, webnotes.call(webnotes.get_attr(handler), *args, **kwargs)) self.set_doclist(self.controller.doclist) return webnotes.local.response return out
def run(report_name, filters=()): report = get_report_doc(report_name) if filters and isinstance(filters, basestring): filters = json.loads(filters) if not webnotes.has_permission(report.ref_doctype, "report"): webnotes.msgprint(_("Must have report permission to access this report."), raise_exception=True) if report.report_type=="Query Report": if not report.query: webnotes.msgprint(_("Must specify a Query to run"), raise_exception=True) if not report.query.lower().startswith("select"): webnotes.msgprint(_("Query must be a SELECT"), raise_exception=True) result = [list(t) for t in webnotes.conn.sql(report.query, filters)] columns = [c[0] for c in webnotes.conn.get_description()] else: module = webnotes.conn.get_value("DocType", report.ref_doctype, "module") if report.is_standard=="Yes": method_name = webnotes.local.module_app[scrub(module)] + "." + scrub(module) \ + ".report." + scrub(report.name) + "." + scrub(report.name) + ".execute" columns, result = webnotes.get_attr(method_name)(filters or {}) result = get_filtered_data(report.ref_doctype, columns, result) if cint(report.add_total_row) and result: result = add_total_row(result, columns) return { "result": result, "columns": columns }
add_home_page(bootinfo, doclist) add_allowed_pages(bootinfo) load_translations(bootinfo) load_conf_settings(bootinfo) load_startup_js(bootinfo) # ipinfo if webnotes.session['data'].get('ipinfo'): bootinfo['ipinfo'] = webnotes.session['data']['ipinfo'] # add docs bootinfo['docs'] = doclist for method in hooks.boot_session or []: webnotes.get_attr(method)(bootinfo) from webnotes.model.utils import compress bootinfo['docs'] = compress(bootinfo['docs']) # deal with __slots__ in lang if bootinfo.lang: bootinfo.lang = unicode(bootinfo.lang) bootinfo.metadata_version = webnotes.cache().get_value("metadata_version") if not bootinfo.metadata_version: bootinfo.metadata_version = webnotes.reset_metadata_version() return bootinfo def load_conf_settings(bootinfo):
def run_trigger(self, method='on_login'): for method in webnotes.get_hooks().get("method", []): webnotes.get_attr(method)(self)
def load_startup_js(bootinfo): bootinfo.startup_js = "" for method in webnotes.get_hooks().startup_js or []: bootinfo.startup_js += webnotes.get_attr(method)()
def get_website_settings(): # TODO Cache this hooks = webnotes.get_hooks() all_top_items = webnotes.conn.sql("""\ select * from `tabTop Bar Item` where parent='Website Settings' and parentfield='top_bar_items' order by idx asc""", as_dict=1) top_items = [d for d in all_top_items if not d['parent_label']] # attach child items to top bar for d in all_top_items: if d['parent_label']: for t in top_items: if t['label']==d['parent_label']: if not 'child_items' in t: t['child_items'] = [] t['child_items'].append(d) break context = webnotes._dict({ 'top_bar_items': top_items, 'footer_items': webnotes.conn.sql("""\ select * from `tabTop Bar Item` where parent='Website Settings' and parentfield='footer_items' order by idx asc""", as_dict=1), "post_login": [ {"label": "Reset Password", "url": "update-password", "icon": "icon-key"}, {"label": "Logout", "url": "?cmd=web_logout", "icon": "icon-signout"} ] }) settings = webnotes.doc("Website Settings", "Website Settings") for k in ["banner_html", "brand_html", "copyright", "twitter_share_via", "favicon", "facebook_share", "google_plus_one", "twitter_share", "linked_in_share", "disable_signup"]: if k in settings.fields: context[k] = settings.fields.get(k) if settings.address: context["footer_address"] = settings.address for k in ["facebook_share", "google_plus_one", "twitter_share", "linked_in_share", "disable_signup"]: context[k] = cint(context.get(k) or 0) context.url = quote(str(get_request_site_address(full_address=True)), safe="/:") context.encoded_title = quote(encode(context.title or ""), str("")) for update_website_context in hooks.update_website_context or []: webnotes.get_attr(update_website_context)(context) context.web_include_js = hooks.web_include_js or [] context.web_include_css = hooks.web_include_css or [] # get settings from site config if webnotes.conf.get("fb_app_id"): context.fb_app_id = webnotes.conf.fb_app_id return context
else: webnotes.throw("Not Allowed") @webnotes.whitelist() def uploadfile(): try: if webnotes.form_dict.get('from_form'): try: ret = webnotes.utils.file_manager.upload() except webnotes.DuplicateEntryError, e: # ignore pass ret = None webnotes.conn.rollback() else: if webnotes.form_dict.get('method'): ret = webnotes.get_attr(webnotes.form_dict.method)() except Exception, e: webnotes.errprint(webnotes.utils.get_traceback()) ret = None return ret def handle(): """handle request""" cmd = webnotes.local.form_dict.cmd if cmd!='login': status_codes = { webnotes.PermissionError: 403, webnotes.AuthenticationError: 401, webnotes.DoesNotExistError: 404,
def get_data(doctypes, last_modified): data_map = {} for dump_report_map in webnotes.get_hooks().dump_report_map: data_map.update(webnotes.get_attr(dump_report_map)) import datetime out = {} doctypes = json.loads(doctypes) last_modified = json.loads(last_modified) start = datetime.datetime.now() for d in doctypes: args = copy.deepcopy(data_map[d]) dt = d.find("[") != -1 and d[:d.find("[")] or d out[dt] = {} if args.get("from"): modified_table = "item." else: modified_table = "" conditions = order_by = "" table = args.get("from") or ("`tab%s`" % dt) if d in last_modified: if not args.get("conditions"): args['conditions'] = [] args['conditions'].append(modified_table + "modified > '" + last_modified[d] + "'") out[dt]["modified_names"] = webnotes.conn.sql_list("""select %sname from %s where %smodified > %s""" % (modified_table, table, modified_table, "%s"), last_modified[d]) if args.get("force_index"): conditions = " force index (%s) " % args["force_index"] if args.get("conditions"): conditions += " where " + " and ".join(args["conditions"]) if args.get("order_by"): order_by = " order by " + args["order_by"] out[dt]["data"] = [list(t) for t in webnotes.conn.sql("""select %s from %s %s %s""" \ % (",".join(args["columns"]), table, conditions, order_by))] # last modified modified_table = table if "," in table: modified_table = " ".join(table.split(",")[0].split(" ")[:-1]) tmp = webnotes.conn.sql("""select `modified` from %s order by modified desc limit 1""" % modified_table) out[dt]["last_modified"] = tmp and tmp[0][0] or "" out[dt]["columns"] = map(lambda c: c.split(" as ")[-1], args["columns"]) if args.get("links"): out[dt]["links"] = args["links"] for d in out: unused_links = [] # only compress full dumps (not partial) if out[d].get("links") and (d not in last_modified): for link_key in out[d]["links"]: link = out[d]["links"][link_key] if link[0] in out and (link[0] not in last_modified): # make a map of link ids # to index link_map = {} doctype_data = out[link[0]] col_idx = doctype_data["columns"].index(link[1]) for row_idx in xrange(len(doctype_data["data"])): row = doctype_data["data"][row_idx] link_map[row[col_idx]] = row_idx for row in out[d]["data"]: col_idx = out[d]["columns"].index(link_key) # replace by id if row[col_idx]: row[col_idx] = link_map.get(row[col_idx]) else: unused_links.append(link_key) for link in unused_links: del out[d]["links"][link] return out