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 desc, page_title asc""", (sitemap_options.pathname,), as_dict=True)
  110. # leaf node, show siblings
  111. if not sitemap_options.children:
  112. sitemap_options.children = webnotes.conn.sql("""select * from `tabWebsite Sitemap`
  113. where ifnull(parent_website_sitemap, '')=%s
  114. and public_read=1 order by -idx desc, page_title asc""",
  115. sitemap_options.parent_website_sitemap or "", as_dict=True)
  116. # determine templates to be used
  117. if not sitemap_options.base_template_path:
  118. sitemap_options.base_template_path = "templates/base.html"
  119. return sitemap_options
  120. def build_context(sitemap_options):
  121. """get_context method of bean or module is supposed to render content templates and push it into context"""
  122. context = webnotes._dict(sitemap_options)
  123. context.update(get_website_settings())
  124. # provide bean
  125. if context.doctype and context.docname:
  126. context.bean = webnotes.bean(context.doctype, context.docname)
  127. if context.controller:
  128. module = webnotes.get_module(context.controller)
  129. if module and hasattr(module, "get_context"):
  130. context.update(module.get_context(context) or {})
  131. if context.get("base_template_path") != context.get("template_path") and not context.get("rendered"):
  132. context.data = render_blocks(context)
  133. # remove bean, as it is not pickle friendly and its purpose is over
  134. if context.bean:
  135. del context["bean"]
  136. return context
  137. def can_cache(no_cache=False):
  138. return not (webnotes.conf.disable_website_cache or no_cache)
  139. def get_home_page():
  140. home_page = webnotes.cache().get_value("home_page", \
  141. lambda: (webnotes.get_hooks("home_page") \
  142. or [webnotes.conn.get_value("Website Settings", None, "home_page") \
  143. or "login"])[0])
  144. print home_page
  145. return home_page
  146. def get_website_settings():
  147. # TODO Cache this
  148. hooks = webnotes.get_hooks()
  149. all_top_items = webnotes.conn.sql("""\
  150. select * from `tabTop Bar Item`
  151. where parent='Website Settings' and parentfield='top_bar_items'
  152. order by idx asc""", as_dict=1)
  153. top_items = [d for d in all_top_items if not d['parent_label']]
  154. # attach child items to top bar
  155. for d in all_top_items:
  156. if d['parent_label']:
  157. for t in top_items:
  158. if t['label']==d['parent_label']:
  159. if not 'child_items' in t:
  160. t['child_items'] = []
  161. t['child_items'].append(d)
  162. break
  163. context = webnotes._dict({
  164. 'top_bar_items': top_items,
  165. 'footer_items': webnotes.conn.sql("""\
  166. select * from `tabTop Bar Item`
  167. where parent='Website Settings' and parentfield='footer_items'
  168. order by idx asc""", as_dict=1),
  169. "post_login": [
  170. {"label": "Reset Password", "url": "update-password", "icon": "icon-key"},
  171. {"label": "Logout", "url": "?cmd=web_logout", "icon": "icon-signout"}
  172. ]
  173. })
  174. settings = webnotes.doc("Website Settings", "Website Settings")
  175. for k in ["banner_html", "brand_html", "copyright", "twitter_share_via",
  176. "favicon", "facebook_share", "google_plus_one", "twitter_share", "linked_in_share",
  177. "disable_signup"]:
  178. if k in settings.fields:
  179. context[k] = settings.fields.get(k)
  180. if settings.address:
  181. context["footer_address"] = settings.address
  182. for k in ["facebook_share", "google_plus_one", "twitter_share", "linked_in_share",
  183. "disable_signup"]:
  184. context[k] = cint(context.get(k) or 0)
  185. context.url = quote(str(get_request_site_address(full_address=True)), safe="/:")
  186. context.encoded_title = quote(encode(context.title or ""), str(""))
  187. for update_website_context in hooks.update_website_context or []:
  188. webnotes.get_attr(update_website_context)(context)
  189. context.web_include_js = hooks.web_include_js or []
  190. context.web_include_css = hooks.web_include_css or []
  191. return context
  192. def is_ajax():
  193. return webnotes.get_request_header("X-Requested-With")=="XMLHttpRequest"
  194. def resolve_path(path):
  195. if not path:
  196. path = "index"
  197. if path.endswith('.html'):
  198. path = path[:-5]
  199. if path == "index":
  200. path = get_home_page()
  201. return path
  202. def set_content_type(data, path):
  203. if isinstance(data, dict):
  204. webnotes._response.headers[b"Content-Type"] = b"application/json; charset: utf-8"
  205. data = json.dumps(data)
  206. return data
  207. webnotes._response.headers[b"Content-Type"] = b"text/html; charset: utf-8"
  208. if "." in path and not path.endswith(".html"):
  209. content_type, encoding = mimetypes.guess_type(path)
  210. webnotes._response.headers[b"Content-Type"] = content_type.encode("utf-8")
  211. return data
  212. def clear_cache(path=None):
  213. cache = webnotes.cache()
  214. if path:
  215. delete_page_cache(path)
  216. else:
  217. for p in webnotes.conn.sql_list("""select name from `tabWebsite Sitemap`"""):
  218. if p is not None:
  219. delete_page_cache(p)
  220. cache.delete_value("home_page")
  221. clear_permissions()
  222. for method in webnotes.get_hooks("website_clear_cache"):
  223. webnotes.get_attr(method)(path)
  224. def delete_page_cache(path):
  225. cache = webnotes.cache()
  226. cache.delete_value("page:" + path)
  227. cache.delete_value("page_context:" + path)
  228. cache.delete_value("sitemap_options:" + path)
  229. def is_signup_enabled():
  230. if getattr(webnotes.local, "is_signup_enabled", None) is None:
  231. webnotes.local.is_signup_enabled = True
  232. if webnotes.utils.cint(webnotes.conn.get_value("Website Settings",
  233. "Website Settings", "disable_signup")):
  234. webnotes.local.is_signup_enabled = False
  235. return webnotes.local.is_signup_enabled
  236. def call_website_generator(bean, method, *args, **kwargs):
  237. getattr(WebsiteGenerator(bean.doc, bean.doclist), method)(*args, **kwargs)
  238. class WebsiteGenerator(DocListController):
  239. def autoname(self):
  240. from webnotes.webutils import cleanup_page_name
  241. self.doc.name = cleanup_page_name(self.get_page_title())
  242. def set_page_name(self):
  243. """set page name based on parent page_name and title"""
  244. page_name = cleanup_page_name(self.get_page_title())
  245. if self.doc.is_new():
  246. self.doc.fields[self._website_config.page_name_field] = page_name
  247. else:
  248. webnotes.conn.set(self.doc, self._website_config.page_name_field, page_name)
  249. def setup_generator(self):
  250. self._website_config = webnotes.conn.get_values("Website Sitemap Config",
  251. {"ref_doctype": self.doc.doctype}, "*")[0]
  252. def on_update(self):
  253. self.update_sitemap()
  254. def after_rename(self, olddn, newdn, merge):
  255. webnotes.conn.sql("""update `tabWebsite Sitemap`
  256. set docname=%s where ref_doctype=%s and docname=%s""", (newdn, self.doc.doctype, olddn))
  257. if merge:
  258. self.setup_generator()
  259. remove_sitemap(ref_doctype=self.doc.doctype, docname=olddn)
  260. def on_trash(self):
  261. self.setup_generator()
  262. remove_sitemap(ref_doctype=self.doc.doctype, docname=self.doc.name)
  263. def update_sitemap(self):
  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)