You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

468 regels
13 KiB

  1. # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
  2. # MIT License. See license.txt
  3. from __future__ import unicode_literals
  4. import webnotes
  5. import json, os, time, re
  6. from webnotes import _
  7. import webnotes.utils
  8. from webnotes.utils import get_request_site_address, encode, cint
  9. from webnotes.model import default_fields
  10. from webnotes.model.controller import DocListController
  11. from urllib import quote
  12. import mimetypes
  13. from webnotes.website.doctype.website_sitemap.website_sitemap import add_to_sitemap, update_sitemap, remove_sitemap
  14. # frequently used imports (used by other modules)
  15. from webnotes.website.doctype.website_sitemap_permission.website_sitemap_permission \
  16. import get_access, clear_permissions
  17. class PageNotFoundError(Exception): pass
  18. def render(path):
  19. """render html page"""
  20. path = resolve_path(path)
  21. try:
  22. data = render_page(path)
  23. except Exception:
  24. path = "error"
  25. data = render_page(path)
  26. data = set_content_type(data, path)
  27. webnotes._response.data = data
  28. webnotes._response.headers[b"Page Name"] = path.encode("utf-8")
  29. def render_page(path):
  30. """get page html"""
  31. cache_key = ("page_context:{}" if is_ajax() else "page:{}").format(path)
  32. out = None
  33. # try memcache
  34. if can_cache():
  35. out = webnotes.cache().get_value(cache_key)
  36. if out and is_ajax():
  37. out = out.get("data")
  38. if out:
  39. if hasattr(webnotes, "_response"):
  40. webnotes._response.headers[b"From Cache"] = True
  41. return out
  42. return build(path)
  43. def build(path):
  44. if not webnotes.conn:
  45. webnotes.connect()
  46. build_method = (build_json if is_ajax() else build_page)
  47. try:
  48. return build_method(path)
  49. except webnotes.DoesNotExistError:
  50. hooks = webnotes.get_hooks()
  51. if hooks.website_catch_all:
  52. return build_method(hooks.website_catch_all[0])
  53. else:
  54. return build_method("404")
  55. def build_json(path):
  56. return get_context(path).data
  57. def build_page(path):
  58. context = get_context(path)
  59. html = webnotes.get_template(context.base_template_path).render(context)
  60. html = scrub_relative_urls(html)
  61. if can_cache(context.no_cache):
  62. webnotes.cache().set_value("page:" + path, html)
  63. return html
  64. def get_context(path):
  65. context = None
  66. cache_key = "page_context:{}".format(path)
  67. # try from memcache
  68. if can_cache():
  69. context = webnotes.cache().get_value(cache_key)
  70. if not context:
  71. context = get_sitemap_options(path)
  72. # permission may be required for rendering
  73. context["access"] = get_access(context.pathname)
  74. context = build_context(context)
  75. if can_cache(context.no_cache):
  76. del context["access"]
  77. webnotes.cache().set_value(cache_key, context)
  78. else:
  79. context["access"] = get_access(context.pathname)
  80. context.update(context.data or {})
  81. # TODO private pages
  82. return context
  83. def get_sitemap_options(path):
  84. sitemap_options = None
  85. cache_key = "sitemap_options:{}".format(path)
  86. if can_cache():
  87. sitemap_options = webnotes.cache().get_value(cache_key)
  88. if not sitemap_options:
  89. sitemap_options = build_sitemap_options(path)
  90. if can_cache(sitemap_options.no_cache):
  91. webnotes.cache().set_value(cache_key, sitemap_options)
  92. return sitemap_options
  93. def build_sitemap_options(path):
  94. sitemap_options = webnotes.doc("Website Sitemap", path).fields
  95. sitemap_config = webnotes.doc("Website Sitemap Config",
  96. sitemap_options.get("website_sitemap_config")).fields
  97. # get sitemap config fields too
  98. for fieldname in ("base_template_path", "template_path", "controller", "no_cache", "no_sitemap",
  99. "page_name_field", "condition_field"):
  100. sitemap_options[fieldname] = sitemap_config.get(fieldname)
  101. sitemap_options.doctype = sitemap_options.ref_doctype
  102. sitemap_options.title = sitemap_options.page_title
  103. sitemap_options.pathname = sitemap_options.name
  104. # establish hierarchy
  105. sitemap_options.parents = webnotes.conn.sql("""select name, page_title from `tabWebsite Sitemap`
  106. where lft < %s and rgt > %s order by lft asc""", (sitemap_options.lft, sitemap_options.rgt), as_dict=True)
  107. sitemap_options.children = webnotes.conn.sql("""select * from `tabWebsite Sitemap`
  108. where parent_website_sitemap=%s
  109. and public_read=1 order by idx asc""", (sitemap_options.name,), as_dict=True)
  110. # determine templates to be used
  111. if not sitemap_options.base_template_path:
  112. sitemap_options.base_template_path = "templates/base.html"
  113. return sitemap_options
  114. def build_context(sitemap_options):
  115. """get_context method of bean or module is supposed to render content templates and push it into context"""
  116. context = webnotes._dict(sitemap_options)
  117. context.update(get_website_settings())
  118. # provide bean
  119. if context.doctype and context.docname:
  120. context.bean = webnotes.bean(context.doctype, context.docname)
  121. if context.controller:
  122. module = webnotes.get_module(context.controller)
  123. if module and hasattr(module, "get_context"):
  124. context.update(module.get_context(context) or {})
  125. if context.get("base_template_path") != context.get("template_path") and not context.get("rendered"):
  126. context.data = render_blocks(context)
  127. # remove bean, as it is not pickle friendly and its purpose is over
  128. if context.bean:
  129. del context["bean"]
  130. return context
  131. def can_cache(no_cache=False):
  132. return not (webnotes.conf.disable_website_cache or no_cache)
  133. def get_home_page():
  134. home_page = webnotes.cache().get_value("home_page", \
  135. lambda: (webnotes.get_hooks("home_page") \
  136. or [webnotes.conn.get_value("Website Settings", None, "home_page") \
  137. or "login"])[0])
  138. return home_page
  139. def get_website_settings():
  140. # TODO Cache this
  141. hooks = webnotes.get_hooks()
  142. all_top_items = webnotes.conn.sql("""\
  143. select * from `tabTop Bar Item`
  144. where parent='Website Settings' and parentfield='top_bar_items'
  145. order by idx asc""", as_dict=1)
  146. top_items = [d for d in all_top_items if not d['parent_label']]
  147. # attach child items to top bar
  148. for d in all_top_items:
  149. if d['parent_label']:
  150. for t in top_items:
  151. if t['label']==d['parent_label']:
  152. if not 'child_items' in t:
  153. t['child_items'] = []
  154. t['child_items'].append(d)
  155. break
  156. context = webnotes._dict({
  157. 'top_bar_items': top_items,
  158. 'footer_items': webnotes.conn.sql("""\
  159. select * from `tabTop Bar Item`
  160. where parent='Website Settings' and parentfield='footer_items'
  161. order by idx asc""", as_dict=1),
  162. "post_login": [
  163. {"label": "Reset Password", "url": "update-password", "icon": "icon-key"},
  164. {"label": "Logout", "url": "?cmd=web_logout", "icon": "icon-signout"}
  165. ]
  166. })
  167. settings = webnotes.doc("Website Settings", "Website Settings")
  168. for k in ["banner_html", "brand_html", "copyright", "twitter_share_via",
  169. "favicon", "facebook_share", "google_plus_one", "twitter_share", "linked_in_share",
  170. "disable_signup"]:
  171. if k in settings.fields:
  172. context[k] = settings.fields.get(k)
  173. if settings.address:
  174. context["footer_address"] = settings.address
  175. for k in ["facebook_share", "google_plus_one", "twitter_share", "linked_in_share",
  176. "disable_signup"]:
  177. context[k] = cint(context.get(k) or 0)
  178. context.url = quote(str(get_request_site_address(full_address=True)), safe="/:")
  179. context.encoded_title = quote(encode(context.title or ""), str(""))
  180. for update_website_context in hooks.update_website_context or []:
  181. webnotes.get_attr(update_website_context)(context)
  182. context.web_include_js = hooks.web_include_js or []
  183. context.web_include_css = hooks.web_include_css or []
  184. # get settings from site config
  185. if webnotes.conf.get("fb_app_id"):
  186. context.fb_app_id = webnotes.conf.fb_app_id
  187. return context
  188. def is_ajax():
  189. return webnotes.get_request_header("X-Requested-With")=="XMLHttpRequest"
  190. def resolve_path(path):
  191. if not path:
  192. path = "index"
  193. if path.endswith('.html'):
  194. path = path[:-5]
  195. if path == "index":
  196. path = get_home_page()
  197. return path
  198. def set_content_type(data, path):
  199. if isinstance(data, dict):
  200. webnotes._response.headers[b"Content-Type"] = b"application/json; charset: utf-8"
  201. data = json.dumps(data)
  202. return data
  203. webnotes._response.headers[b"Content-Type"] = b"text/html; charset: utf-8"
  204. if "." in path and not path.endswith(".html"):
  205. content_type, encoding = mimetypes.guess_type(path)
  206. webnotes._response.headers[b"Content-Type"] = content_type.encode("utf-8")
  207. return data
  208. def clear_cache(path=None):
  209. cache = webnotes.cache()
  210. if path:
  211. delete_page_cache(path)
  212. else:
  213. for p in webnotes.conn.sql_list("""select name from `tabWebsite Sitemap`"""):
  214. if p is not None:
  215. delete_page_cache(p)
  216. cache.delete_value("home_page")
  217. clear_permissions()
  218. for method in webnotes.get_hooks("website_clear_cache"):
  219. webnotes.get_attr(method)(path)
  220. def delete_page_cache(path):
  221. cache = webnotes.cache()
  222. cache.delete_value("page:" + path)
  223. cache.delete_value("page_context:" + path)
  224. cache.delete_value("sitemap_options:" + path)
  225. def is_signup_enabled():
  226. if getattr(webnotes.local, "is_signup_enabled", None) is None:
  227. webnotes.local.is_signup_enabled = True
  228. if webnotes.utils.cint(webnotes.conn.get_value("Website Settings",
  229. "Website Settings", "disable_signup")):
  230. webnotes.local.is_signup_enabled = False
  231. return webnotes.local.is_signup_enabled
  232. def call_website_generator(bean, method, *args, **kwargs):
  233. getattr(WebsiteGenerator(bean.doc, bean.doclist), method)(*args, **kwargs)
  234. class WebsiteGenerator(DocListController):
  235. def autoname(self):
  236. from webnotes.webutils import cleanup_page_name
  237. self.doc.name = cleanup_page_name(self.get_page_title())
  238. def set_page_name(self):
  239. """set page name based on parent page_name and title"""
  240. page_name = cleanup_page_name(self.get_page_title())
  241. if self.doc.is_new():
  242. self.doc.fields[self._website_config.page_name_field] = page_name
  243. else:
  244. webnotes.conn.set(self.doc, self._website_config.page_name_field, page_name)
  245. def setup_generator(self):
  246. if webnotes.flags.in_install_app:
  247. return
  248. self._website_config = webnotes.conn.get_values("Website Sitemap Config",
  249. {"ref_doctype": self.doc.doctype}, "*")[0]
  250. def on_update(self):
  251. self.update_sitemap()
  252. def after_rename(self, olddn, newdn, merge):
  253. webnotes.conn.sql("""update `tabWebsite Sitemap`
  254. set docname=%s where ref_doctype=%s and docname=%s""", (newdn, self.doc.doctype, olddn))
  255. if merge:
  256. self.setup_generator()
  257. remove_sitemap(ref_doctype=self.doc.doctype, docname=olddn)
  258. def on_trash(self):
  259. self.setup_generator()
  260. remove_sitemap(ref_doctype=self.doc.doctype, docname=self.doc.name)
  261. def update_sitemap(self):
  262. if webnotes.flags.in_install_app:
  263. return
  264. self.setup_generator()
  265. if self._website_config.condition_field and \
  266. not self.doc.fields.get(self._website_config.condition_field):
  267. # condition field failed, remove and return!
  268. remove_sitemap(ref_doctype=self.doc.doctype, docname=self.doc.name)
  269. return
  270. self.add_or_update_sitemap()
  271. def add_or_update_sitemap(self):
  272. page_name = self.get_page_name()
  273. existing_site_map = webnotes.conn.get_value("Website Sitemap", {"ref_doctype": self.doc.doctype,
  274. "docname": self.doc.name})
  275. opts = webnotes._dict({
  276. "page_or_generator": "Generator",
  277. "ref_doctype":self.doc.doctype,
  278. "docname": self.doc.name,
  279. "page_name": page_name,
  280. "link_name": self._website_config.name,
  281. "lastmod": webnotes.utils.get_datetime(self.doc.modified).strftime("%Y-%m-%d"),
  282. "parent_website_sitemap": self.doc.parent_website_sitemap,
  283. "page_title": self.get_page_title()
  284. })
  285. self.update_permissions(opts)
  286. if existing_site_map:
  287. update_sitemap(existing_site_map, opts)
  288. else:
  289. add_to_sitemap(opts)
  290. def update_permissions(self, opts):
  291. if self.meta.get_field("public_read"):
  292. opts.public_read = self.doc.public_read
  293. opts.public_write = self.doc.public_write
  294. else:
  295. opts.public_read = 1
  296. def get_page_name(self):
  297. if not self._get_page_name():
  298. self.set_page_name()
  299. return self._get_page_name()
  300. def _get_page_name(self):
  301. return self.doc.fields.get(self._website_config.page_name_field)
  302. def get_page_title(self):
  303. return self.doc.title or (self.doc.name.replace("-", " ").replace("_", " ").title())
  304. def cleanup_page_name(title):
  305. """make page name from title"""
  306. import re
  307. name = title.lower()
  308. name = re.sub('[~!@#$%^&*+()<>,."\'\?]', '', name)
  309. name = re.sub('[:/]', '-', name)
  310. name = '-'.join(name.split())
  311. # replace repeating hyphens
  312. name = re.sub(r"(-)\1+", r"\1", name)
  313. return name
  314. def get_hex_shade(color, percent):
  315. def p(c):
  316. v = int(c, 16) + int(int('ff', 16) * (float(percent)/100))
  317. if v < 0:
  318. v=0
  319. if v > 255:
  320. v=255
  321. h = hex(v)[2:]
  322. if len(h) < 2:
  323. h = "0" + h
  324. return h
  325. r, g, b = color[0:2], color[2:4], color[4:6]
  326. avg = (float(int(r, 16) + int(g, 16) + int(b, 16)) / 3)
  327. # switch dark and light shades
  328. if avg > 128:
  329. percent = -percent
  330. # stronger diff for darker shades
  331. if percent < 25 and avg < 64:
  332. percent = percent * 2
  333. return p(r) + p(g) + p(b)
  334. def render_blocks(context):
  335. """returns a dict of block name and its rendered content"""
  336. from jinja2.utils import concat
  337. out = {}
  338. template = webnotes.get_template(context["template_path"])
  339. # required as per low level API
  340. context = template.new_context(context)
  341. # render each block individually
  342. for block, render in template.blocks.items():
  343. out[block] = scrub_relative_urls(concat(render(context)))
  344. return out
  345. def scrub_relative_urls(html):
  346. """prepend a slash before a relative url"""
  347. return re.sub("""(src|href)[^\w'"]*['"](?!http|ftp|/|#)([^'" >]+)['"]""", '\g<1> = "/\g<2>"', html)