Exemplo n.º 1
0
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
Exemplo n.º 2
0
	def send_login_mail(self, subject, template, add_args):
		"""send mail with login details"""
		from webnotes.profile import get_user_fullname
		from webnotes.utils import get_url
		
		mail_titles = webnotes.get_hooks().get("login_mail_title", [])
		title = webnotes.conn.get_default('company') or (mail_titles and mail_titles[0]) or ""
		
		full_name = get_user_fullname(webnotes.session['user'])
		if full_name == "Guest":
			full_name = "Administrator"
	
		args = {
			'first_name': self.doc.first_name or self.doc.last_name or "user",
			'user': self.doc.name,
			'title': title,
			'login_url': get_url(),
			'user_fullname': full_name
		}
		
		args.update(add_args)
		
		sender = webnotes.session.user not in ("Administrator", "Guest") and webnotes.session.user or None
		
		webnotes.sendmail(recipients=self.doc.email, sender=sender, subject=subject, 
			message=webnotes.get_template(template).render(args))
Exemplo n.º 3
0
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
Exemplo n.º 4
0
def get_messages_from_include_files(app_name=None):
	messages = []
	hooks = webnotes.get_hooks(app_name)
	for file in (hooks.app_include_js or []) + (hooks.web_include_js or []):
		messages.extend(get_messages_from_file(os.path.join(webnotes.local.sites_path, file)))
		
	return messages
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
Exemplo n.º 6
0
def get_context(context):
	hooks = webnotes.get_hooks()
	return {
		"build_version": str(os.path.getmtime(os.path.join(webnotes.local.sites_path, "assets", "js", 
			"webnotes.min.js"))),
		"include_js": hooks["app_include_js"],
		"include_css": hooks["app_include_css"]
	}
Exemplo n.º 7
0
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
Exemplo n.º 8
0
	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
Exemplo n.º 9
0
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
Exemplo n.º 10
0
def build(page_name):
	if not webnotes.conn:
		webnotes.connect()
	
	build_method = (build_json if is_ajax() else build_page)
	try:
		return build_method(page_name)

	except webnotes.DoesNotExistError:
		hooks = webnotes.get_hooks()
		if hooks.website_catch_all:
			return build_method(hooks.website_catch_all[0])
		else:
			return build_method("404")
Exemplo n.º 11
0
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)
Exemplo n.º 12
0
def get_app_list():
	out = {}
	installed = webnotes.get_installed_apps()
	for app in webnotes.get_all_apps(True):
		out[app] = {}
		app_hooks = webnotes.get_hooks(app_name=app)
		for key in ("app_name", "app_title", "app_description", "app_icon",
			"app_publisher", "app_version", "app_url", "app_color"):
			 val = app_hooks.get(key) or []
			 out[app][key] = val[0] if len(val) else ""
			
		if app in installed:
			out[app]["installed"] = 1
		
	return out
Exemplo n.º 13
0
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)
Exemplo n.º 14
0
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"
Exemplo n.º 15
0
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
Exemplo n.º 16
0
def load_startup_js(bootinfo):
	bootinfo.startup_js = ""
	for method in webnotes.get_hooks().startup_js or []:
		bootinfo.startup_js += webnotes.get_attr(method)()
Exemplo n.º 17
0
	def run_trigger(self, method='on_login'):
		for method in webnotes.get_hooks().get("method", []):
			webnotes.get_attr(method)(self)
Exemplo n.º 18
0
def get_handler(group_type):
	handler = webnotes.get_hooks("website_group_handler:{}".format(group_type))
	if handler:
		return webnotes.get_module(handler[0])
Exemplo n.º 19
0
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